text
stringlengths
5
1.04M
#include "huaweicloud/ecs/v2/model/DeleteServersRequestBody.h" namespace HuaweiCloud { namespace Sdk { namespace Ecs { namespace V2 { namespace Model { DeleteServersRequestBody::DeleteServersRequestBody() { deletePublicip_ = false; deletePublicipIsSet_ = false; deleteVolume_ = false; deleteVolumeIsSet_ = false; serversIsSet_ = false; } DeleteServersRequestBody::~DeleteServersRequestBody() = default; void DeleteServersRequestBody::validate() { } web::json::value DeleteServersRequestBody::toJson() const { web::json::value val = web::json::value::object(); if(deletePublicipIsSet_) { val[utility::conversions::to_string_t("delete_publicip")] = ModelBase::toJson(deletePublicip_); } if(deleteVolumeIsSet_) { val[utility::conversions::to_string_t("delete_volume")] = ModelBase::toJson(deleteVolume_); } if(serversIsSet_) { val[utility::conversions::to_string_t("servers")] = ModelBase::toJson(servers_); } return val; } bool DeleteServersRequestBody::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("delete_publicip"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("delete_publicip")); if(!fieldValue.is_null()) { bool refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDeletePublicip(refVal); } } if(val.has_field(utility::conversions::to_string_t("delete_volume"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("delete_volume")); if(!fieldValue.is_null()) { bool refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDeleteVolume(refVal); } } if(val.has_field(utility::conversions::to_string_t("servers"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("servers")); if(!fieldValue.is_null()) { std::vector<ServerId> refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setServers(refVal); } } return ok; } bool DeleteServersRequestBody::isDeletePublicip() const { return deletePublicip_; } void DeleteServersRequestBody::setDeletePublicip(bool value) { deletePublicip_ = value; deletePublicipIsSet_ = true; } bool DeleteServersRequestBody::deletePublicipIsSet() const { return deletePublicipIsSet_; } void DeleteServersRequestBody::unsetdeletePublicip() { deletePublicipIsSet_ = false; } bool DeleteServersRequestBody::isDeleteVolume() const { return deleteVolume_; } void DeleteServersRequestBody::setDeleteVolume(bool value) { deleteVolume_ = value; deleteVolumeIsSet_ = true; } bool DeleteServersRequestBody::deleteVolumeIsSet() const { return deleteVolumeIsSet_; } void DeleteServersRequestBody::unsetdeleteVolume() { deleteVolumeIsSet_ = false; } std::vector<ServerId>& DeleteServersRequestBody::getServers() { return servers_; } void DeleteServersRequestBody::setServers(const std::vector<ServerId>& value) { servers_ = value; serversIsSet_ = true; } bool DeleteServersRequestBody::serversIsSet() const { return serversIsSet_; } void DeleteServersRequestBody::unsetservers() { serversIsSet_ = false; } } } } } }
/**************************************************************************** * * Copyright (c) 2013-2015 PX4 Development Team. 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. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE * COPYRIGHT OWNER 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. * ****************************************************************************/ /** * @file mc_att_control_main.cpp * Multicopter attitude controller. * * Publication for the desired attitude tracking: * Daniel Mellinger and Vijay Kumar. Minimum Snap Trajectory Generation and Control for Quadrotors. * Int. Conf. on Robotics and Automation, Shanghai, China, May 2011. * * @author Lorenz Meier <lorenz@px4.io> * @author Anton Babushkin <anton.babushkin@me.com> * @author Sander Smeets <sander@droneslab.com> * * The controller has two loops: P loop for angular error and PD loop for angular rate error. * Desired rotation calculated keeping in mind that yaw response is normally slower than roll/pitch. * For small deviations controller rotates copter to have shortest path of thrust vector and independently rotates around yaw, * so actual rotation axis is not constant. For large deviations controller rotates copter around fixed axis. * These two approaches fused seamlessly with weight depending on angular error. * When thrust vector directed near-horizontally (e.g. roll ~= PI/2) yaw setpoint ignored because of singularity. * Controller doesn't use Euler angles for work, they generated only for more human-friendly control and logging. * If rotation matrix setpoint is invalid it will be generated from Euler angles for compatibility with old position controllers. */ #include <px4_config.h> #include <px4_defines.h> #include <px4_tasks.h> #include <px4_posix.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <math.h> #include <poll.h> #include <drivers/drv_hrt.h> #include <arch/board/board.h> #include <uORB/uORB.h> #include <uORB/topics/vehicle_attitude_setpoint.h> #include <uORB/topics/manual_control_setpoint.h> #include <uORB/topics/actuator_controls.h> #include <uORB/topics/vehicle_rates_setpoint.h> #include <uORB/topics/fw_virtual_rates_setpoint.h> #include <uORB/topics/mc_virtual_rates_setpoint.h> #include <uORB/topics/control_state.h> #include <uORB/topics/vehicle_control_mode.h> #include <uORB/topics/vehicle_status.h> #include <uORB/topics/actuator_armed.h> #include <uORB/topics/parameter_update.h> #include <uORB/topics/multirotor_motor_limits.h> #include <uORB/topics/mc_att_ctrl_status.h> #include <systemlib/param/param.h> #include <systemlib/err.h> #include <systemlib/perf_counter.h> #include <systemlib/systemlib.h> #include <systemlib/circuit_breaker.h> #include <lib/mathlib/mathlib.h> #include <lib/geo/geo.h> #include <lib/tailsitter_recovery/tailsitter_recovery.h> //custom #include <uORB/topics/sensor_accel.h> #include <uORB/topics/impact_recovery_stage.h> #include <uORB/topics/impact_characterization.h> #include <uORB/topics/recovery_control.h> /** * Multicopter attitude control app start / stop handling function * * @ingroup apps */ extern "C" __EXPORT int mc_att_control_main(int argc, char *argv[]); #define YAW_DEADZONE 0.05f #define MIN_TAKEOFF_THRUST 0.2f #define RATES_I_LIMIT 0.3f #define MANUAL_THROTTLE_MAX_MULTICOPTER 0.9f #define ATTITUDE_TC_DEFAULT 0.2f #define AXIS_INDEX_ROLL 0 #define AXIS_INDEX_PITCH 1 #define AXIS_INDEX_YAW 2 #define AXIS_COUNT 3 class MulticopterAttitudeControl { public: /** * Constructor */ MulticopterAttitudeControl(); /** * Destructor, also kills the main task */ ~MulticopterAttitudeControl(); /** * Start the multicopter attitude control task. * * @return OK on success. */ int start(); private: bool _task_should_exit; /**< if true, task_main() should exit */ int _control_task; /**< task handle */ int _ctrl_state_sub; /**< control state subscription */ int _v_att_sp_sub; /**< vehicle attitude setpoint subscription */ int _v_rates_sp_sub; /**< vehicle rates setpoint subscription */ int _v_control_mode_sub; /**< vehicle control mode subscription */ int _params_sub; /**< parameter updates subscription */ int _manual_control_sp_sub; /**< manual control setpoint subscription */ int _armed_sub; /**< arming status subscription */ int _vehicle_status_sub; /**< vehicle status subscription */ int _motor_limits_sub; /**< motor limits subscription */ //custom int _sensor_accel_sub; int _recovery_stage_sub; int _characterization_sub; orb_advert_t _v_rates_sp_pub; /**< rate setpoint publication */ orb_advert_t _actuators_0_pub; /**< attitude actuator controls publication */ orb_advert_t _controller_status_pub; /**< controller status publication */ orb_advert_t _recovery_control_pub; orb_id_t _rates_sp_id; /**< pointer to correct rates setpoint uORB metadata structure */ orb_id_t _actuators_id; /**< pointer to correct actuator controls0 uORB metadata structure */ //custom bool _actuators_0_circuit_breaker_enabled; /**< circuit breaker to suppress output */ struct control_state_s _ctrl_state; /**< control state */ struct vehicle_attitude_setpoint_s _v_att_sp; /**< vehicle attitude setpoint */ struct vehicle_rates_setpoint_s _v_rates_sp; /**< vehicle rates setpoint */ struct manual_control_setpoint_s _manual_control_sp; /**< manual control setpoint */ struct vehicle_control_mode_s _v_control_mode; /**< vehicle control mode */ struct actuator_controls_s _actuators; /**< actuator controls */ struct actuator_armed_s _armed; /**< actuator arming status */ struct vehicle_status_s _vehicle_status; /**< vehicle status */ struct multirotor_motor_limits_s _motor_limits; /**< motor limits */ struct mc_att_ctrl_status_s _controller_status; /**< controller status */ //custom struct sensor_accel_s _sensor_accel; struct impact_recovery_stage_s _recovery_stage; struct impact_characterization_s _characterization; struct recovery_control_s _recovery_control; perf_counter_t _loop_perf; /**< loop performance counter */ perf_counter_t _controller_latency_perf; math::Vector<3> _rates_prev; /**< angular rates on previous step */ math::Vector<3> _rates_sp_prev; /**< previous rates setpoint */ math::Vector<3> _rates_sp; /**< angular rates setpoint */ math::Vector<3> _rates_int; /**< angular rates integral error */ float _thrust_sp; /**< thrust setpoint */ math::Vector<3> _att_control; /**< attitude control vector */ math::Matrix<3, 3> _I; /**< identity matrix */ struct { param_t roll_p; param_t roll_rate_p; param_t roll_rate_i; param_t roll_rate_d; param_t roll_rate_ff; param_t pitch_p; param_t pitch_rate_p; param_t pitch_rate_i; param_t pitch_rate_d; param_t pitch_rate_ff; param_t yaw_p; param_t yaw_rate_p; param_t yaw_rate_i; param_t yaw_rate_d; param_t yaw_rate_ff; param_t yaw_ff; param_t roll_rate_max; param_t pitch_rate_max; param_t yaw_rate_max; param_t yaw_auto_max; param_t acro_roll_max; param_t acro_pitch_max; param_t acro_yaw_max; param_t rattitude_thres; param_t vtol_type; param_t roll_tc; param_t pitch_tc; param_t vtol_opt_recovery_enabled; param_t vtol_wv_yaw_rate_scale; } _params_handles; /**< handles for interesting parameters */ struct { math::Vector<3> att_p; /**< P gain for angular error */ math::Vector<3> rate_p; /**< P gain for angular rate error */ math::Vector<3> rate_i; /**< I gain for angular rate error */ math::Vector<3> rate_d; /**< D gain for angular rate error */ math::Vector<3> rate_ff; /**< Feedforward gain for desired rates */ float yaw_ff; /**< yaw control feed-forward */ float roll_rate_max; float pitch_rate_max; float yaw_rate_max; float yaw_auto_max; math::Vector<3> mc_rate_max; /**< attitude rate limits in stabilized modes */ math::Vector<3> auto_rate_max; /**< attitude rate limits in auto modes */ math::Vector<3> acro_rate_max; /**< max attitude rates in acro mode */ float rattitude_thres; int vtol_type; /**< 0 = Tailsitter, 1 = Tiltrotor, 2 = Standard airframe */ bool vtol_opt_recovery_enabled; float vtol_wv_yaw_rate_scale; /**< Scale value [0, 1] for yaw rate setpoint */ } _params; TailsitterRecovery *_ts_opt_recovery; /**< Computes optimal rates for tailsitter recovery */ /** * Update our local parameter cache. */ int parameters_update(); /** * Check for parameter update and handle it. */ void parameter_update_poll(); /** * Check for changes in vehicle control mode. */ void vehicle_control_mode_poll(); /** * Check for changes in manual inputs. */ void vehicle_manual_poll(); /** * Check for attitude setpoint updates. */ void vehicle_attitude_setpoint_poll(); /** * Check for rates setpoint updates. */ void vehicle_rates_setpoint_poll(); /** * Check for arming status updates. */ void arming_status_poll(); /** * Attitude controller. */ void control_attitude(float dt); /** * Attitude rates controller. */ void control_attitude_rates(float dt); /** * Check for vehicle status updates. */ void vehicle_status_poll(); /** * Check for vehicle motor limits status. */ void vehicle_motor_limits_poll(); /** * Check for accelerometer sensor data. */ void sensor_accel_poll(); /* * Check for impact detection and characterization updates */ void impact_poll(); /** * Shim for calling task_main from task_create. */ static void task_main_trampoline(int argc, char *argv[]); /** * Main attitude control task. */ void task_main(); }; namespace mc_att_control { MulticopterAttitudeControl *g_control; } MulticopterAttitudeControl::MulticopterAttitudeControl() : _task_should_exit(false), _control_task(-1), /* subscriptions */ _ctrl_state_sub(-1), _v_att_sp_sub(-1), _v_control_mode_sub(-1), _params_sub(-1), _manual_control_sp_sub(-1), _armed_sub(-1), _vehicle_status_sub(-1), //custom _sensor_accel_sub(-1), _recovery_stage_sub(-1), _characterization_sub(-1), /* publications */ _v_rates_sp_pub(nullptr), _actuators_0_pub(nullptr), _controller_status_pub(nullptr), //custom _recovery_control_pub(nullptr), _rates_sp_id(0), _actuators_id(0), _actuators_0_circuit_breaker_enabled(false), /* performance counters */ _loop_perf(perf_alloc(PC_ELAPSED, "mc_att_control")), _controller_latency_perf(perf_alloc_once(PC_ELAPSED, "ctrl_latency")), _ts_opt_recovery(nullptr) { memset(&_ctrl_state, 0, sizeof(_ctrl_state)); memset(&_v_att_sp, 0, sizeof(_v_att_sp)); memset(&_v_rates_sp, 0, sizeof(_v_rates_sp)); memset(&_manual_control_sp, 0, sizeof(_manual_control_sp)); memset(&_v_control_mode, 0, sizeof(_v_control_mode)); memset(&_actuators, 0, sizeof(_actuators)); memset(&_armed, 0, sizeof(_armed)); memset(&_vehicle_status, 0, sizeof(_vehicle_status)); memset(&_motor_limits, 0, sizeof(_motor_limits)); memset(&_controller_status, 0, sizeof(_controller_status)); //custom memset(&_sensor_accel, 0, sizeof(_sensor_accel)); memset(&_recovery_stage_sub, 0, sizeof(_recovery_stage_sub)); memset(&_characterization_sub, 0, sizeof(_characterization_sub)); memset(&_recovery_control, 0, sizeof(_recovery_control)); _vehicle_status.is_rotary_wing = true; _params.att_p.zero(); _params.rate_p.zero(); _params.rate_i.zero(); _params.rate_d.zero(); _params.rate_ff.zero(); _params.yaw_ff = 0.0f; _params.roll_rate_max = 0.0f; _params.pitch_rate_max = 0.0f; _params.yaw_rate_max = 0.0f; _params.mc_rate_max.zero(); _params.auto_rate_max.zero(); _params.acro_rate_max.zero(); _params.rattitude_thres = 1.0f; _params.vtol_opt_recovery_enabled = false; _params.vtol_wv_yaw_rate_scale = 1.0f; _rates_prev.zero(); _rates_sp.zero(); _rates_sp_prev.zero(); _rates_int.zero(); _thrust_sp = 0.0f; _att_control.zero(); _I.identity(); _params_handles.roll_p = param_find("MC_ROLL_P"); _params_handles.roll_rate_p = param_find("MC_ROLLRATE_P"); _params_handles.roll_rate_i = param_find("MC_ROLLRATE_I"); _params_handles.roll_rate_d = param_find("MC_ROLLRATE_D"); _params_handles.roll_rate_ff = param_find("MC_ROLLRATE_FF"); _params_handles.pitch_p = param_find("MC_PITCH_P"); _params_handles.pitch_rate_p = param_find("MC_PITCHRATE_P"); _params_handles.pitch_rate_i = param_find("MC_PITCHRATE_I"); _params_handles.pitch_rate_d = param_find("MC_PITCHRATE_D"); _params_handles.pitch_rate_ff = param_find("MC_PITCHRATE_FF"); _params_handles.yaw_p = param_find("MC_YAW_P"); _params_handles.yaw_rate_p = param_find("MC_YAWRATE_P"); _params_handles.yaw_rate_i = param_find("MC_YAWRATE_I"); _params_handles.yaw_rate_d = param_find("MC_YAWRATE_D"); _params_handles.yaw_rate_ff = param_find("MC_YAWRATE_FF"); _params_handles.yaw_ff = param_find("MC_YAW_FF"); _params_handles.roll_rate_max = param_find("MC_ROLLRATE_MAX"); _params_handles.pitch_rate_max = param_find("MC_PITCHRATE_MAX"); _params_handles.yaw_rate_max = param_find("MC_YAWRATE_MAX"); _params_handles.yaw_auto_max = param_find("MC_YAWRAUTO_MAX"); _params_handles.acro_roll_max = param_find("MC_ACRO_R_MAX"); _params_handles.acro_pitch_max = param_find("MC_ACRO_P_MAX"); _params_handles.acro_yaw_max = param_find("MC_ACRO_Y_MAX"); _params_handles.rattitude_thres = param_find("MC_RATT_TH"); _params_handles.vtol_type = param_find("VT_TYPE"); _params_handles.roll_tc = param_find("MC_ROLL_TC"); _params_handles.pitch_tc = param_find("MC_PITCH_TC"); _params_handles.vtol_opt_recovery_enabled = param_find("VT_OPT_RECOV_EN"); _params_handles.vtol_wv_yaw_rate_scale = param_find("VT_WV_YAWR_SCL"); /* fetch initial parameter values */ parameters_update(); if (_params.vtol_type == 0 && _params.vtol_opt_recovery_enabled) { // the vehicle is a tailsitter, use optimal recovery control strategy _ts_opt_recovery = new TailsitterRecovery(); } } MulticopterAttitudeControl::~MulticopterAttitudeControl() { if (_control_task != -1) { /* task wakes up every 100ms or so at the longest */ _task_should_exit = true; /* wait for a second for the task to quit at our request */ unsigned i = 0; do { /* wait 20ms */ usleep(20000); /* if we have given up, kill it */ if (++i > 50) { px4_task_delete(_control_task); break; } } while (_control_task != -1); } if (_ts_opt_recovery != nullptr) { delete _ts_opt_recovery; } mc_att_control::g_control = nullptr; } int MulticopterAttitudeControl::parameters_update() { float v; float roll_tc, pitch_tc; param_get(_params_handles.roll_tc, &roll_tc); param_get(_params_handles.pitch_tc, &pitch_tc); /* roll gains */ param_get(_params_handles.roll_p, &v); _params.att_p(0) = v * (ATTITUDE_TC_DEFAULT / roll_tc); param_get(_params_handles.roll_rate_p, &v); _params.rate_p(0) = v * (ATTITUDE_TC_DEFAULT / roll_tc); param_get(_params_handles.roll_rate_i, &v); _params.rate_i(0) = v; param_get(_params_handles.roll_rate_d, &v); _params.rate_d(0) = v * (ATTITUDE_TC_DEFAULT / roll_tc); param_get(_params_handles.roll_rate_ff, &v); _params.rate_ff(0) = v; /* pitch gains */ param_get(_params_handles.pitch_p, &v); _params.att_p(1) = v * (ATTITUDE_TC_DEFAULT / pitch_tc); param_get(_params_handles.pitch_rate_p, &v); _params.rate_p(1) = v * (ATTITUDE_TC_DEFAULT / pitch_tc); param_get(_params_handles.pitch_rate_i, &v); _params.rate_i(1) = v; param_get(_params_handles.pitch_rate_d, &v); _params.rate_d(1) = v * (ATTITUDE_TC_DEFAULT / pitch_tc); param_get(_params_handles.pitch_rate_ff, &v); _params.rate_ff(1) = v; /* yaw gains */ param_get(_params_handles.yaw_p, &v); _params.att_p(2) = v; param_get(_params_handles.yaw_rate_p, &v); _params.rate_p(2) = v; param_get(_params_handles.yaw_rate_i, &v); _params.rate_i(2) = v; param_get(_params_handles.yaw_rate_d, &v); _params.rate_d(2) = v; param_get(_params_handles.yaw_rate_ff, &v); _params.rate_ff(2) = v; param_get(_params_handles.yaw_ff, &_params.yaw_ff); /* angular rate limits */ param_get(_params_handles.roll_rate_max, &_params.roll_rate_max); _params.mc_rate_max(0) = math::radians(_params.roll_rate_max); param_get(_params_handles.pitch_rate_max, &_params.pitch_rate_max); _params.mc_rate_max(1) = math::radians(_params.pitch_rate_max); param_get(_params_handles.yaw_rate_max, &_params.yaw_rate_max); _params.mc_rate_max(2) = math::radians(_params.yaw_rate_max); /* auto angular rate limits */ param_get(_params_handles.roll_rate_max, &_params.roll_rate_max); _params.auto_rate_max(0) = math::radians(_params.roll_rate_max); param_get(_params_handles.pitch_rate_max, &_params.pitch_rate_max); _params.auto_rate_max(1) = math::radians(_params.pitch_rate_max); param_get(_params_handles.yaw_auto_max, &_params.yaw_auto_max); _params.auto_rate_max(2) = math::radians(_params.yaw_auto_max); /* manual rate control scale and auto mode roll/pitch rate limits */ param_get(_params_handles.acro_roll_max, &v); _params.acro_rate_max(0) = math::radians(v); param_get(_params_handles.acro_pitch_max, &v); _params.acro_rate_max(1) = math::radians(v); param_get(_params_handles.acro_yaw_max, &v); _params.acro_rate_max(2) = math::radians(v); /* stick deflection needed in rattitude mode to control rates not angles */ param_get(_params_handles.rattitude_thres, &_params.rattitude_thres); param_get(_params_handles.vtol_type, &_params.vtol_type); int tmp; param_get(_params_handles.vtol_opt_recovery_enabled, &tmp); _params.vtol_opt_recovery_enabled = (bool)tmp; param_get(_params_handles.vtol_wv_yaw_rate_scale, &_params.vtol_wv_yaw_rate_scale); _actuators_0_circuit_breaker_enabled = circuit_breaker_enabled("CBRK_RATE_CTRL", CBRK_RATE_CTRL_KEY); return OK; } void MulticopterAttitudeControl::parameter_update_poll() { bool updated; /* Check if parameters have changed */ orb_check(_params_sub, &updated); if (updated) { struct parameter_update_s param_update; orb_copy(ORB_ID(parameter_update), _params_sub, &param_update); parameters_update(); } } void MulticopterAttitudeControl::vehicle_control_mode_poll() { bool updated; /* Check if vehicle control mode has changed */ orb_check(_v_control_mode_sub, &updated); if (updated) { orb_copy(ORB_ID(vehicle_control_mode), _v_control_mode_sub, &_v_control_mode); } } void MulticopterAttitudeControl::vehicle_manual_poll() { bool updated; /* get pilots inputs */ orb_check(_manual_control_sp_sub, &updated); if (updated) { orb_copy(ORB_ID(manual_control_setpoint), _manual_control_sp_sub, &_manual_control_sp); } } void MulticopterAttitudeControl::vehicle_attitude_setpoint_poll() { /* check if there is a new setpoint */ bool updated; orb_check(_v_att_sp_sub, &updated); if (updated) { orb_copy(ORB_ID(vehicle_attitude_setpoint), _v_att_sp_sub, &_v_att_sp); } } void MulticopterAttitudeControl::vehicle_rates_setpoint_poll() { /* check if there is a new setpoint */ bool updated; orb_check(_v_rates_sp_sub, &updated); if (updated) { orb_copy(ORB_ID(vehicle_rates_setpoint), _v_rates_sp_sub, &_v_rates_sp); } } void MulticopterAttitudeControl::arming_status_poll() { /* check if there is a new setpoint */ bool updated; orb_check(_armed_sub, &updated); if (updated) { orb_copy(ORB_ID(actuator_armed), _armed_sub, &_armed); } } void MulticopterAttitudeControl::vehicle_status_poll() { /* check if there is new status information */ bool vehicle_status_updated; orb_check(_vehicle_status_sub, &vehicle_status_updated); if (vehicle_status_updated) { orb_copy(ORB_ID(vehicle_status), _vehicle_status_sub, &_vehicle_status); /* set correct uORB ID, depending on if vehicle is VTOL or not */ if (!_rates_sp_id) { if (_vehicle_status.is_vtol) { _rates_sp_id = ORB_ID(mc_virtual_rates_setpoint); _actuators_id = ORB_ID(actuator_controls_virtual_mc); } else { _rates_sp_id = ORB_ID(vehicle_rates_setpoint); _actuators_id = ORB_ID(actuator_controls_0); } } } } void MulticopterAttitudeControl::vehicle_motor_limits_poll() { /* check if there is a new message */ bool updated; orb_check(_motor_limits_sub, &updated); if (updated) { orb_copy(ORB_ID(multirotor_motor_limits), _motor_limits_sub, &_motor_limits); } } /** * Attitude controller. * Input: 'vehicle_attitude_setpoint' topics (depending on mode) * Output: '_rates_sp' vector, '_thrust_sp' */ void MulticopterAttitudeControl::sensor_accel_poll() { bool updated; orb_check(_sensor_accel_sub, &updated); if (updated){ orb_copy(ORB_ID(sensor_accel), _sensor_accel_sub, &_sensor_accel); } } void MulticopterAttitudeControl::impact_poll() { bool updated_recovery_stage; bool updated_characterization; orb_check(_recovery_stage_sub, &updated_recovery_stage); orb_check(_characterization_sub, &updated_characterization); if (updated_recovery_stage){ orb_copy(ORB_ID(impact_recovery_stage), _recovery_stage_sub, &_recovery_stage); PX4_WARN("Yea, it's copying\n"); } if (updated_characterization){ orb_copy(ORB_ID(impact_characterization), _characterization_sub, &_characterization); } } void MulticopterAttitudeControl::control_attitude(float dt) { vehicle_attitude_setpoint_poll(); math::Vector<3> accelReference(_characterization.accelReference[0],_characterization.accelReference[1], _characterization.accelReference[2]); float HOVER_THRUST = 0.33f;//param_find("HOVER_THRUST"); PX4_WARN("%u\n",_recovery_stage.recoveryStage); if(_recovery_stage.recoveryStage == 0){ _thrust_sp = _v_att_sp.thrust;//normal control } else if(_recovery_stage.recoveryStage == 1){ _thrust_sp = HOVER_THRUST; // set to hover thrust for initial recovery stage } else if(_recovery_stage.recoveryStage == 2){ _thrust_sp = _v_att_sp.thrust;//set thrust to altitude w/ zero setpoint accelReference.zero(); } else if(_recovery_stage.recoveryStage == 3){ _thrust_sp = _v_att_sp.thrust;//don't change anything, check for stable vertical velocity accelReference.zero(); } else{ //PX4_WARN("Something is terribly wrong."); } math::Quaternion attitudeQuaternion(_ctrl_state.q[0], _ctrl_state.q[1], _ctrl_state.q[2], _ctrl_state.q[3]); if(_recovery_stage.recoveryStage > 0){ // execute recovery control math::Vector<3> eulerAngles = attitudeQuaternion.to_euler(); math::Vector<3> rates; // these are the measured body rates rates(0) = _ctrl_state.roll_rate; rates(1) = _ctrl_state.pitch_rate; rates(2) = _ctrl_state.yaw_rate; math::Vector<3> gravity(0.0f, 0.0f, 9.81f); math::Vector<3> accelDesired = accelReference + gravity; math::Quaternion zAxisAppended(0.0f, 0.0f, 0.0f, 1.0f); math::Quaternion bodyZAppended = ((attitudeQuaternion * zAxisAppended) * attitudeQuaternion.inversed()); math::Vector<3> bodyZ(bodyZAppended(1), bodyZAppended(2), bodyZAppended(3)); math::Vector<3> bodyZDesired = accelDesired.normalized(); // equation (11) float alpha = acosf(bodyZ(0)*bodyZDesired(0) + bodyZ(1)*bodyZDesired(1) + bodyZ(2)*bodyZDesired(2)); //compute axis of rotation in world frame math::Vector<3> axis(bodyZ(1)*bodyZDesired(2) - bodyZ(2)*bodyZDesired(1), \ bodyZ(2)*bodyZDesired(0) - bodyZ(0)*bodyZDesired(2), \ bodyZ(0)*bodyZDesired(1) - bodyZ(1)*bodyZDesired(0)); //to be safe axis.normalize(); //rotate into body frame math::Quaternion axisAppended(0.0f, axis(0), axis(1), axis(2)); math::Quaternion axisBodyAppended = ((attitudeQuaternion.inversed() * axisAppended) * attitudeQuaternion); math::Vector<3> axisBody(axisBodyAppended(1), axisBodyAppended(2), axisBodyAppended(3)); // compute roll pitch error quaternion math::Quaternion rollPitchQuaternionError(cosf(alpha/2), axisBody(0)*sinf(alpha/2), \ axisBody(1)*sinf(alpha/2), axisBody(2)*sinf(alpha/2)); _recovery_control.quatError[0] = rollPitchQuaternionError(0); _recovery_control.quatError[1] = rollPitchQuaternionError(1); _recovery_control.quatError[2] = rollPitchQuaternionError(2); _recovery_control.quatError[3] = rollPitchQuaternionError(3); //proportional constant for aggressiveness of recovery float BODY_RATE_GAIN = 15.0f;//param_find("BODY_RATE_GAIN"); float bodyRate_P_Desired = BODY_RATE_GAIN * rollPitchQuaternionError(1); float bodyRate_Q_Desired = BODY_RATE_GAIN * rollPitchQuaternionError(2); if (rollPitchQuaternionError(0) < 0.0f){ bodyRate_P_Desired = -1*bodyRate_P_Desired; bodyRate_Q_Desired = -1*bodyRate_Q_Desired; } float bodyRate_R_Desired = 0.0f; // these are the desired body rates math::Vector<3> bodyRates(bodyRate_P_Desired, bodyRate_Q_Desired, bodyRate_R_Desired); _rates_sp = bodyRates; _recovery_control.bodyRatesDesired[0] = bodyRate_P_Desired; _recovery_control.bodyRatesDesired[1] = bodyRate_Q_Desired; _recovery_control.bodyRatesDesired[2] = bodyRate_R_Desired; } else{ /* construct attitude setpoint rotation matrix */ //math::Quaternion q_sp(_v_att_sp.q_d[0], _v_att_sp.q_d[1], _v_att_sp.q_d[2], _v_att_sp.q_d[3]); //math::Matrix<3, 3> R_sp = q_sp.to_dcm(); math::Matrix<3, 3> R_sp; R_sp.set(_v_att_sp.R_body); /* get current rotation matrix from control state quaternions */ math::Quaternion q_att(_ctrl_state.q[0], _ctrl_state.q[1], _ctrl_state.q[2], _ctrl_state.q[3]); math::Matrix<3, 3> R = q_att.to_dcm(); /* all input data is ready, run controller itself */ /* try to move thrust vector shortest way, because yaw response is slower than roll/pitch */ math::Vector<3> R_z(R(0, 2), R(1, 2), R(2, 2)); math::Vector<3> R_sp_z(R_sp(0, 2), R_sp(1, 2), R_sp(2, 2)); /* axis and sin(angle) of desired rotation */ math::Vector<3> e_R = R.transposed() * (R_z % R_sp_z); /* calculate angle error */ float e_R_z_sin = e_R.length(); float e_R_z_cos = R_z * R_sp_z; /* calculate weight for yaw control */ float yaw_w = R_sp(2, 2) * R_sp(2, 2); /* calculate rotation matrix after roll/pitch only rotation */ math::Matrix<3, 3> R_rp; if (e_R_z_sin > 0.0f) { /* get axis-angle representation */ float e_R_z_angle = atan2f(e_R_z_sin, e_R_z_cos); math::Vector<3> e_R_z_axis = e_R / e_R_z_sin; e_R = e_R_z_axis * e_R_z_angle; /* cross product matrix for e_R_axis */ math::Matrix<3, 3> e_R_cp; e_R_cp.zero(); e_R_cp(0, 1) = -e_R_z_axis(2); e_R_cp(0, 2) = e_R_z_axis(1); e_R_cp(1, 0) = e_R_z_axis(2); e_R_cp(1, 2) = -e_R_z_axis(0); e_R_cp(2, 0) = -e_R_z_axis(1); e_R_cp(2, 1) = e_R_z_axis(0); /* rotation matrix for roll/pitch only rotation */ R_rp = R * (_I + e_R_cp * e_R_z_sin + e_R_cp * e_R_cp * (1.0f - e_R_z_cos)); } else { /* zero roll/pitch rotation */ R_rp = R; } /* R_rp and R_sp has the same Z axis, calculate yaw error */ math::Vector<3> R_sp_x(R_sp(0, 0), R_sp(1, 0), R_sp(2, 0)); math::Vector<3> R_rp_x(R_rp(0, 0), R_rp(1, 0), R_rp(2, 0)); e_R(2) = atan2f((R_rp_x % R_sp_x) * R_sp_z, R_rp_x * R_sp_x) * yaw_w; if (e_R_z_cos < 0.0f) { /* for large thrust vector rotations use another rotation method: * calculate angle and axis for R -> R_sp rotation directly */ math::Quaternion q_error; q_error.from_dcm(R.transposed() * R_sp); math::Vector<3> e_R_d = q_error(0) >= 0.0f ? q_error.imag() * 2.0f: -q_error.imag() * 2.0f; /* use fusion of Z axis based rotation and direct rotation */ float direct_w = e_R_z_cos * e_R_z_cos * yaw_w; e_R = e_R * (1.0f - direct_w) + e_R_d * direct_w; } /* calculate angular rates setpoint */ _rates_sp = _params.att_p.emult(e_R); /* limit rates */ for (int i = 0; i < 3; i++) { if ((_v_control_mode.flag_control_velocity_enabled || _v_control_mode.flag_control_auto_enabled) && !_v_control_mode.flag_control_manual_enabled) { _rates_sp(i) = math::constrain(_rates_sp(i), -_params.auto_rate_max(i), _params.auto_rate_max(i)); } else { _rates_sp(i) = math::constrain(_rates_sp(i), -_params.mc_rate_max(i), _params.mc_rate_max(i)); } } /* feed forward yaw setpoint rate */ _rates_sp(2) += _v_att_sp.yaw_sp_move_rate * yaw_w * _params.yaw_ff; /* weather-vane mode, dampen yaw rate */ if ((_v_control_mode.flag_control_velocity_enabled || _v_control_mode.flag_control_auto_enabled) && _v_att_sp.disable_mc_yaw_control == true && !_v_control_mode.flag_control_manual_enabled) { float wv_yaw_rate_max = _params.auto_rate_max(2) * _params.vtol_wv_yaw_rate_scale; _rates_sp(2) = math::constrain(_rates_sp(2), -wv_yaw_rate_max, wv_yaw_rate_max); // prevent integrator winding up in weathervane mode _rates_int(2) = 0.0f; } } } /* * Attitude rates controller. * Input: '_rates_sp' vector, '_thrust_sp' * Output: '_att_control' vector */ void MulticopterAttitudeControl::control_attitude_rates(float dt) { // this unwinds the integral gain for PID control /* update integral only if not saturated on low limit and if motor commands are not saturated */ if (!_armed.armed || !_vehicle_status.is_rotary_wing) { _rates_int.zero(); } if(_armed.armed){ math::Vector<3> rates(_ctrl_state.roll_rate,_ctrl_state.pitch_rate,_ctrl_state.yaw_rate); // these are the measured body rates math::Vector<3> rates_err = _rates_sp - rates; // recovery body rate control is PD only if(_recovery_stage.recoveryStage > 0){ _att_control = _params.rate_p.emult(rates_err) + _params.rate_d.emult(_rates_prev - rates) / dt; } else{ // do PID (not sure if we need this, but it might stabilize the control) _att_control = _params.rate_p.emult(rates_err) + _params.rate_d.emult(_rates_prev - rates) / dt + _rates_int; } _rates_sp_prev = _rates_sp; _rates_prev = rates; if (_thrust_sp > MIN_TAKEOFF_THRUST && !_motor_limits.lower_limit && !_motor_limits.upper_limit) { for (int i = AXIS_INDEX_ROLL; i < AXIS_COUNT; i++) { if (fabsf(_att_control(i)) < _thrust_sp) { float rate_i = _rates_int(i) + _params.rate_i(i) * rates_err(i) * dt; if (PX4_ISFINITE(rate_i) && rate_i > -RATES_I_LIMIT && rate_i < RATES_I_LIMIT && _att_control(i) > -RATES_I_LIMIT && _att_control(i) < RATES_I_LIMIT && /* if the axis is the yaw axis, do not update the integral if the limit is hit */ !((i == AXIS_INDEX_YAW) && _motor_limits.yaw)) { _rates_int(i) = rate_i; } } } } } else{ //don't give moments if disarmed, redundent _att_control.zero(); } } void MulticopterAttitudeControl::task_main_trampoline(int argc, char *argv[]) { mc_att_control::g_control->task_main(); } void MulticopterAttitudeControl::task_main() { /* * do subscriptions */ _v_att_sp_sub = orb_subscribe(ORB_ID(vehicle_attitude_setpoint)); _v_rates_sp_sub = orb_subscribe(ORB_ID(vehicle_rates_setpoint)); _ctrl_state_sub = orb_subscribe(ORB_ID(control_state)); _v_control_mode_sub = orb_subscribe(ORB_ID(vehicle_control_mode)); _params_sub = orb_subscribe(ORB_ID(parameter_update)); _manual_control_sp_sub = orb_subscribe(ORB_ID(manual_control_setpoint)); _armed_sub = orb_subscribe(ORB_ID(actuator_armed)); _vehicle_status_sub = orb_subscribe(ORB_ID(vehicle_status)); _motor_limits_sub = orb_subscribe(ORB_ID(multirotor_motor_limits)); _sensor_accel_sub = orb_subscribe(ORB_ID(sensor_accel)); _recovery_stage_sub = orb_subscribe(ORB_ID(impact_recovery_stage)); _characterization_sub = orb_subscribe(ORB_ID(impact_characterization)); /* initialize parameters cache */ parameters_update(); /* wakeup source: vehicle attitude */ px4_pollfd_struct_t fds[1]; fds[0].fd = _ctrl_state_sub; fds[0].events = POLLIN; while (!_task_should_exit) { /* wait for up to 100ms for data */ int pret = px4_poll(&fds[0], (sizeof(fds) / sizeof(fds[0])), 100); /* timed out - periodic check for _task_should_exit */ if (pret == 0) { continue; } /* this is undesirable but not much we can do - might want to flag unhappy status */ if (pret < 0) { warn("mc att ctrl: poll error %d, %d", pret, errno); /* sleep a bit before next try */ usleep(100000); continue; } perf_begin(_loop_perf); /* run controller on attitude changes */ if (fds[0].revents & POLLIN) { static uint64_t last_run = 0; float dt = (hrt_absolute_time() - last_run) / 1000000.0f; last_run = hrt_absolute_time(); /* guard against too small (< 2ms) and too large (> 20ms) dt's */ if (dt < 0.002f) { dt = 0.002f; } else if (dt > 0.02f) { dt = 0.02f; } /* copy attitude and control state topics */ orb_copy(ORB_ID(control_state), _ctrl_state_sub, &_ctrl_state); /* check for updates in other topics */ parameter_update_poll(); vehicle_control_mode_poll(); arming_status_poll(); vehicle_manual_poll(); vehicle_status_poll(); vehicle_motor_limits_poll(); sensor_accel_poll(); impact_poll(); /* Check if we are in rattitude mode and the pilot is above the threshold on pitch * or roll (yaw can rotate 360 in normal att control). If both are true don't * even bother running the attitude controllers */ if (_v_control_mode.flag_control_rattitude_enabled) { if (fabsf(_manual_control_sp.y) > _params.rattitude_thres || fabsf(_manual_control_sp.x) > _params.rattitude_thres) { _v_control_mode.flag_control_attitude_enabled = false; } } if (_v_control_mode.flag_control_attitude_enabled) { if (_ts_opt_recovery == nullptr) { // the tailsitter recovery instance has not been created, thus, the vehicle // is not a tailsitter, do normal attitude control control_attitude(dt); } else { vehicle_attitude_setpoint_poll(); _thrust_sp = _v_att_sp.thrust; math::Quaternion q(_ctrl_state.q[0], _ctrl_state.q[1], _ctrl_state.q[2], _ctrl_state.q[3]); math::Quaternion q_sp(&_v_att_sp.q_d[0]); _ts_opt_recovery->setAttGains(_params.att_p, _params.yaw_ff); _ts_opt_recovery->calcOptimalRates(q, q_sp, _v_att_sp.yaw_sp_move_rate, _rates_sp); /* limit rates */ for (int i = 0; i < 3; i++) { _rates_sp(i) = math::constrain(_rates_sp(i), -_params.mc_rate_max(i), _params.mc_rate_max(i)); } } /* publish attitude rates setpoint */ _v_rates_sp.roll = _rates_sp(0); _v_rates_sp.pitch = _rates_sp(1); _v_rates_sp.yaw = _rates_sp(2); _v_rates_sp.thrust = _thrust_sp; _v_rates_sp.timestamp = hrt_absolute_time(); if (_v_rates_sp_pub != nullptr) { orb_publish(_rates_sp_id, _v_rates_sp_pub, &_v_rates_sp); } else if (_rates_sp_id) { _v_rates_sp_pub = orb_advertise(_rates_sp_id, &_v_rates_sp); } //} } else { /* attitude controller disabled, poll rates setpoint topic */ if (_v_control_mode.flag_control_manual_enabled) { /* manual rates control - ACRO mode */ _rates_sp = math::Vector<3>(_manual_control_sp.y, -_manual_control_sp.x, _manual_control_sp.r).emult(_params.acro_rate_max); _thrust_sp = math::min(_manual_control_sp.z, MANUAL_THROTTLE_MAX_MULTICOPTER); /* publish attitude rates setpoint */ _v_rates_sp.roll = _rates_sp(0); _v_rates_sp.pitch = _rates_sp(1); _v_rates_sp.yaw = _rates_sp(2); _v_rates_sp.thrust = _thrust_sp; _v_rates_sp.timestamp = hrt_absolute_time(); if (_v_rates_sp_pub != nullptr) { orb_publish(_rates_sp_id, _v_rates_sp_pub, &_v_rates_sp); } else if (_rates_sp_id) { _v_rates_sp_pub = orb_advertise(_rates_sp_id, &_v_rates_sp); } } else { /* attitude controller disabled, poll rates setpoint topic */ vehicle_rates_setpoint_poll(); _rates_sp(0) = _v_rates_sp.roll; _rates_sp(1) = _v_rates_sp.pitch; _rates_sp(2) = _v_rates_sp.yaw; _thrust_sp = _v_rates_sp.thrust; } } if (_v_control_mode.flag_control_rates_enabled) { control_attitude_rates(dt); /* publish actuator controls */ _actuators.control[0] = (PX4_ISFINITE(_att_control(0))) ? _att_control(0) : 0.0f; _actuators.control[1] = (PX4_ISFINITE(_att_control(1))) ? _att_control(1) : 0.0f; _actuators.control[2] = (PX4_ISFINITE(_att_control(2))) ? _att_control(2) : 0.0f; _actuators.control[3] = (PX4_ISFINITE(_thrust_sp)) ? _thrust_sp : 0.0f; _actuators.timestamp = hrt_absolute_time(); _actuators.timestamp_sample = _ctrl_state.timestamp; _controller_status.roll_rate_integ = _rates_int(0); _controller_status.pitch_rate_integ = _rates_int(1); _controller_status.yaw_rate_integ = _rates_int(2); _controller_status.timestamp = hrt_absolute_time(); if (!_actuators_0_circuit_breaker_enabled) { if (_actuators_0_pub != nullptr) { orb_publish(_actuators_id, _actuators_0_pub, &_actuators); perf_end(_controller_latency_perf); } else if (_actuators_id) { _actuators_0_pub = orb_advertise(_actuators_id, &_actuators); } } /* publish controller status */ if (_controller_status_pub != nullptr) { orb_publish(ORB_ID(mc_att_ctrl_status), _controller_status_pub, &_controller_status); } else { _controller_status_pub = orb_advertise(ORB_ID(mc_att_ctrl_status), &_controller_status); } //custom if (_recovery_control_pub != nullptr) { orb_publish(ORB_ID(recovery_control), _recovery_control_pub, &_recovery_control); } else{ _recovery_control_pub = orb_advertise(ORB_ID(recovery_control), &_recovery_control); } } } perf_end(_loop_perf); } _control_task = -1; return; } int MulticopterAttitudeControl::start() { ASSERT(_control_task == -1); /* start the task */ _control_task = px4_task_spawn_cmd("mc_att_control", SCHED_DEFAULT, SCHED_PRIORITY_MAX - 5, 1500, (px4_main_t)&MulticopterAttitudeControl::task_main_trampoline, nullptr); if (_control_task < 0) { warn("task start failed"); return -errno; } return OK; } int mc_att_control_main(int argc, char *argv[]) { if (argc < 2) { warnx("usage: mc_att_control {start|stop|status}"); return 1; } if (!strcmp(argv[1], "start")) { if (mc_att_control::g_control != nullptr) { warnx("already running"); return 1; } mc_att_control::g_control = new MulticopterAttitudeControl; if (mc_att_control::g_control == nullptr) { warnx("alloc failed"); return 1; } if (OK != mc_att_control::g_control->start()) { delete mc_att_control::g_control; mc_att_control::g_control = nullptr; warnx("start failed"); return 1; } return 0; } if (!strcmp(argv[1], "stop")) { if (mc_att_control::g_control == nullptr) { warnx("not running"); return 1; } delete mc_att_control::g_control; mc_att_control::g_control = nullptr; return 0; } if (!strcmp(argv[1], "status")) { if (mc_att_control::g_control) { warnx("running"); return 0; } else { warnx("not running"); return 1; } } warnx("unrecognized command"); return 1; }
#include "./Game.h" #include <iostream> #include "../lib/glm/glm.hpp" #include "./AssetManager.h" #include "./Components/ColliderComponent.h" #include "./Components/KeyboardControlComponent.h" #include "./Components/ProjectileEmitterComponent.h" #include "./Components/SpriteComponent.h" #include "./Components/TextLabelComponent.h" #include "./Components/TransformComponent.h" #include "./Constants.h" #include "./Map.h" EntityManager manager; AssetManager* Game::assetManager = new AssetManager(&manager); SDL_Renderer* Game::renderer; SDL_Event Game::event; SDL_Rect Game::camera = {0, 0, WINDOW_WIDTH, WINDOW_HEIGHT}; Map* map; Game::Game() { this->isRunning = false; } Game::~Game() { } bool Game::IsRunning() const { return this->isRunning; } void Game::Initialize(int width, int height) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cerr << "Error initializing SDL." << std::endl; return; } if (TTF_Init() != 0) { std::cerr << "Error initializing SDL TTF" << std::endl; return; } window = SDL_CreateWindow( NULL, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_BORDERLESS); if (!window) { std::cerr << "Error creating SDL window." << std::endl; return; } renderer = SDL_CreateRenderer(window, -1, 0); if (!renderer) { std::cerr << "Error creating SDL renderer." << std::endl; return; } LoadLevel(0); isRunning = true; return; } Entity& player(manager.AddEntity("chopper", PLAYER_LAYER)); void Game::LoadLevel(int levelNumber) { /* Start including new assets to the assetmanager list */ assetManager->AddTexture("tank-image", std::string("./assets/images/tank-big-right.png").c_str()); assetManager->AddTexture("chopper-image", std::string("./assets/images/chopper-spritesheet.png").c_str()); assetManager->AddTexture("radar-image", std::string("./assets/images/radar.png").c_str()); assetManager->AddTexture("jungle-tiletexture", std::string("./assets/tilemaps/jungle.png").c_str()); assetManager->AddTexture("heliport-image", std::string("./assets/images/heliport.png").c_str()); assetManager->AddTexture("collision-texture", std::string("./assets/images/collision-texture.png").c_str()); assetManager->AddTexture("projectile-image", std::string("./assets/images/bullet-enemy.png").c_str()); assetManager->AddFont("charriot-font", std::string("./assets/fonts/charriot.ttf").c_str(), 14); map = new Map("jungle-tiletexture", 2, 32); map->LoadMap("./assets/tilemaps/jungle.map", 25, 20); /* Start including entities and also components to them */ player.AddComponent<TransformComponent>(240, 106, 0, 0, 32, 32, 1); player.AddComponent<SpriteComponent>("chopper-image", 2, 90, true, false); player.AddComponent<KeyboardControlComponent>("up", "right", "down", "left", "space"); player.AddComponent<ColliderComponent>("PLAYER", 240, 106, 32, 32); Entity& tankEntity(manager.AddEntity("tank", ENEMY_LAYER)); tankEntity.AddComponent<TransformComponent>(150, 495, 5, 0, 32, 32, 1); tankEntity.AddComponent<SpriteComponent>("tank-image"); tankEntity.AddComponent<ColliderComponent>("ENEMY", 150, 495, 32, 32); Entity& projectile(manager.AddEntity("projectile", PROJECTILE_LAYER)); projectile.AddComponent<TransformComponent>(150 + 16, 495 + 16, 0, 0, 4, 4, 1); projectile.AddComponent<SpriteComponent>("projectile-image"); projectile.AddComponent<ColliderComponent>("PROJECTILE", 150 + 16, 495 + 16, 4, 4); projectile.AddComponent<ProjectileEmitterComponent>(50, 270, 200, true); Entity& heliport(manager.AddEntity("Heliport", OBSTACLE_LAYER)); heliport.AddComponent<TransformComponent>(470, 420, 0, 0, 32, 32, 1); heliport.AddComponent<SpriteComponent>("heliport-image"); heliport.AddComponent<ColliderComponent>("LEVEL_COMPLETE", 470, 420, 32, 32); Entity& radarEntity(manager.AddEntity("Radar", UI_LAYER)); radarEntity.AddComponent<TransformComponent>(720, 15, 0, 0, 64, 64, 1); radarEntity.AddComponent<SpriteComponent>("radar-image", 8, 150, false, true); Entity& labelLevelName(manager.AddEntity("LabelLevelName", UI_LAYER)); labelLevelName.AddComponent<TextLabelComponent>(10, 10, "First Level...", "charriot-font", WHITE_COLOR); } void Game::ProcessInput() { SDL_PollEvent(&event); switch (event.type) { case SDL_QUIT: { isRunning = false; break; } case SDL_KEYDOWN: { if (event.key.keysym.sym == SDLK_ESCAPE) { isRunning = false; } } default: { break; } } } void Game::Update() { // Wait until 16ms has ellapsed since the last frame while (!SDL_TICKS_PASSED(SDL_GetTicks(), ticksLastFrame + FRAME_TARGET_TIME)) ; // Delta time is the difference in ticks from last frame converted to seconds float deltaTime = (SDL_GetTicks() - ticksLastFrame) / 1000.0f; // Clamp deltaTime to a maximum value deltaTime = (deltaTime > 0.05f) ? 0.05f : deltaTime; // Sets the new ticks for the current frame to be used in the next pass ticksLastFrame = SDL_GetTicks(); manager.Update(deltaTime); HandleCameraMovement(); CheckCollisions(); } void Game::Render() { SDL_SetRenderDrawColor(renderer, 21, 21, 21, 255); SDL_RenderClear(renderer); if (manager.HasNoEntities()) { return; } manager.Render(); SDL_RenderPresent(renderer); } void Game::HandleCameraMovement() { TransformComponent* mainPlayerTransform = player.GetComponent<TransformComponent>(); camera.x = mainPlayerTransform->position.x - (WINDOW_WIDTH / 2); camera.y = mainPlayerTransform->position.y - (WINDOW_HEIGHT / 2); camera.x = camera.x < 0 ? 0 : camera.x; camera.y = camera.y < 0 ? 0 : camera.y; camera.x = camera.x > camera.w ? camera.w : camera.x; camera.y = camera.y > camera.h ? camera.h : camera.y; } void Game::CheckCollisions() { CollisionType collisionType = manager.CheckCollisions(); if (collisionType == PLAYER_ENEMY_COLLISION) { ProcessGameOver(); } if (collisionType == PLAYER_LEVEL_COMPLETE_COLLISION) { ProcessNextLevel(1); } if (collisionType == PLAYER_PROJECTILE_COLLISION) { ProcessGameOver(); } } void Game::ProcessNextLevel(int levelNumber) { std::cout << "Next Level" << std::endl; isRunning = false; } void Game::ProcessGameOver() { std::cout << "Game Over" << std::endl; isRunning = false; } void Game::Destroy() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); }
// Copyright 2020 The XLS Authors // // 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. #include "xls/ir/package.h" #include <utility> #include "absl/status/statusor.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "xls/common/logging/logging.h" #include "xls/common/status/status_macros.h" #include "xls/common/strong_int.h" #include "xls/ir/block.h" #include "xls/ir/channel.h" #include "xls/ir/function.h" #include "xls/ir/proc.h" #include "xls/ir/type.h" #include "xls/ir/value.h" #include "xls/ir/value_helpers.h" namespace xls { namespace { constexpr char kMain[] = "main"; } Package::Package(absl::string_view name, absl::optional<absl::string_view> entry) : entry_(entry), name_(name) { owned_types_.insert(&token_type_); } Package::~Package() {} Function* Package::AddFunction(std::unique_ptr<Function> f) { functions_.push_back(std::move(f)); return functions_.back().get(); } Proc* Package::AddProc(std::unique_ptr<Proc> proc) { procs_.push_back(std::move(proc)); return procs_.back().get(); } Block* Package::AddBlock(std::unique_ptr<Block> block) { blocks_.push_back(std::move(block)); return blocks_.back().get(); } absl::StatusOr<Function*> Package::GetFunction( absl::string_view func_name) const { for (auto& f : functions_) { if (f->name() == func_name) { return f.get(); } } return absl::NotFoundError(absl::StrFormat( "Package does not have a function with name: \"%s\"; available: [%s]", func_name, absl::StrJoin(functions_, ", ", [](std::string* out, const std::unique_ptr<Function>& f) { absl::StrAppend(out, f->name()); }))); } absl::StatusOr<Proc*> Package::GetProc(absl::string_view proc_name) const { for (auto& p : procs_) { if (p->name() == proc_name) { return p.get(); } } return absl::NotFoundError(absl::StrFormat( "Package does not have a proc with name: \"%s\"; available: [%s]", proc_name, absl::StrJoin(procs_, ", ", [](std::string* out, const std::unique_ptr<Proc>& p) { absl::StrAppend(out, p->name()); }))); } absl::StatusOr<Block*> Package::GetBlock(absl::string_view block_name) const { for (auto& block : blocks_) { if (block->name() == block_name) { return block.get(); } } return absl::NotFoundError(absl::StrFormat( "Package does not have a block with name: \"%s\"; available: [%s]", block_name, absl::StrJoin(blocks_, ", ", [](std::string* out, const std::unique_ptr<Block>& block) { absl::StrAppend(out, block->name()); }))); } std::vector<FunctionBase*> Package::GetFunctionBases() const { std::vector<FunctionBase*> result; for (auto& function : functions()) { result.push_back(function.get()); } for (auto& proc : procs()) { result.push_back(proc.get()); } for (auto& block : blocks()) { result.push_back(block.get()); } return result; } absl::Status Package::RemoveFunction(Function* function) { auto it = std::remove_if( functions_.begin(), functions_.end(), [&](const std::unique_ptr<Function>& f) { return f.get() == function; }); if (it == functions_.end()) { return absl::NotFoundError(absl::StrFormat( "`%s` is not a function in package `%s`", function->name(), name())); } functions_.erase(it, functions_.end()); return absl::OkStatus(); } absl::Status Package::RemoveProc(Proc* proc) { auto it = std::remove_if( procs_.begin(), procs_.end(), [&](const std::unique_ptr<Proc>& f) { return f.get() == proc; }); if (it == procs_.end()) { return absl::NotFoundError(absl::StrFormat( "`%s` is not a proc in package `%s`", proc->name(), name())); } procs_.erase(it, procs_.end()); return absl::OkStatus(); } absl::Status Package::RemoveBlock(Block* block) { auto it = std::remove_if( blocks_.begin(), blocks_.end(), [&](const std::unique_ptr<Block>& f) { return f.get() == block; }); if (it == blocks_.end()) { return absl::NotFoundError(absl::StrFormat( "`%s` is not a block in package `%s`", block->name(), name())); } blocks_.erase(it, blocks_.end()); return absl::OkStatus(); } absl::StatusOr<Function*> Package::EntryFunction() { auto by_name = GetFunctionByName(); if (entry_.has_value()) { auto it = by_name.find(entry_.value()); if (it != by_name.end()) { return it->second; } std::string available = absl::StrJoin(by_name.begin(), by_name.end(), ", ", [](std::string* out, const std::pair<std::string, const Function*>& item) { absl::StrAppend(out, "\"", item.first, "\""); }); return absl::NotFoundError( absl::StrFormat("Could not find entry function for this package; " "tried: [\"%s\"]; available: %s", entry_.value(), available)); } // Try a few possibilities of names for the canonical entry function. const std::vector<std::string> to_try = { kMain, name(), absl::StrCat("__", name(), "__", kMain), absl::StrCat("__", name(), "__", name()), }; for (const std::string& attempt : to_try) { auto it = by_name.find(attempt); if (it != by_name.end()) { return it->second; } } // Finally we use the only function if only one exists. if (functions_.size() == 1) { return functions_.front().get(); } auto quote = [](std::string* out, const std::string& s) { absl::StrAppend(out, "\"", s, "\""); }; return absl::NotFoundError(absl::StrFormat( "Could not find an entry function for the \"%s\" package; " "attempted: [%s]", name(), absl::StrJoin(to_try, ", ", quote))); } absl::StatusOr<const Function*> Package::EntryFunction() const { XLS_ASSIGN_OR_RETURN(Function * f, const_cast<Package*>(this)->EntryFunction()); return f; } SourceLocation Package::AddSourceLocation(absl::string_view filename, Lineno lineno, Colno colno) { Fileno this_fileno = GetOrCreateFileno(filename); return SourceLocation(this_fileno, lineno, colno); } std::string Package::SourceLocationToString(const SourceLocation loc) { const std::string unknown = "UNKNOWN"; absl::string_view filename = fileno_to_filename_.find(loc.fileno()) != fileno_to_filename_.end() ? fileno_to_filename_.at(loc.fileno()) : unknown; return absl::StrFormat("%s:%d", filename, loc.lineno().value()); } absl::StatusOr<Type*> Package::MapTypeFromOtherPackage( Type* other_package_type) { // Package already owns this type. if (IsOwnedType(other_package_type)) { return other_package_type; } if (other_package_type->IsBits()) { const BitsType* bits = other_package_type->AsBitsOrDie(); return GetBitsType(bits->bit_count()); } else if (other_package_type->IsArray()) { const ArrayType* array = other_package_type->AsArrayOrDie(); XLS_ASSIGN_OR_RETURN(Type * elem_type, MapTypeFromOtherPackage(array->element_type())); return GetArrayType(array->size(), elem_type); } else if (other_package_type->IsTuple()) { const TupleType* tuple = other_package_type->AsTupleOrDie(); std::vector<Type*> member_types; member_types.reserve(tuple->size()); for (auto* elem_type : tuple->element_types()) { XLS_ASSIGN_OR_RETURN(Type * new_elem_type, MapTypeFromOtherPackage(elem_type)); member_types.push_back(new_elem_type); } return GetTupleType(member_types); } else if (other_package_type->IsToken()) { return GetTokenType(); } else { return absl::InternalError("Unsupported type."); } } BitsType* Package::GetBitsType(int64_t bit_count) { if (bit_count_to_type_.find(bit_count) != bit_count_to_type_.end()) { return &bit_count_to_type_.at(bit_count); } auto it = bit_count_to_type_.emplace(bit_count, BitsType(bit_count)); BitsType* new_type = &(it.first->second); owned_types_.insert(new_type); return new_type; } ArrayType* Package::GetArrayType(int64_t size, Type* element_type) { ArrayKey key{size, element_type}; if (array_types_.find(key) != array_types_.end()) { return &array_types_.at(key); } XLS_CHECK(IsOwnedType(element_type)) << "Type is not owned by package: " << *element_type; auto it = array_types_.emplace(key, ArrayType(size, element_type)); ArrayType* new_type = &(it.first->second); owned_types_.insert(new_type); return new_type; } TupleType* Package::GetTupleType(absl::Span<Type* const> element_types) { TypeVec key(element_types.begin(), element_types.end()); if (tuple_types_.find(key) != tuple_types_.end()) { return &tuple_types_.at(key); } for (const Type* element_type : element_types) { XLS_CHECK(IsOwnedType(element_type)) << "Type is not owned by package: " << *element_type; } auto it = tuple_types_.emplace(key, TupleType(element_types)); TupleType* new_type = &(it.first->second); owned_types_.insert(new_type); return new_type; } TokenType* Package::GetTokenType() { return &token_type_; } FunctionType* Package::GetFunctionType(absl::Span<Type* const> args_types, Type* return_type) { std::string key = FunctionType(args_types, return_type).ToString(); if (function_types_.find(key) != function_types_.end()) { return &function_types_.at(key); } for (Type* t : args_types) { XLS_CHECK(IsOwnedType(t)) << "Parameter type is not owned by package: " << t->ToString(); } auto it = function_types_.emplace(key, FunctionType(args_types, return_type)); FunctionType* new_type = &(it.first->second); owned_function_types_.insert(new_type); return new_type; } absl::StatusOr<Type*> Package::GetTypeFromProto(const TypeProto& proto) { if (!proto.has_type_enum()) { return absl::InvalidArgumentError("Missing type_enum field in TypeProto."); } if (proto.type_enum() == TypeProto::BITS) { if (!proto.has_bit_count() || proto.bit_count() < 0) { return absl::InvalidArgumentError( "Missing or invalid bit_count field in TypeProto."); } return GetBitsType(proto.bit_count()); } if (proto.type_enum() == TypeProto::TUPLE) { std::vector<Type*> elements; for (const TypeProto& element_proto : proto.tuple_elements()) { XLS_ASSIGN_OR_RETURN(Type * element, GetTypeFromProto(element_proto)); elements.push_back(element); } return GetTupleType(elements); } if (proto.type_enum() == TypeProto::ARRAY) { if (!proto.has_array_size() || proto.array_size() < 0) { return absl::InvalidArgumentError( "Missing or invalid array_size field in TypeProto."); } if (!proto.has_array_element()) { return absl::InvalidArgumentError( "Missing array_element field in TypeProto."); } XLS_ASSIGN_OR_RETURN(Type * element_type, GetTypeFromProto(proto.array_element())); return GetArrayType(proto.array_size(), element_type); } if (proto.type_enum() == TypeProto::TOKEN) { return GetTokenType(); } return absl::InvalidArgumentError(absl::StrFormat( "Invalid type_enum value in TypeProto: %d", proto.type_enum())); } absl::StatusOr<FunctionType*> Package::GetFunctionTypeFromProto( const FunctionTypeProto& proto) { std::vector<Type*> param_types; for (const TypeProto& param_proto : proto.parameters()) { XLS_ASSIGN_OR_RETURN(Type * param_type, GetTypeFromProto(param_proto)); param_types.push_back(param_type); } if (!proto.has_return_type()) { return absl::InvalidArgumentError( "Missing return_type field in FunctionTypeProto."); } XLS_ASSIGN_OR_RETURN(Type * return_type, GetTypeFromProto(proto.return_type())); return GetFunctionType(param_types, return_type); } Type* Package::GetTypeForValue(const Value& value) { switch (value.kind()) { case ValueKind::kBits: return GetBitsType(value.bits().bit_count()); case ValueKind::kTuple: { std::vector<Type*> element_types; for (const Value& value : value.elements()) { element_types.push_back(GetTypeForValue(value)); } return GetTupleType(element_types); } case ValueKind::kArray: { // No element type can be inferred for 0-element arrays. if (value.empty()) { return GetArrayType(0, nullptr); } return GetArrayType(value.size(), GetTypeForValue(value.elements()[0])); } case ValueKind::kToken: return GetTokenType(); case ValueKind::kInvalid: break; } XLS_LOG(FATAL) << "Invalid value for type extraction."; } Fileno Package::GetOrCreateFileno(absl::string_view filename) { // Attempt to add a new fileno/filename pair to the map. auto this_fileno = Fileno(filename_to_fileno_.size()); if (auto it = filename_to_fileno_.find(std::string(filename)); it != filename_to_fileno_.end()) { return it->second; } filename_to_fileno_.emplace(std::string(filename), this_fileno); fileno_to_filename_.emplace(this_fileno, std::string(filename)); return this_fileno; } int64_t Package::GetNodeCount() const { int64_t count = 0; for (const auto& f : functions()) { count += f->node_count(); } return count; } bool Package::IsDefinitelyEqualTo(const Package* other) const { auto entry_function_status = EntryFunction(); if (!entry_function_status.ok()) { return false; } auto other_entry_function_status = other->EntryFunction(); if (!other_entry_function_status.ok()) { return false; } const Function* entry = entry_function_status.value(); const Function* other_entry = other_entry_function_status.value(); return entry->IsDefinitelyEqualTo(other_entry); } std::string Package::DumpIr() const { std::string out; absl::StrAppend(&out, "package ", name(), "\n\n"); if (!channels().empty()) { for (Channel* channel : channels()) { absl::StrAppend(&out, channel->ToString(), "\n"); } absl::StrAppend(&out, "\n"); } std::vector<std::string> function_dumps; for (auto& function : functions()) { function_dumps.push_back(function->DumpIr()); } for (auto& proc : procs()) { function_dumps.push_back(proc->DumpIr()); } for (auto& block : blocks()) { function_dumps.push_back(block->DumpIr()); } absl::StrAppend(&out, absl::StrJoin(function_dumps, "\n")); return out; } std::ostream& operator<<(std::ostream& os, const Package& package) { os << package.DumpIr(); return os; } absl::flat_hash_map<std::string, Function*> Package::GetFunctionByName() { absl::flat_hash_map<std::string, Function*> name_to_function; for (std::unique_ptr<Function>& function : functions_) { name_to_function[function->name()] = function.get(); } return name_to_function; } std::vector<std::string> Package::GetFunctionNames() const { std::vector<std::string> names; for (const std::unique_ptr<Function>& function : functions_) { names.push_back(function->name()); } std::sort(names.begin(), names.end()); return names; } bool Package::HasFunctionWithName(absl::string_view target) const { for (const std::unique_ptr<Function>& function : functions_) { if (function->name() == target) { return true; } } return false; } namespace { absl::Status VerifyValuesAreType(absl::Span<const Value> values, Type* type) { for (const Value& value : values) { if (!ValueConformsToType(value, type)) { return absl::InvalidArgumentError( absl::StrFormat("Initial value does not match channel type %s: %s", type->ToString(), value.ToString())); } } return absl::OkStatus(); } } // namespace absl::StatusOr<StreamingChannel*> Package::CreateStreamingChannel( absl::string_view name, ChannelOps supported_ops, Type* type, absl::Span<const Value> initial_values, FlowControl flow_control, const ChannelMetadataProto& metadata, absl::optional<int64_t> id) { XLS_RETURN_IF_ERROR(VerifyValuesAreType(initial_values, type)); int64_t actual_id = id.has_value() ? id.value() : next_channel_id_; auto channel = std::make_unique<StreamingChannel>( name, actual_id, supported_ops, type, initial_values, flow_control, metadata); StreamingChannel* channel_ptr = channel.get(); XLS_RETURN_IF_ERROR(AddChannel(std::move(channel))); return channel_ptr; } absl::StatusOr<SingleValueChannel*> Package::CreateSingleValueChannel( absl::string_view name, ChannelOps supported_ops, Type* type, const ChannelMetadataProto& metadata, absl::optional<int64_t> id) { int64_t actual_id = id.has_value() ? id.value() : next_channel_id_; auto channel = std::make_unique<SingleValueChannel>( name, actual_id, supported_ops, type, metadata); SingleValueChannel* channel_ptr = channel.get(); XLS_RETURN_IF_ERROR(AddChannel(std::move(channel))); return channel_ptr; } absl::Status Package::RemoveChannel(Channel* channel) { // First check that the channel is owned by this package. auto it = std::find(channel_vec_.begin(), channel_vec_.end(), channel); XLS_RET_CHECK(it != channel_vec_.end()) << "Channel not owned by package"; // Check that no send/receive nodes are associted with the channel. // TODO(https://github.com/google/xls/issues/411) 2012/04/24 Avoid iterating // through all the nodes after channels are mapped to send/receive nodes. for (const auto& proc : procs()) { for (Node* node : proc->nodes()) { if ((node->Is<Send>() && node->As<Send>()->channel_id() == channel->id()) || (node->Is<Receive>() && node->As<Receive>()->channel_id() == channel->id())) { return absl::InternalError(absl::StrFormat( "Channel %s (%d) cannot be removed because it is used by node %s", channel->name(), channel->id(), node->GetName())); } } } // Remove from channel vector. channel_vec_.erase(it); // Remove from channel map. XLS_RET_CHECK(channels_.contains(channel->id())); channels_.erase(channel->id()); return absl::OkStatus(); } absl::Status Package::AddChannel(std::unique_ptr<Channel> channel) { int64_t id = channel->id(); auto [channel_it, inserted] = channels_.insert({id, std::move(channel)}); if (!inserted) { return absl::InternalError( absl::StrFormat("Channel already exists with id %d.", id)); } Channel* channel_ptr = channel_it->second.get(); // Verify the channel name is unique. for (Channel* ch : channel_vec_) { if (ch->name() == channel_ptr->name()) { return absl::InvalidArgumentError(absl::StrFormat( "Channel already exists with name \"%s\"", ch->name())); } } // The channel name and all data element names must be valid identifiers. if (!NameUniquer::IsValidIdentifier(channel_ptr->name())) { return absl::InvalidArgumentError( absl::StrFormat("Invalid channel name: \"%s\"", channel_ptr->name())); } // Add pointer to newly added channel to the channel vector and resort it by // ID. channel_vec_.push_back(channel_ptr); std::sort(channel_vec_.begin(), channel_vec_.end(), [](Channel* a, Channel* b) { return a->id() < b->id(); }); next_channel_id_ = std::max(next_channel_id_, id + 1); return absl::OkStatus(); } absl::StatusOr<Channel*> Package::GetChannel(int64_t id) const { if (channels_.find(id) == channels_.end()) { return absl::NotFoundError( absl::StrFormat("No channel with id %d (package has %d channels).", id, channels_.size())); } return channels_.at(id).get(); } absl::StatusOr<Channel*> Package::GetChannel(absl::string_view name) const { for (Channel* ch : channels()) { if (ch->name() == name) { return ch; } } return absl::NotFoundError( absl::StrFormat("No channel with name '%s' (package has %d channels).", name, channels().size())); } } // namespace xls
/***************************************************************************** * * * OpenNI 2.x Alpha * * Copyright (C) 2012 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * 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. * * * *****************************************************************************/ #include "XnLinkContInputStream.h" #include "XnLinkProtoUtils.h" #include "XnLinkProtoLibDefs.h" #include "XnLinkControlEndpoint.h" #include <XnLog.h> #include <XnEvent.h> #define XN_MASK_INPUT_STREAM "xnInputStream" namespace xn { const uint32_t LinkContInputStream::CONT_STREAM_PREDEFINED_BUFFER_SIZE = 0x40000; LinkContInputStream::LinkContInputStream() { m_bInitialized = false; m_bStreaming = false; m_bNewDataAvailable = false; m_hCriticalSection = NULL; m_nUserBufferMaxSize = 0; m_pUserBuffer = NULL; m_nUserBufferCurrentSize = 0; xnOSCreateCriticalSection(&m_hCriticalSection); m_pDumpFile = NULL; xnOSMemSet(m_strDumpName, 0, sizeof(m_strDumpName)); } LinkContInputStream::~LinkContInputStream() { Shutdown(); xnOSCloseCriticalSection(&m_hCriticalSection); } XnStatus LinkContInputStream::Init(LinkControlEndpoint* pLinkControlEndpoint, XnStreamType streamType, uint16_t nStreamID, IConnection* pConnection) { XnStatus nRetVal = XN_STATUS_OK; if (m_hCriticalSection == NULL) { xnLogError(XN_MASK_INPUT_STREAM, "Cannot initialize - critical section was not created successfully"); XN_ASSERT(false); return XN_STATUS_ERROR; } xnl::AutoCSLocker csLock(m_hCriticalSection); if (m_bInitialized) { //We shutdown first so we can re-initialize. Shutdown(); } nRetVal = LinkInputStream::Init(pLinkControlEndpoint, streamType, nStreamID, pConnection); XN_IS_STATUS_OK_LOG_ERROR("Init base input stream", nRetVal); m_nStreamID = nStreamID; m_nUserBufferMaxSize = CONT_STREAM_PREDEFINED_BUFFER_SIZE; m_nUserBufferCurrentSize = m_nWorkingBufferCurrentSize = 0; //Allocate buffers m_pUserBuffer = reinterpret_cast<uint8_t*>(xnOSCallocAligned(1, m_nUserBufferMaxSize, XN_DEFAULT_MEM_ALIGN)); if (m_pUserBuffer == NULL) { Shutdown(); xnLogError(XN_MASK_INPUT_STREAM, "Failed to allocate buffer of size %u", m_nUserBufferMaxSize); XN_ASSERT(false); return XN_STATUS_ALLOC_FAILED; } m_pWorkingBuffer = reinterpret_cast<uint8_t*>(xnOSCallocAligned(1, CONT_STREAM_PREDEFINED_BUFFER_SIZE, XN_DEFAULT_MEM_ALIGN)); if (m_pWorkingBuffer == NULL) { Shutdown(); xnLogError(XN_MASK_INPUT_STREAM, "Failed to allocate buffer of size %u", m_nUserBufferMaxSize); XN_ASSERT(false); return XN_STATUS_ALLOC_FAILED; } nRetVal = xnLinkGetStreamDumpName(m_nStreamID, m_strDumpName, sizeof(m_strDumpName)); if (nRetVal != XN_STATUS_OK) { xnLogWarning(XN_MASK_INPUT_STREAM, "Failed to get stream dump name: %s", xnGetStatusString(nRetVal)); XN_ASSERT(false); } m_bInitialized = true; return XN_STATUS_OK; } bool LinkContInputStream::IsInitialized() const { return m_bInitialized; } void LinkContInputStream::Shutdown() { if (!m_bInitialized) return; xnOSEnterCriticalSection(&m_hCriticalSection); XN_ALIGNED_FREE_AND_NULL(m_pUserBuffer); XN_ALIGNED_FREE_AND_NULL(m_pWorkingBuffer); m_bInitialized = false; m_bNewDataAvailable = false; LinkInputStream::Shutdown(); xnOSLeaveCriticalSection(&m_hCriticalSection); } XnStatus LinkContInputStream::HandlePacket(const LinkPacketHeader& header, const uint8_t* pData, bool& bPacketLoss) { XnStatus nRetVal = XN_STATUS_OK; xnl::AutoCSLocker csLock(m_hCriticalSection); if (!m_bInitialized) { return XN_STATUS_NOT_INIT; } // TODO: handle packet loss! bPacketLoss = false; if(m_streamType == XN_LINK_STREAM_TYPE_LOG) { // begin parsing frame nRetVal = m_logParser.BeginParsing(m_pWorkingBuffer, CONT_STREAM_PREDEFINED_BUFFER_SIZE); XN_IS_STATUS_OK_LOG_ERROR("Begin parsing link log msg", nRetVal); nRetVal = m_logParser.ParsePacket(header, pData); if (nRetVal != XN_STATUS_OK) XN_IS_STATUS_OK_LOG_ERROR("Parse data from stream", nRetVal); } //Write new data to dump (if it's on) xnDumpFileWriteBuffer(m_pDumpFile, reinterpret_cast<const uint8_t*>(m_logParser.GetParsedData()), m_logParser.GetParsedSize()); if (header.GetFragmentationFlags() & XN_LINK_FRAG_END) { //Notify that we have new data available m_bNewDataAvailable = true; nRetVal = m_newDataAvailableEvent.Raise(); XN_IS_STATUS_OK_LOG_ERROR("Raise new data available event", nRetVal); } return XN_STATUS_OK; } const void* LinkContInputStream::GetData() const { return m_pUserBuffer; } uint32_t LinkContInputStream::GetDataSize() const { return m_nUserBufferCurrentSize; } const void* LinkContInputStream::GetNextData() const { static const uint64_t nDummy = 0; //TODO: Implement this properly for timestamps... XN_ASSERT(false); return &nDummy; } uint32_t LinkContInputStream::GetNextDataSize() const { return 0; } bool LinkContInputStream::IsNewDataAvailable() const { xnOSEnterCriticalSection(&m_hCriticalSection); if (!m_bInitialized) { return false; } bool bNewDataAvailable = m_bNewDataAvailable; xnOSLeaveCriticalSection(&m_hCriticalSection); return bNewDataAvailable; } XnStatus LinkContInputStream::StartImpl() { XnStatus nRetVal = XN_STATUS_OK; if (m_bStreaming) { return XN_STATUS_OK; } m_pDumpFile = xnDumpFileOpen(m_strDumpName, "%s", m_strDumpName); //We only need log buffer output if dumping is on m_logParser.GenerateOutputBuffer(m_pDumpFile != NULL); //We must set the streaming flag first cuz the data handler checks it m_bStreaming = true; nRetVal = m_pConnection->Connect(); XN_IS_STATUS_OK_LOG_ERROR("Connect stream's input connection", nRetVal); nRetVal = m_pLinkControlEndpoint->StartStreaming(m_nStreamID); XN_IS_STATUS_OK_LOG_ERROR("Start streaming", nRetVal); return XN_STATUS_OK; } XnStatus LinkContInputStream::StopImpl() { XnStatus nRetVal = XN_STATUS_OK; if (!m_bStreaming) { return XN_STATUS_OK; } nRetVal = m_pLinkControlEndpoint->StopStreaming(m_nStreamID); XN_IS_STATUS_OK_LOG_ERROR("Stop streaming", nRetVal); m_pConnection->Disconnect(); m_bStreaming = false; xnDumpFileClose(m_pDumpFile); return XN_STATUS_OK; } bool LinkContInputStream::IsStreaming() const { return m_bStreaming; } XnStatus LinkContInputStream::UpdateData() { xnl::AutoCSLocker csLock(m_hCriticalSection); if (!m_bInitialized) { xnLogError(XN_MASK_INPUT_STREAM, "Attempted to update data from stream %u which is not initialized", m_nStreamID); XN_ASSERT(false); return XN_STATUS_NOT_INIT; } if (m_bNewDataAvailable) { //Copy working buffer to user buffer xnOSMemCopy(m_pUserBuffer, m_pWorkingBuffer, m_nUserBufferMaxSize); m_nUserBufferCurrentSize = m_nWorkingBufferCurrentSize; m_bNewDataAvailable = false; } return XN_STATUS_OK; } XnStatus LinkContInputStream::RegisterToNewDataAvailable(NewDataAvailableHandler pHandler, void* pCookie, XnCallbackHandle& hCallback) { return m_newDataAvailableEvent.Register(pHandler, pCookie, hCallback); } void LinkContInputStream::UnregisterFromNewDataAvailable(XnCallbackHandle hCallback) { m_newDataAvailableEvent.Unregister(hCallback); } void LinkContInputStream::SetDumpName(const char* strDumpName) { XnStatus nRetVal = XN_STATUS_OK; (void)nRetVal; nRetVal = xnOSStrCopy(m_strDumpName, strDumpName, sizeof(m_strDumpName)); if (nRetVal != XN_STATUS_OK) { xnLogWarning(XN_MASK_INPUT_STREAM, "Failed to set dump name: %s", xnGetStatusString(nRetVal)); XN_ASSERT(false); } } void LinkContInputStream::SetDumpOn(bool bDumpOn) { XnStatus nRetVal = XN_STATUS_OK; (void)nRetVal; nRetVal = xnDumpSetMaskState(m_strDumpName, bDumpOn); if (nRetVal != XN_STATUS_OK) { xnLogWarning(XN_MASK_INPUT_STREAM, "Failed to set dump state: %s", xnGetStatusString(nRetVal)); XN_ASSERT(false); } } }
// Copyright (c) 2014-2018, The Monero Project // // 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. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 // THE COPYRIGHT HOLDER 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "ringct/rctSigs.h" #include "chaingen.h" #include "rct.h" #include "device/device.hpp" using namespace epee; using namespace crypto; using namespace cryptonote; //---------------------------------------------------------------------------------------------------------------------- // Tests bool gen_rct_tx_validation_base::generate_with(std::vector<test_event_entry>& events, const int *out_idx, int mixin, uint64_t amount_paid, bool valid, const std::function<void(std::vector<tx_source_entry> &sources, std::vector<tx_destination_entry> &destinations)> &pre_tx, const std::function<void(transaction &tx)> &post_tx) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); // create 4 miner accounts, and have them mine the next 4 blocks cryptonote::account_base miner_accounts[4]; const cryptonote::block *prev_block = &blk_0; cryptonote::block blocks[4]; for (size_t n = 0; n < 4; ++n) { miner_accounts[n].generate(); CHECK_AND_ASSERT_MES(generator.construct_block_manually(blocks[n], *prev_block, miner_accounts[n], test_generator::bf_major_ver | test_generator::bf_minor_ver | test_generator::bf_timestamp | test_generator::bf_hf_version, 2, 2, prev_block->timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN * 2, // v2 has blocks twice as long crypto::hash(), 0, transaction(), std::vector<crypto::hash>(), 0), false, "Failed to generate block"); events.push_back(blocks[n]); prev_block = blocks + n; LOG_PRINT_L0("Initial miner tx " << n << ": " << obj_to_json_str(blocks[n].miner_tx)); } // rewind cryptonote::block blk_r, blk_last; { blk_last = blocks[3]; for (size_t i = 0; i < CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW; ++i) { cryptonote::block blk; CHECK_AND_ASSERT_MES(generator.construct_block_manually(blk, blk_last, miner_account, test_generator::bf_major_ver | test_generator::bf_minor_ver | test_generator::bf_timestamp | test_generator::bf_hf_version, 2, 2, blk_last.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN * 2, // v2 has blocks twice as long crypto::hash(), 0, transaction(), std::vector<crypto::hash>(), 0), false, "Failed to generate block"); events.push_back(blk); blk_last = blk; } blk_r = blk_last; } // create 4 txes from these miners in another block, to generate some rct outputs transaction rct_txes[4]; rct::key rct_tx_masks[16]; cryptonote::block blk_txes[4]; for (size_t n = 0; n < 4; ++n) { std::vector<crypto::hash> starting_rct_tx_hashes; std::vector<tx_source_entry> sources; sources.resize(1); tx_source_entry& src = sources.back(); const size_t index_in_tx = 5; src.amount = 30000000000000; for (int m = 0; m < 4; ++m) { src.push_output(m, boost::get<txout_to_key>(blocks[m].miner_tx.vout[index_in_tx].target).key, src.amount); } src.real_out_tx_key = cryptonote::get_tx_pub_key_from_extra(blocks[n].miner_tx); src.real_output = n; src.real_output_in_tx_index = index_in_tx; src.mask = rct::identity(); src.rct = false; //fill outputs entry tx_destination_entry td; td.addr = miner_accounts[n].get_keys().m_account_address; td.amount = 7390000000000; std::vector<tx_destination_entry> destinations; destinations.push_back(td); destinations.push_back(td); destinations.push_back(td); destinations.push_back(td); // 30 -> 7.39 * 4 crypto::secret_key tx_key; std::vector<crypto::secret_key> additional_tx_keys; std::unordered_map<crypto::public_key, cryptonote::subaddress_index> subaddresses; subaddresses[miner_accounts[n].get_keys().m_account_address.m_spend_public_key] = {0,0}; kredits_construct_tx_params tx_params; tx_params.hf_version = cryptonote::network_version_8; bool r = construct_tx_and_get_tx_key(miner_accounts[n].get_keys(), subaddresses, sources, destinations, cryptonote::tx_destination_entry{}, std::vector<uint8_t>(), rct_txes[n], 0, tx_key, additional_tx_keys, {}, nullptr, tx_params); CHECK_AND_ASSERT_MES(r, false, "failed to construct transaction"); events.push_back(rct_txes[n]); starting_rct_tx_hashes.push_back(get_transaction_hash(rct_txes[n])); for (size_t o = 0; o < 4; ++o) { crypto::key_derivation derivation; bool r = crypto::generate_key_derivation(destinations[o].addr.m_view_public_key, tx_key, derivation); CHECK_AND_ASSERT_MES(r, false, "Failed to generate key derivation"); crypto::secret_key amount_key; crypto::derivation_to_scalar(derivation, o, amount_key); const uint8_t type = rct_txes[n].rct_signatures.type; if (type == rct::RCTTypeSimple || type == rct::RCTTypeBulletproof || type == rct::RCTTypeBulletproof2) rct::decodeRctSimple(rct_txes[n].rct_signatures, rct::sk2rct(amount_key), o, rct_tx_masks[o+n*4], hw::get_device("default")); else rct::decodeRct(rct_txes[n].rct_signatures, rct::sk2rct(amount_key), o, rct_tx_masks[o+n*4], hw::get_device("default")); } CHECK_AND_ASSERT_MES(generator.construct_block_manually(blk_txes[n], blk_last, miner_account, test_generator::bf_major_ver | test_generator::bf_minor_ver | test_generator::bf_timestamp | test_generator::bf_tx_hashes | test_generator::bf_hf_version, 4, 4, blk_last.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN * 2, // v2 has blocks twice as long crypto::hash(), 0, transaction(), starting_rct_tx_hashes, 0), false, "Failed to generate block"); events.push_back(blk_txes[n]); blk_last = blk_txes[n]; } // rewind { for (size_t i = 0; i < CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW; ++i) { cryptonote::block blk; CHECK_AND_ASSERT_MES(generator.construct_block_manually(blk, blk_last, miner_account, test_generator::bf_major_ver | test_generator::bf_minor_ver | test_generator::bf_timestamp | test_generator::bf_hf_version, 4, 4, blk_last.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN * 2, // v2 has blocks twice as long crypto::hash(), 0, transaction(), std::vector<crypto::hash>(), 0), false, "Failed to generate block"); events.push_back(blk); blk_last = blk; } blk_r = blk_last; } // create a tx from the requested ouputs std::vector<tx_source_entry> sources; size_t global_rct_idx = 6; // skip first coinbase (6 outputs) size_t rct_idx = 0; size_t pre_rct_idx = 0; for (size_t out_idx_idx = 0; out_idx[out_idx_idx] >= 0; ++out_idx_idx) { sources.resize(sources.size()+1); tx_source_entry& src = sources.back(); src.real_output = 0; if (out_idx[out_idx_idx]) { // rct src.amount = 7390000000000; src.real_out_tx_key = get_tx_pub_key_from_extra(rct_txes[rct_idx/4]); src.real_output_in_tx_index = rct_idx&3; src.mask = rct_tx_masks[rct_idx]; src.rct = true; for (int m = 0; m <= mixin; ++m) { rct::ctkey ctkey; ctkey.dest = rct::pk2rct(boost::get<txout_to_key>(rct_txes[rct_idx/4].vout[rct_idx&3].target).key); ctkey.mask = rct_txes[rct_idx/4].rct_signatures.outPk[rct_idx&3].mask; src.outputs.push_back(std::make_pair(global_rct_idx, ctkey)); ++rct_idx; ++global_rct_idx; if (global_rct_idx % 10 == 0) global_rct_idx += 6; // skip the coinbase } } else { // pre rct src.amount = 5000000000000; src.real_out_tx_key = cryptonote::get_tx_pub_key_from_extra(blocks[pre_rct_idx].miner_tx); src.real_output_in_tx_index = 4; src.mask = rct::identity(); src.rct = false; for (int m = 0; m <= mixin; ++m) { src.push_output(m, boost::get<txout_to_key>(blocks[pre_rct_idx].miner_tx.vout[4].target).key, src.amount); ++pre_rct_idx; } } } //fill outputs entry tx_destination_entry td; td.addr = miner_account.get_keys().m_account_address; td.amount = amount_paid; std::vector<tx_destination_entry> destinations; destinations.push_back(td); if (pre_tx) pre_tx(sources, destinations); transaction tx; crypto::secret_key tx_key; std::vector<crypto::secret_key> additional_tx_keys; std::unordered_map<crypto::public_key, cryptonote::subaddress_index> subaddresses; subaddresses[miner_accounts[0].get_keys().m_account_address.m_spend_public_key] = {0,0}; kredits_construct_tx_params tx_params; tx_params.hf_version = cryptonote::network_version_8; bool r = construct_tx_and_get_tx_key(miner_accounts[0].get_keys(), subaddresses, sources, destinations, cryptonote::tx_destination_entry{}, std::vector<uint8_t>(), tx, 0, tx_key, additional_tx_keys, {}, nullptr, tx_params); CHECK_AND_ASSERT_MES(r, false, "failed to construct transaction"); if (post_tx) post_tx(tx); if (!valid) DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(tx); LOG_PRINT_L0("Test tx: " << obj_to_json_str(tx)); return true; } bool gen_rct_tx_valid_from_pre_rct::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, true, NULL, NULL); } bool gen_rct_tx_valid_from_rct::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, true, NULL, NULL); } bool gen_rct_tx_valid_from_mixed::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, 0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, true, NULL, NULL); } bool gen_rct_tx_pre_rct_bad_real_dest::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; bool tx_creation_succeeded = false; // in the case, the tx will fail to create, due to mismatched sk/pk bool ret = generate_with(events, out_idx, mixin, amount_paid, false, [](std::vector<tx_source_entry> &sources, std::vector<tx_destination_entry> &destinations) {rct::key sk; rct::skpkGen(sk, sources[0].outputs[0].second.dest);}, [&tx_creation_succeeded](const transaction &tx){tx_creation_succeeded=true;}); return !ret && !tx_creation_succeeded; } bool gen_rct_tx_pre_rct_bad_real_mask::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, [](std::vector<tx_source_entry> &sources, std::vector<tx_destination_entry> &destinations) {sources[0].outputs[0].second.mask = rct::zeroCommit(99999);}, NULL); } bool gen_rct_tx_pre_rct_bad_fake_dest::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, [](std::vector<tx_source_entry> &sources, std::vector<tx_destination_entry> &destinations) {rct::key sk; rct::skpkGen(sk, sources[0].outputs[1].second.dest);}, NULL); } bool gen_rct_tx_pre_rct_bad_fake_mask::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, [](std::vector<tx_source_entry> &sources, std::vector<tx_destination_entry> &destinations) {sources[0].outputs[1].second.mask = rct::zeroCommit(99999);}, NULL); } bool gen_rct_tx_rct_bad_real_dest::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; bool tx_creation_succeeded = false; // in the case, the tx will fail to create, due to mismatched sk/pk bool ret = generate_with(events, out_idx, mixin, amount_paid, false, [](std::vector<tx_source_entry> &sources, std::vector<tx_destination_entry> &destinations) {rct::key sk; rct::skpkGen(sk, sources[0].outputs[0].second.dest);}, [&tx_creation_succeeded](const transaction &tx){tx_creation_succeeded=true;}); return !ret && !tx_creation_succeeded; } bool gen_rct_tx_rct_bad_real_mask::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, [](std::vector<tx_source_entry> &sources, std::vector<tx_destination_entry> &destinations) {sources[0].outputs[0].second.mask = rct::zeroCommit(99999);}, NULL); } bool gen_rct_tx_rct_bad_fake_dest::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, [](std::vector<tx_source_entry> &sources, std::vector<tx_destination_entry> &destinations) {rct::key sk; rct::skpkGen(sk, sources[0].outputs[1].second.dest);}, NULL); } bool gen_rct_tx_rct_bad_fake_mask::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, [](std::vector<tx_source_entry> &sources, std::vector<tx_destination_entry> &destinations) {sources[0].outputs[1].second.mask = rct::zeroCommit(99999);}, NULL); } bool gen_rct_tx_rct_spend_with_zero_commit::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, [](std::vector<tx_source_entry> &sources, std::vector<tx_destination_entry> &destinations) {sources[0].outputs[0].second.mask = rct::zeroCommit(sources[0].amount); sources[0].mask = rct::identity();}, [](transaction &tx){boost::get<txin_to_key>(tx.vin[0]).amount = 0;}); } bool gen_rct_tx_pre_rct_zero_vin_amount::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {boost::get<txin_to_key>(tx.vin[0]).amount = 0;}); } bool gen_rct_tx_rct_non_zero_vin_amount::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {boost::get<txin_to_key>(tx.vin[0]).amount = 5000000000000;}); // one that we know exists } bool gen_rct_tx_non_zero_vout_amount::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {tx.vout[0].amount = 5000000000000;}); // one that we know exists } bool gen_rct_tx_pre_rct_duplicate_key_image::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [&events](transaction &tx) {boost::get<txin_to_key>(tx.vin[0]).k_image = boost::get<txin_to_key>(boost::get<transaction>(events[67]).vin[0]).k_image;}); } bool gen_rct_tx_rct_duplicate_key_image::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [&events](transaction &tx) {boost::get<txin_to_key>(tx.vin[0]).k_image = boost::get<txin_to_key>(boost::get<transaction>(events[67]).vin[0]).k_image;}); } bool gen_rct_tx_pre_rct_wrong_key_image::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; // some random key image from the monero blockchain, so we get something that is a valid key image static const uint8_t k_image[33] = "\x49\x3b\x56\x16\x54\x76\xa8\x75\xb7\xf4\xa8\x51\xf5\x55\xd3\x44\xe7\x3e\xea\x73\xee\xc1\x06\x7c\x7d\xb6\x57\x28\x46\x85\xe1\x07"; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {memcpy(&boost::get<txin_to_key>(tx.vin[0]).k_image, k_image, 32);}); } bool gen_rct_tx_rct_wrong_key_image::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; // some random key image from the monero blockchain, so we get something that is a valid key image static const uint8_t k_image[33] = "\x49\x3b\x56\x16\x54\x76\xa8\x75\xb7\xf4\xa8\x51\xf5\x55\xd3\x44\xe7\x3e\xea\x73\xee\xc1\x06\x7c\x7d\xb6\x57\x28\x46\x85\xe1\x07"; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {memcpy(&boost::get<txin_to_key>(tx.vin[0]).k_image, k_image, 32);}); } bool gen_rct_tx_pre_rct_wrong_fee::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {tx.rct_signatures.txnFee++;}); } bool gen_rct_tx_rct_wrong_fee::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {tx.rct_signatures.txnFee++;}); } bool gen_rct_tx_pre_rct_increase_vin_and_fee::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {boost::get<txin_to_key>(tx.vin[0]).amount++;tx.rct_signatures.txnFee++;}); } bool gen_rct_tx_pre_rct_remove_vin::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {tx.vin.pop_back();}); } bool gen_rct_tx_rct_remove_vin::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {tx.vin.pop_back();}); } bool gen_rct_tx_pre_rct_add_vout::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {tx.vout.push_back(tx.vout.back());}); } bool gen_rct_tx_rct_add_vout::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [](transaction &tx) {tx.vout.push_back(tx.vout.back());}); } bool gen_rct_tx_pre_rct_altered_extra::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {0, -1}; const uint64_t amount_paid = 10000; bool failed = false; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [&failed](transaction &tx) {std::string extra_nonce; crypto::hash pid = crypto::null_hash; set_payment_id_to_tx_extra_nonce(extra_nonce, pid); if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce)) failed = true; }) && !failed; } bool gen_rct_tx_rct_altered_extra::generate(std::vector<test_event_entry>& events) const { const int mixin = 2; const int out_idx[] = {1, -1}; const uint64_t amount_paid = 10000; bool failed = false; return generate_with(events, out_idx, mixin, amount_paid, false, NULL, [&failed](transaction &tx) {std::string extra_nonce; crypto::hash pid = crypto::null_hash; set_payment_id_to_tx_extra_nonce(extra_nonce, pid); if (!add_extra_nonce_to_tx_extra(tx.extra, extra_nonce)) failed = true; }) && !failed; }
#include <memory> #include "gtest/gtest.h" #include "mathFunctions/functionFactory.hpp" namespace ablateTesting::mathFunctions { TEST(FunctionFactoryTests, ShouldCreateFunctionForStatelessLambda) { // arrange auto function = ablate::mathFunctions::Create([](int dim, double time, auto loc, int nf, auto u, auto ctx) { u[0] = loc[0] + loc[1] + loc[2] + time; return 0; }); // act/assert ASSERT_TRUE(std::dynamic_pointer_cast<ablate::mathFunctions::FunctionPointer>(function) != nullptr); ASSERT_DOUBLE_EQ(10.0, function->Eval(1.0, 2.0, 3.0, 4.0)); } TEST(FunctionFactoryTests, ShouldCreateFunctionForStatefullLambda) { // arrange double offset; auto function = ablate::mathFunctions::Create([&offset](int dim, double time, auto loc, int nf, auto u, auto ctx) { u[0] = loc[0] + loc[1] + loc[2] + time + offset; return 0; }); offset = 2; // act/assert ASSERT_TRUE(std::dynamic_pointer_cast<ablate::mathFunctions::FunctionWrapper>(function) != nullptr); ASSERT_DOUBLE_EQ(12.0, function->Eval(1.0, 2.0, 3.0, 4.0)); } TEST(FunctionFactoryTests, ShouldCreateFunctionForParsedString) { // arrange auto function = ablate::mathFunctions::Create("x + y + z +t"); // act/assert ASSERT_TRUE(std::dynamic_pointer_cast<ablate::mathFunctions::ParsedFunction>(function) != nullptr); ASSERT_DOUBLE_EQ(10.0, function->Eval(1.0, 2.0, 3.0, 4.0)); } static PetscErrorCode ExamplePetscFunction(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar* u, void* ctx) { u[0] = x[0] + x[1] + x[2] + time; return 0; } TEST(FunctionFactoryTests, ShouldCreateFunctionFromFunction) { // arrange auto function = ablate::mathFunctions::Create(ExamplePetscFunction); // act/assert ASSERT_TRUE(std::dynamic_pointer_cast<ablate::mathFunctions::FunctionPointer>(function) != nullptr); ASSERT_DOUBLE_EQ(10.0, function->Eval(1.0, 2.0, 3.0, 4.0)); } } // namespace ablateTesting::mathFunctions
#include "GWidget.h" #include "GEvent.h" #include "GEventLoop.h" #include "GWindow.h" #include <AK/Assertions.h> #include <AK/JsonObject.h> #include <LibGUI/GAction.h> #include <LibGUI/GApplication.h> #include <LibGUI/GLayout.h> #include <LibGUI/GMenu.h> #include <LibGUI/GPainter.h> #include <LibDraw/GraphicsBitmap.h> #include <unistd.h> GWidget::GWidget(GWidget* parent) : CObject(parent, true) , m_font(Font::default_font()) { m_background_color = Color::WarmGray; m_foreground_color = Color::Black; } GWidget::~GWidget() { } void GWidget::child_event(CChildEvent& event) { if (event.type() == GEvent::ChildAdded) { if (event.child() && is<GWidget>(*event.child()) && layout()) layout()->add_widget(to<GWidget>(*event.child())); } if (event.type() == GEvent::ChildRemoved) { if (layout()) { if (event.child() && is<GWidget>(*event.child())) layout()->remove_widget(to<GWidget>(*event.child())); else invalidate_layout(); } update(); } return CObject::child_event(event); } void GWidget::set_relative_rect(const Rect& rect) { if (rect == m_relative_rect) return; auto old_rect = m_relative_rect; bool size_changed = m_relative_rect.size() != rect.size(); m_relative_rect = rect; if (size_changed) { GResizeEvent resize_event(m_relative_rect.size(), rect.size()); event(resize_event); } if (auto* parent = parent_widget()) parent->update(old_rect); update(); } void GWidget::event(CEvent& event) { switch (event.type()) { case GEvent::Paint: return handle_paint_event(static_cast<GPaintEvent&>(event)); case GEvent::Resize: return handle_resize_event(static_cast<GResizeEvent&>(event)); case GEvent::FocusIn: return focusin_event(event); case GEvent::FocusOut: return focusout_event(event); case GEvent::Show: return show_event(static_cast<GShowEvent&>(event)); case GEvent::Hide: return hide_event(static_cast<GHideEvent&>(event)); case GEvent::KeyDown: return keydown_event(static_cast<GKeyEvent&>(event)); case GEvent::KeyUp: return keyup_event(static_cast<GKeyEvent&>(event)); case GEvent::MouseMove: return mousemove_event(static_cast<GMouseEvent&>(event)); case GEvent::MouseDown: return handle_mousedown_event(static_cast<GMouseEvent&>(event)); case GEvent::MouseDoubleClick: return handle_mousedoubleclick_event(static_cast<GMouseEvent&>(event)); case GEvent::MouseUp: return handle_mouseup_event(static_cast<GMouseEvent&>(event)); case GEvent::MouseWheel: return mousewheel_event(static_cast<GMouseEvent&>(event)); case GEvent::Enter: return handle_enter_event(event); case GEvent::Leave: return handle_leave_event(event); case GEvent::EnabledChange: return change_event(static_cast<GEvent&>(event)); default: return CObject::event(event); } } void GWidget::handle_paint_event(GPaintEvent& event) { ASSERT(is_visible()); if (fill_with_background_color()) { GPainter painter(*this); painter.fill_rect(event.rect(), background_color()); } else { #ifdef DEBUG_WIDGET_UNDERDRAW // FIXME: This is a bit broken. // If the widget is not opaque, let's not mess it up with debugging color. GPainter painter(*this); painter.fill_rect(rect(), Color::Red); #endif } paint_event(event); for_each_child_widget([&](auto& child) { if (!child.is_visible()) return IterationDecision::Continue; if (child.relative_rect().intersects(event.rect())) { GPaintEvent local_event(event.rect().intersected(child.relative_rect()).translated(-child.relative_position())); child.event(local_event); } return IterationDecision::Continue; }); second_paint_event(event); } void GWidget::set_layout(OwnPtr<GLayout>&& layout) { if (m_layout) m_layout->notify_disowned({}, *this); m_layout = move(layout); if (m_layout) { m_layout->notify_adopted({}, *this); do_layout(); } else { update(); } } void GWidget::do_layout() { custom_layout(); if (!m_layout) return; m_layout->run(*this); update(); } void GWidget::notify_layout_changed(Badge<GLayout>) { invalidate_layout(); } void GWidget::handle_resize_event(GResizeEvent& event) { do_layout(); return resize_event(event); } void GWidget::handle_mouseup_event(GMouseEvent& event) { mouseup_event(event); } void GWidget::handle_mousedown_event(GMouseEvent& event) { if (accepts_focus()) set_focus(true); mousedown_event(event); if (event.button() == GMouseButton::Right) { GContextMenuEvent c_event(event.position(), screen_relative_rect().location().translated(event.position())); context_menu_event(c_event); } } void GWidget::handle_mousedoubleclick_event(GMouseEvent& event) { doubleclick_event(event); } void GWidget::handle_enter_event(CEvent& event) { if (has_tooltip()) GApplication::the().show_tooltip(m_tooltip, screen_relative_rect().center().translated(0, height() / 2)); enter_event(event); } void GWidget::handle_leave_event(CEvent& event) { GApplication::the().hide_tooltip(); leave_event(event); } void GWidget::click_event(GMouseEvent&) { } void GWidget::doubleclick_event(GMouseEvent&) { } void GWidget::resize_event(GResizeEvent&) { } void GWidget::paint_event(GPaintEvent&) { } void GWidget::second_paint_event(GPaintEvent&) { } void GWidget::show_event(GShowEvent&) { } void GWidget::hide_event(GHideEvent&) { } void GWidget::keydown_event(GKeyEvent& event) { if (!event.alt() && !event.ctrl() && !event.logo() && event.key() == KeyCode::Key_Tab) { if (event.shift()) focus_previous_widget(); else focus_next_widget(); } } void GWidget::keyup_event(GKeyEvent&) { } void GWidget::mousedown_event(GMouseEvent&) { } void GWidget::mouseup_event(GMouseEvent&) { } void GWidget::mousemove_event(GMouseEvent&) { } void GWidget::mousewheel_event(GMouseEvent&) { } void GWidget::context_menu_event(GContextMenuEvent&) { } void GWidget::focusin_event(CEvent&) { } void GWidget::focusout_event(CEvent&) { } void GWidget::enter_event(CEvent&) { } void GWidget::leave_event(CEvent&) { } void GWidget::change_event(GEvent&) { } void GWidget::update() { if (rect().is_empty()) return; update(rect()); } void GWidget::update(const Rect& rect) { if (!is_visible()) return; if (!updates_enabled()) return; GWindow* window = m_window; GWidget* parent = parent_widget(); while (parent) { if (!parent->updates_enabled()) return; window = parent->m_window; parent = parent->parent_widget(); } if (window) window->update(rect.translated(window_relative_rect().location())); } Rect GWidget::window_relative_rect() const { auto rect = relative_rect(); for (auto* parent = parent_widget(); parent; parent = parent->parent_widget()) { rect.move_by(parent->relative_position()); } return rect; } Rect GWidget::screen_relative_rect() const { return window_relative_rect().translated(window()->position()); } GWidget* GWidget::child_at(const Point& point) const { for (int i = children().size() - 1; i >= 0; --i) { if (!is<GWidget>(*children()[i])) continue; auto& child = to<GWidget>(*children()[i]); if (!child.is_visible()) continue; if (child.relative_rect().contains(point)) return &child; } return nullptr; } GWidget::HitTestResult GWidget::hit_test(const Point& position) { if (is_greedy_for_hits()) return { this, position }; if (auto* child = child_at(position)) return child->hit_test(position - child->relative_position()); return { this, position }; } void GWidget::set_window(GWindow* window) { if (m_window == window) return; m_window = window; } bool GWidget::is_focused() const { auto* win = window(); if (!win) return false; if (!win->is_active()) return false; return win->focused_widget() == this; } void GWidget::set_focus(bool focus) { auto* win = window(); if (!win) return; if (focus) { win->set_focused_widget(this); } else { if (win->focused_widget() == this) win->set_focused_widget(nullptr); } } void GWidget::set_font(const Font* font) { if (m_font.ptr() == font) return; if (!font) m_font = Font::default_font(); else m_font = *font; did_change_font(); update(); } void GWidget::set_global_cursor_tracking(bool enabled) { auto* win = window(); if (!win) return; win->set_global_cursor_tracking_widget(enabled ? this : nullptr); } bool GWidget::global_cursor_tracking() const { auto* win = window(); if (!win) return false; return win->global_cursor_tracking_widget() == this; } void GWidget::set_preferred_size(const Size& size) { if (m_preferred_size == size) return; m_preferred_size = size; invalidate_layout(); } void GWidget::set_size_policy(Orientation orientation, SizePolicy policy) { if (orientation == Orientation::Horizontal) set_size_policy(policy, m_vertical_size_policy); else set_size_policy(m_horizontal_size_policy, policy); } void GWidget::set_size_policy(SizePolicy horizontal_policy, SizePolicy vertical_policy) { if (m_horizontal_size_policy == horizontal_policy && m_vertical_size_policy == vertical_policy) return; m_horizontal_size_policy = horizontal_policy; m_vertical_size_policy = vertical_policy; invalidate_layout(); } void GWidget::invalidate_layout() { if (m_layout_dirty) return; m_layout_dirty = true; deferred_invoke([this](auto&) { m_layout_dirty = false; auto* w = window(); if (!w) return; if (!w->main_widget()) return; do_layout(); w->main_widget()->do_layout(); }); } void GWidget::set_visible(bool visible) { if (visible == m_visible) return; m_visible = visible; if (auto* parent = parent_widget()) parent->invalidate_layout(); if (m_visible) update(); } bool GWidget::spans_entire_window_horizontally() const { auto* w = window(); if (!w) return false; auto* main_widget = w->main_widget(); if (!main_widget) return false; if (main_widget == this) return true; auto wrr = window_relative_rect(); return wrr.left() == main_widget->rect().left() && wrr.right() == main_widget->rect().right(); } void GWidget::set_enabled(bool enabled) { if (m_enabled == enabled) return; m_enabled = enabled; GEvent e(GEvent::EnabledChange); event(e); update(); } void GWidget::move_to_front() { auto* parent = parent_widget(); if (!parent) return; if (parent->children().size() == 1) return; parent->children().remove_first_matching([this](auto& entry) { return entry == this; }); parent->children().append(this); parent->update(); } void GWidget::move_to_back() { auto* parent = parent_widget(); if (!parent) return; if (parent->children().size() == 1) return; parent->children().remove_first_matching([this](auto& entry) { return entry == this; }); parent->children().prepend(this); parent->update(); } bool GWidget::is_frontmost() const { auto* parent = parent_widget(); if (!parent) return true; return parent->children().last() == this; } bool GWidget::is_backmost() const { auto* parent = parent_widget(); if (!parent) return true; return parent->children().first() == this; } GAction* GWidget::action_for_key_event(const GKeyEvent& event) { auto it = m_local_shortcut_actions.find(GShortcut(event.modifiers(), (KeyCode)event.key())); if (it == m_local_shortcut_actions.end()) return nullptr; return (*it).value; } void GWidget::register_local_shortcut_action(Badge<GAction>, GAction& action) { m_local_shortcut_actions.set(action.shortcut(), &action); } void GWidget::unregister_local_shortcut_action(Badge<GAction>, GAction& action) { m_local_shortcut_actions.remove(action.shortcut()); } void GWidget::set_updates_enabled(bool enabled) { if (m_updates_enabled == enabled) return; m_updates_enabled = enabled; if (enabled) update(); } void GWidget::focus_previous_widget() { auto focusable_widgets = window()->focusable_widgets(); for (int i = focusable_widgets.size() - 1; i >= 0; --i) { if (focusable_widgets[i] != this) continue; if (i > 0) focusable_widgets[i - 1]->set_focus(true); else focusable_widgets.last()->set_focus(true); } } void GWidget::focus_next_widget() { auto focusable_widgets = window()->focusable_widgets(); for (int i = 0; i < focusable_widgets.size(); ++i) { if (focusable_widgets[i] != this) continue; if (i < focusable_widgets.size() - 1) focusable_widgets[i + 1]->set_focus(true); else focusable_widgets.first()->set_focus(true); } } void GWidget::set_backcolor(const StringView& color_string) { auto color = Color::from_string(color_string); if (!color.has_value()) return; set_background_color(color.value()); } void GWidget::set_forecolor(const StringView& color_string) { auto color = Color::from_string(color_string); if (!color.has_value()) return; set_foreground_color(color.value()); } void GWidget::save_to(AK::JsonObject& json) { json.set("relative_rect", relative_rect().to_string()); json.set("fill_with_background_color", fill_with_background_color()); json.set("tooltip", tooltip()); json.set("visible", is_visible()); json.set("focused", is_focused()); json.set("enabled", is_enabled()); json.set("background_color", background_color().to_string()); json.set("foreground_color", foreground_color().to_string()); json.set("preferred_size", preferred_size().to_string()); json.set("size_policy", String::format("[%s,%s]", to_string(horizontal_size_policy()), to_string(vertical_size_policy()))); CObject::save_to(json); }
#include <stan/math/rev/mat.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/mat/fun/util.hpp> #include <test/unit/math/rev/mat/util.hpp> TEST(AgradRevMatrix,eigenval_sum) { using stan::math::sum; using stan::math::matrix_v; using stan::math::vector_v; using stan::math::eigenvalues_sym; matrix_v a(3,3); a << 1.0, 2.0, 3.0, 2.0, 5.0, 7.9, 3.0, 7.9, 1.08; AVEC x = createAVEC(a(0,0), a(1,1), a(2,2), a(1,2)); x.push_back(a(0,1)); x.push_back(a(2,0)); // grad sum eig = I vector_v a_eigenvalues = eigenvalues_sym(a); AVAR sum_a_eigenvalues = sum(a_eigenvalues); VEC g = cgradvec(sum_a_eigenvalues,x); EXPECT_NEAR(1.0,g[0],1.0E-11); EXPECT_NEAR(1.0,g[1],1.0E-11); EXPECT_NEAR(1.0,g[2],1.0E-11); EXPECT_NEAR(0.0,g[3],1.0E-10); EXPECT_NEAR(0.0,g[4],1.0E-10); EXPECT_NEAR(0.0,g[5],1.0E-10); } TEST(AgradRevMatrix, check_varis_on_stack) { using stan::math::matrix_v; using stan::math::eigenvalues_sym; matrix_v a(3,3); a << 1.0, 2.0, 3.0, 2.0, 5.0, 7.9, 3.0, 7.9, 1.08; test::check_varis_on_stack(stan::math::eigenvalues_sym(a)); }
//================================================================================================= /*! // \file src/mathtest/smatsmatadd/LCaDCb.cpp // \brief Source file for the LCaDCb sparse matrix/sparse matrix addition math test // // Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/DiagonalMatrix.h> #include <blaze/math/LowerMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatsmatadd/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'LCaDCb'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions typedef blaze::LowerMatrix< blaze::CompressedMatrix<TypeA> > LCa; typedef blaze::DiagonalMatrix< blaze::CompressedMatrix<TypeB> > DCb; // Creator type definitions typedef blazetest::Creator<LCa> CLCa; typedef blazetest::Creator<DCb> CDCb; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=LCa::maxNonZeros( i ); ++j ) { for( size_t k=0UL; k<=i; ++k ) { RUN_SMATSMATADD_OPERATION_TEST( CLCa( i, j ), CDCb( i, k ) ); } } } // Running tests with large matrices RUN_SMATSMATADD_OPERATION_TEST( CLCa( 67UL, 7UL ), CDCb( 67UL, 13UL ) ); RUN_SMATSMATADD_OPERATION_TEST( CLCa( 128UL, 16UL ), CDCb( 128UL, 8UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix addition:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ #include "image.h" #include "condor_common.h" #include "condor_syscalls.h" #include "condor_sys.h" #include "condor_syscall_mode.h" #include "condor_debug.h" #include "file_state.h" #include "file_table_interf.h" #include "condor_file.h" #include "condor_file_local.h" #include "condor_file_fd.h" #include "condor_file_remote.h" #include "condor_file_special.h" #include "condor_file_agent.h" #include "condor_file_buffer.h" #include "condor_file_compress.h" #include "condor_file_append.h" #include "condor_error.h" #include <stdarg.h> #include <sys/errno.h> /* These are the remote system calls we use in this file */ extern "C" int REMOTE_CONDOR_report_file_info_new(char *name, long long open_count, long long read_count, long long write_count, long long seek_count, long long read_bytes, long long write_bytes); extern "C" int REMOTE_CONDOR_get_file_info_new(char *logical_name, char *&actual_url); extern "C" int REMOTE_CONDOR_get_buffer_info(int *bytes, int *block_size, int *prefetch_size); extern "C" int REMOTE_CONDOR_chdir(const char *path); CondorFileTable *FileTab=0; /** This class records statistics about how a file is used. It is kept around even after a file is closed so that it may be re-used and updated for multiple opens. The class definition is placed here because the implementation is entirely private to this module. */ class CondorFileInfo { public: CondorFileInfo( const char *n ) { info_name = strdup(n); open_count = 0; read_count = read_bytes = 0; write_count = write_bytes = 0; seek_count = 0; already_warned = 0; next = 0; } ~CondorFileInfo() { free( info_name ); } void report() { if( RemoteSysCalls() ) { REMOTE_CONDOR_report_file_info_new( info_name, open_count, read_count, write_count, seek_count, read_bytes, write_bytes ); } } // IMPORTANT NOTE: // This name is not necessarily the same as the logical // name of the file with which it is associated. After // a certain number of files are opened, one block // named "everything else" is shared between all open files. char *info_name; long long open_count; long long read_count, read_bytes; long long write_count, write_bytes; long long seek_count; int already_warned; CondorFileInfo *next; }; /** This class maintains a seek pointer which sits between a file descriptor and a file implementation. Several file descriptors may share one file pointer. It also associates a File object with a FileInfo object. This class is a helper for CondorFileTable. The class definition is placed here because the implementation is entirely private to this module. */ class CondorFilePointer { public: CondorFilePointer( CondorFile *f, CondorFileInfo *i, int fl, const char *n ) { file = f; info = i; flags = fl; offset = 0; logical_name = strdup( n ); } ~CondorFilePointer() { free( logical_name ); } CondorFile *file; CondorFileInfo *info; int flags; off_t offset; char *logical_name; }; /* We register this function to be the last thing executed before a job exits. Here, we call fflush() to force all the stio buffers into the Condor buffers, and then close all the files. We are obliged to close all of our files manually, because several file types have commit semantics that only force data when a file Anything output after this point will be lost, so users relying on output from global destructors will be disappointed. */ static void _condor_file_table_shutdown() { fflush(0); FileTab->close_all(); FileTab->report_all(); } /* This init function could be called from just about anywhere, perhaps even when there is no shadow to talk to. We will delay initializing a buffer until we do the first remote open. Each of the standard file descriptors will be connected to their local analogues until further notice. */ void CondorFileTable::init() { got_buffer_info = 0; buffer_size = 0; buffer_block_size = 0; info_count = 0; aggravate_mode = 0; int scm = SetSyscalls( SYS_UNMAPPED | SYS_LOCAL ); length = sysconf(_SC_OPEN_MAX); SetSyscalls(scm); pointers = new CondorFilePointer *[length]; if(!pointers) { _condor_error_retry("Out of memory!\n"); } for( int i=0; i<length; i++ ) { pointers[i]=0; } info_head = 0; pointers[0] = new CondorFilePointer(0,make_info("default stdin"),O_RDONLY,"default stdin"); pointers[1] = new CondorFilePointer(0,make_info("default stdout"),O_WRONLY,"default stdout"); pointers[2] = new CondorFilePointer(0,make_info("default stderr"),O_WRONLY,"default stderr"); working_dir = strdup("."); atexit( _condor_file_table_shutdown ); } void CondorFileTable::flush() { for( int i=0; i<length; i++ ) { if( pointers[i] ) { if( pointers[i]->file ) { pointers[i]->file->flush(); } } } } void CondorFileTable::report_all() { CondorFileInfo *i; for( i=info_head; i; i=i->next ) { i->report(); } } void CondorFileTable::close_all() { for( int i=0; i<length; i++ ) { close(i); } } void CondorFileTable::set_aggravate_mode( int on_off ) { aggravate_mode = on_off; } /* This function presumes that init() has been called. A proper class initializer could force working_dir to be NULL (or a valid pointer), but I'm loathe to make random changes this deep in the standard universe code. */ void CondorFileTable::set_working_dir( char * dir ) { ASSERT( dir != NULL ); free( working_dir ); working_dir = strdup( dir ); } void CondorFileTable::dump() { CondorFilePointer *p; dprintf(D_ALWAYS,"\nOPEN FILE TABLE:\n"); for( int j=0; j<length; j++ ) { p = pointers[j]; if( p ) { dprintf(D_ALWAYS,"fd %d\n",j); dprintf(D_ALWAYS,"\tlogical name: %s\n",p->logical_name); dprintf(D_ALWAYS,"\toffset: %ld\n",(long)p->offset); dprintf(D_ALWAYS,"\tdups: %d\n",count_pointer_uses(p)); dprintf(D_ALWAYS,"\topen flags: 0x%x\n",p->flags); if( p->file ) { dprintf(D_ALWAYS,"\turl: %s\n",p->file->get_url()); dprintf(D_ALWAYS,"\tsize: %ld\n",(long)p->file->get_size()); dprintf(D_ALWAYS,"\topens: %d\n",count_file_uses(p->file)); } else { dprintf(D_ALWAYS,"\tnot currently bound to a url.\n"); } } } } /* If this url is already open, return its file descriptor. */ int CondorFileTable::find_url( char *url ) { for( int i=0; i<length; i++ ) if( pointers[i] ) if( pointers[i]->file ) if( !strcmp(pointers[i]->file->get_url(),url) ) return i; return -1; } /* If this logical name is already open, return its file descriptor. */ int CondorFileTable::find_logical_name( const char *logical_name ) { for( int i=0; i<length; i++ ) if( pointers[i] ) if( !strcmp(pointers[i]->logical_name,logical_name) ) return i; return -1; } /* If there already exists an info block for this name, re-use it. Otherwise, make and return a new one. If more than 100 files have been opened, stop making info blocks (i.e. leaking memory,) and dump all of the rest into "everything else". */ CondorFileInfo * CondorFileTable::make_info( const char *logical_name ) { CondorFileInfo *i; for( i=info_head; i; i=i->next ) if( !strcmp(logical_name,i->info_name) ) return i; if( info_count<100 ) { i = new CondorFileInfo( logical_name ); i->next = info_head; info_head = i; } else if( info_count==100 ) { i = new CondorFileInfo( "everything else" ); i->next = info_head; info_head = i; } else { /* fall through */ } info_count++; return info_head; } /* Usually, chose the lowest numbered file descriptor that is available. However, if aggravation is enabled, never choose an fd between 3 and 31. This helps to uncover bugs due to untrapped system calls. */ int CondorFileTable::find_empty() { int fd; for( fd=0; fd<length; fd++ ) { if( aggravate_mode ) { if( fd>2 && fd<32 ) { continue; } } if( !pointers[fd] ) { return fd; } } return -1; } int CondorFileTable::count_pointer_uses( CondorFilePointer *p ) { int count=0; for( int fd=0; fd<length; fd++ ) if(pointers[fd]==p) count++; return count; } int CondorFileTable::count_file_uses( CondorFile *f ) { int count=0; for( int fd=0; fd<length; fd++ ) if(pointers[fd]) if(pointers[fd]->file==f) count++; return count; } /* Convert a logical file name into a physical url by any and all methods available. This function will not fail -- it will always fall back on something reasonable. This is a private function which expects an already compelted path name. */ void CondorFileTable::lookup_url( char *logical_name, char **url ) { static int never_ask_shadow = FALSE; // Special case: Requests to look up default standard files // should be mapped to constant file descriptors. if(!strcmp(logical_name,"default stdin")) { *url = strdup("fd:0"); return; } else if(!strcmp(logical_name,"default stdout")) { *url = strdup("fd:1"); return; } else if(!strcmp(logical_name,"default stderr")) { *url = strdup("fd:2"); return; } // If in local mode, just use local:logical_name. // Otherwise, ask shadow. If that fails, try buffer:remote:logical_name. if( LocalSysCalls() || (never_ask_shadow == TRUE)) { *url = (char *)malloc(strlen(logical_name)+7); sprintf(*url,"local:%s",logical_name); } else { if (never_ask_shadow == FALSE ) { int result; // If <0 is returned, then an error happened. // If 0 is returned then the shadow wanted the FileTable to work // just like normal in comming back to it for each file the // FileTable wants to know what to do with. // if 1 is returned, then the shadow automatically give up // control of how the files are opened, permanently I assume, // since the static variable in here is preserved across // checkpoints in the memory image. result = REMOTE_CONDOR_get_file_info_new( logical_name, *url ); if (result == 1) { never_ask_shadow = TRUE; } else if( result < 0 ) { free( *url ); *url = (char *)malloc(strlen(logical_name)+8); sprintf(*url,"buffer:remote:%s",logical_name); } if(!got_buffer_info) { int temp; REMOTE_CONDOR_get_buffer_info( &buffer_size, &buffer_block_size, &temp ); got_buffer_info = 1; } } } } /* Convert a nested url into a url chain. For example, compress:fetch:remote:/tmp/file becomes CondorFileCompress( CondorFileFetch( CondorFileRemote ) ) */ CondorFile * CondorFileTable::create_url_chain( char const *url ) { char *method = (char *)malloc(strlen(url)+1); char *rest = (char *)malloc(strlen(url)+1); CondorFile * result = create_url_chain( url, method, rest ); free( method ); free( rest ); return result; } CondorFile * CondorFileTable::create_url_chain( char const *url, char *method, char *rest ) { char *next; CondorFile *f; /* linux glibc 2.1 and presumeably 2.0 had a bug where the range didn't work with 8bit numbers */ #if defined(LINUX) && (defined(GLIBC20) || defined(GLIBC21)) int fields = sscanf( url, "%[^:]:%[\x1-\x7F]", method, rest ); #else int fields = sscanf( url, "%[^:]:%[\x1-\xFF]", method, rest ); #endif if( fields!=2 ) return 0; /* Options interpreted by each layer go in () following the : */ /* If we encounter that here, skip it. */ next = rest; if( *next=='(' ) { while(*next) { next++; if(*next==')') { next++; break; } } } /* Now examine the method. */ if( !strcmp( method, "local" ) ) { return new CondorFileLocal; } else if( !strcmp( method, "fd" ) ) { return new CondorFileFD; } else if( !strcmp( method, "special" ) ) { return new CondorFileSpecial; } else if( !strcmp( method, "remote" ) ) { return new CondorFileRemote; } else if( !strcmp( method, "buffer" ) ) { f = create_url_chain( next ); if(f) return new CondorFileBuffer( f, buffer_size, buffer_block_size ); else return 0; } else if( !strcmp( method, "fetch" ) ) { f = create_url_chain( next ); if(f) return new CondorFileAgent( f ); else return 0; } else if( !strcmp( method, "compress" ) ) { f = create_url_chain( next ); if(f) return new CondorFileCompress( f ); else return 0; } else if( !strcmp( method, "append" ) ) { f = create_url_chain( next ); if(f) return new CondorFileAppend( f ); else return 0; } else { _condor_warning(CONDOR_WARNING_KIND_BADURL,"I don't understand url (%s).",url); errno = ENOENT; return 0; } } /* Given a url, create and open a url chain. */ CondorFile * CondorFileTable::open_url( char const *url, int flags, int mode ) { CondorFile *f = create_url_chain( url ); if( !f ) { _condor_warning(CONDOR_WARNING_KIND_BADURL,"I can't parse url type (%s).",url); errno = ENOENT; return 0; } else { if( f->open(url,flags,mode)>=0 ) { return f; } else { delete f; return 0; } } } /* Open a url. If the open fails, fall back on buffered remote system calls. */ CondorFile * CondorFileTable::open_url_retry( char const *url, int flags, int mode ) { CondorFile *f; f = open_url( url, flags, mode ); if(f) return f; if( RemoteSysCalls() ) { const char *path; if( strstr(url,"remote:") ) return 0; path = strrchr(url,':'); if(!path) return 0; path++; if(!*path) return 0; char *new_url = (char *)malloc(strlen(path)+15); sprintf(new_url,"buffer:remote:%s",path); CondorFile *result = open_url( new_url, flags, mode ); free( new_url ); return result; } return 0; } /* Compare the flag of a file already opened and a file about to be opened. Return true if the old flags will not allow the access requested by the new flags. */ static int needs_reopen( int old_flags, int new_flags ) { int mask = (O_RDONLY|O_WRONLY|O_RDWR); if( (old_flags&mask) == (new_flags&mask) ) return 0; if( (old_flags&mask) == O_RDWR ) return 0; return 1; } /* Find any pointers to one file and replace it with another. */ void CondorFileTable::replace_file( CondorFile *old_file, CondorFile *new_file ) { int i; for( i=0;i<length; i++ ) { if(pointers[i] && pointers[i]->file==old_file) { pointers[i]->file=new_file; } } } /* Create and open a file object from a logical name. If either the logical name or url are already in the file table AND the file was previously opened with compatible flags, then share the object. If not, elevate the flags to a common denominator and open a new object suitable for both purposes. */ CondorFile * CondorFileTable::open_file_unique( char *logical_name, int flags, int mode ) { int match = find_logical_name( logical_name ); if( match==-1 || !pointers[match]->file ) { char *url = NULL; lookup_url( (char*)logical_name, &url ); if( url ) { match = find_url( url ); if( match==-1 ) { CondorFile *f = open_url_retry( url, flags, mode ); free( url ); return f; } free( url ); } } CondorFilePointer *p = pointers[match]; CondorFile *old_file; if( needs_reopen( p->flags, flags ) ) { flags &= ~(O_RDONLY); flags &= ~(O_WRONLY); flags |= O_RDWR; p->file->flush(); CondorFile *f = open_url_retry( p->file->get_url(), flags, mode ); if(!f) return 0; old_file = p->file; if( old_file->close()!=0 ) return 0; replace_file( old_file, f ); /* Even though old_file is aliasing p->file here, and then we're deleting old_file, There is no returning a freed pointer error at the end of the function because replace_file() will *always* be able to replace the entry in the pointers[] table (aliased by p) indexed with old_file (being actually p->file) with the updated value of f. */ delete old_file; } return p->file; } /* If short_path is an absolute path, copy it to full path. Otherwise, tack the current directory on to the front of short_path, and copy it to full_path. */ void CondorFileTable::complete_path( const char *short_path, char **full_path ) { if(short_path[0]=='/') { *full_path = strdup(short_path); } else { *full_path = (char *)malloc(strlen(working_dir)+strlen(short_path)+2); strcpy(*full_path,working_dir); strcat(*full_path,"/"); strcat(*full_path,short_path); } } int CondorFileTable::open( const char *logical_name, int flags, int mode ) { char *full_logical_name = NULL; CondorFile *file=0; CondorFileInfo *info=0; // Convert a relative path into a complete path complete_path( logical_name, &full_logical_name ); // Find a fresh file descriptor int fd = find_empty(); if(fd<0) { errno = EMFILE; free( full_logical_name ); return -1; } file = open_file_unique( full_logical_name, flags, mode ); if(!file) { free( full_logical_name ); return -1; } info = make_info( full_logical_name ); info->open_count++; // Flags that should be applied once only are now removed flags &= ~(O_TRUNC); flags &= ~(O_CREAT); // Install the pointer and return! pointers[fd] = new CondorFilePointer(file,info,flags,full_logical_name); free( full_logical_name ); return fd; } int CondorFileTable::install_special( int real_fd, const char *kind ) { int fd = find_empty(); if(fd<0) return -1; CondorFileInfo *i= make_info(kind); i->already_warned = 1; i->open_count++; CondorFileSpecial *s = new CondorFileSpecial(); s->attach( real_fd ); pointers[fd] = new CondorFilePointer( s, i, O_RDWR, kind ); return fd; } /* pipe() works by invoking a local pipe, and then installing a CondorFileSpecial on those two fds. A CondorFileSpecial is just like a local file, but checkpointing is prohibited while it exists. */ int CondorFileTable::pipe(int fds[]) { int real_fds[2]; int scm = SetSyscalls( SYS_LOCAL|SYS_UNMAPPED ); int result = ::pipe(real_fds); SetSyscalls(scm); if(result<0) return -1; fds[0] = install_special(real_fds[0],"pipes"); fds[1] = install_special(real_fds[1],"pipes"); if( fds[0]<0 || fds[1]<0 ) return -1; return 0; } /* Socket is similar to pipe. We will perform a local socket(), and then install a CondorFileSpecial on that fd to access it locally and inhibit checkpointing in the meantime. */ int CondorFileTable::socket( int domain, int type, int protocol ) { int scm = SetSyscalls( SYS_LOCAL|SYS_UNMAPPED ); int real_fd = ::socket(domain,type,protocol); SetSyscalls(scm); if(real_fd<0) return -1; return install_special(real_fd,"network connections"); } /* Close is a little tricky. The file pointer might be in use by several dups, or the file itself might be in use by several opens. So, count all uses of the file. If there is only one, close and delete. Same goes for the file pointer. */ int CondorFileTable::close( int fd ) { if( (fd<0) || (fd>=length) || (pointers[fd]==0) ) { errno = EBADF; return -1; } CondorFilePointer *p = pointers[fd]; //CondorFileInfo *i = p->info; CondorFile *f = p->file; // If this is the last use of the file, flush, close, and delete. // If the close fails (yes, possible!) then return the error // but do not adjust the table. if(f && count_file_uses(f)==1) { /* Commented out this next line to prevent eager updates to the shadow of file statistics on a file close. This is to make WantRemoteIO function better when you say False. At checkpoint boundaries and the end of the job will this information get sent (by other parts of the codebase), so it isn't lost. AFAICT, this commenting out doesn't hurt anything, but I'll leave the line of code in in case we ever want to restore eager reporting and or make it do something better when remote io is turned off for a job inside of Condor. */ /* i->report(); */ int result = f->close(); if( result!=0 ) { return result; } delete f; } // If this is the last use of the pointer, delete it // but leave the info block -- it is in the linked // list beginning with info_head. if(count_pointer_uses(p)==1) { delete p; } // In any case, mark the fd as unused // and return. pointers[fd]=0; return 0; } ssize_t CondorFileTable::read( int fd, void *data, size_t nbyte ) { if( resume(fd)<0 ) return -1; if( !pointers[fd]->file->is_readable() ) { errno = EBADF; return -1; } if (!data) { errno = EINVAL; return -1; } CondorFilePointer *fp = pointers[fd]; CondorFile *f = fp->file; if( nbyte==0 ) return 0; // get the data from the object int actual = f->read( fp->offset, (char*) data, nbyte ); // If there is an error, don't touch the offset. if(actual<0) return -1; // Update the offset fp->offset += actual; // Record that a read was done fp->info->read_count++; fp->info->read_bytes+=actual; // Perhaps send a warning message check_safety(fp); // Return the number of bytes read return actual; } ssize_t CondorFileTable::write( int fd, const void *data, size_t nbyte ) { if( resume(fd)<0 ) return -1; if( !pointers[fd]->file->is_writeable() ) { errno = EBADF; return -1; } if (!data) { errno = EINVAL; return -1; } if( nbyte==0 ) return 0; CondorFilePointer *fp = pointers[fd]; CondorFile *f = fp->file; // Write to the object at the current offset // XXX Don't fix the warning on this line. There is a semantic breakdown // between char* and const void* in the file table API itself, and // between that and the UNIX system API. It will take a pretty serious // rewrite of the function signatures to make everything conform, and // there is a chance there is no such conforming API. int actual = f->write( fp->offset, (const char*)data, nbyte ); // If there is an error, don't touch the offset. if(actual<0) return -1; // Special case: always flush data on stderr if(fd==2) f->flush(); // Update the offset by the amount written fp->offset += actual; // Record that a write was done fp->info->write_count++; fp->info->write_bytes+=actual; // Perhaps send a warning message check_safety(fp); // Return the number of bytes written return actual; } void CondorFileTable::check_safety( CondorFilePointer *fp ) { if( fp->info->read_bytes && fp->info->write_bytes && !fp->info->already_warned ) { fp->info->already_warned = 1; _condor_warning(CONDOR_WARNING_KIND_READWRITE,"File '%s' used for both reading and writing. This is not checkpoint-safe.\n",fp->logical_name); } } off_t CondorFileTable::lseek( int fd, off_t offset, int whence ) { if( resume(fd)<0 ) return -1; if( (fd<0) || (fd>=length) || (pointers[fd]==0) ) { errno = EBADF; return -1; } CondorFilePointer *fp = pointers[fd]; CondorFile *f = fp->file; off_t temp; // This error could conceivably be simply a warning and return with errno=ESPIPE. // Despite this, most programs assume that a seek performed on a regular file // will succeed and do not check the error code. So, this must be a fatal error. if( !f->is_seekable() ) { _condor_error_fatal("Seek operation attempted on non-seekable file %s.",f->get_url()); } // Compute the new offset first. // If the new offset is illegal, don't change it. if( whence == SEEK_SET ) { temp = offset; } else if( whence == SEEK_CUR ) { temp = fp->offset+offset; } else if( whence == SEEK_END ) { temp = f->get_size()+offset; } else { errno = EINVAL; return -1; } if(temp<0) { errno = EINVAL; return -1; } else { fp->offset = temp; fp->info->seek_count++; return temp; } } int CondorFileTable::dup( int fd ) { return search_dup2( fd, 0 ); } int CondorFileTable::search_dup2( int fd, int search ) { if( (fd<0) || (fd>=length) || (pointers[fd]==0) || (search<0) || (search>=length) ) { errno = EBADF; return -1; } int i; for( i=search; i<length; i++ ) if(!pointers[i]) break; if( i==length ) { errno = EMFILE; return -1; } else { return dup2(fd,i); } } int CondorFileTable::dup2( int fd, int nfd ) { int result; if( resume(fd)<0 ) return -1; if( (nfd<0) || (nfd>=length) ) { errno = EBADF; return -1; } if( fd==nfd ) return fd; // If this fd is already in use, close it. // But, close _can_ fail! If that happens, // abort the dup with the errno from the close. if( pointers[nfd]!=0 ) { result = close(nfd); if( result==-1 ) { return result; } } pointers[nfd] = pointers[fd]; return nfd; } /* fchdir is a little sneaky. A particular fd might be remapped to any old file name or access method, which may or may not support changing directories. (furthermore, what does it mean to fchdir to a file that is mapped locally to, say, /tmp/foo?) So, we will just avoid the problem by extracting the name of the file, and calling chdir. */ int CondorFileTable::fchdir( int fd ) { if( resume(fd)<0 ) return -1; dprintf(D_ALWAYS,"CondorFileTable::fchdir(%d) will try chdir(%s)\n", fd, pointers[fd]->logical_name ); return chdir( pointers[fd]->logical_name ); } /* chdir() works by attempting the chdir remotely, and then storing the working directory text. If this is a relative path, we just tack it on to the given path. We have to be careful never to do a getcwd(), because this is not safe on auto-mounted NFS systems. */ int CondorFileTable::chdir( const char *path ) { int result; char *nmem = NULL; if( MyImage.GetMode() != STANDALONE ) { result = REMOTE_CONDOR_chdir( path ); } else { result = syscall( SYS_chdir, path ); } if( result==-1 ) return result; if( path[0]=='/' ) { /* since path might in fact be identical to working_dir, let's be careful and copy before freeing. */ nmem = strdup( path ); free( working_dir ); working_dir = nmem; } else { nmem = (char *)realloc(working_dir,strlen(path)+strlen(working_dir)+2); if (nmem == NULL) { /* I wonder what happens if the actual chidir succeeded and I fail to get memory here and return. If the user program ignores the errno, I'm sure problems will arise since working_dir is now unsynchronized with the actual chdir. */ errno = ENOMEM; return -1; } /* if working_dir's pointer stayed the same, this is a nop, if it changed, then realloc() already freed() the memory and returned the new pointer, which I update here. */ working_dir = nmem; strcat( working_dir, "/" ); strcat( working_dir, path ); } return result; } /* ioctls don't affect the open file table, so we will pass them along to the individual access method, which will decide if it can be supported. */ int CondorFileTable::ioctl( int fd, int cmd, long arg ) { if( resume(fd)<0 ) return -1; return pointers[fd]->file->ioctl(cmd,arg); } int CondorFileTable::ftruncate( int fd, size_t size ) { if( resume(fd)<0 ) return -1; return pointers[fd]->file->ftruncate(size); } /* fcntl does all sorts of wild stuff. Some operations affect the fd table. Perform those here. Others merely modify an individual file. Pass these along to the access method, which may support the operation, or fail with its own error. */ int CondorFileTable::fcntl( int fd, int cmd, int arg ) { if( resume(fd)<0 ) return -1; switch(cmd) { #ifdef F_DUPFD case F_DUPFD: return search_dup2(fd,arg); break; #endif #ifdef F_DUP2FD case F_DUP2FD: return dup2(fd,arg); break; #endif /* A length of zero to FREESP indicates the file should be truncated at the start value. Truncation must be handled at this level, and not at an individual object, because the entire chain of objects, e.g. CFBuffer->CFCompress->CFRemote, must all be informed about a truncate in turn. */ #ifdef F_FREESP case F_FREESP: { struct flock *f = (struct flock *)arg; if( (f->l_whence==0) && (f->l_len==0) ) { return FileTab->ftruncate(fd,f->l_start); } return pointers[fd]->file->fcntl(cmd,arg); } break; #endif #ifdef F_FREESP64 case F_FREESP64: { struct flock64 *f64 = (struct flock64 *)arg; if( (f64->l_whence==0) && (f64->l_len==0) ) { return FileTab->ftruncate(fd,f64->l_start); } return pointers[fd]->file->fcntl(cmd,arg); } break; #endif default: return pointers[fd]->file->fcntl(cmd,arg); break; } } int CondorFileTable::fsync( int fd ) { if( resume(fd)<0 ) return -1; return pointers[fd]->file->fsync(); } int CondorFileTable::fstat( int fd, struct stat *buf) { if( resume(fd)<0 ) return -1; return pointers[fd]->file->fstat(buf); } int CondorFileTable::stat( const char *name, struct stat *buf) { int fd; int scm, oscm; int ret; int do_local; /* See if the file is open, if so, then just do an fstat. If it isn't open then call the normal stat in unmapped mode with whatever the shadow said the location of the file was. */ fd = find_logical_name( name ); if (fd == -1) { oscm = scm = GetSyscallMode(); /* determine where the shadow says to deal with this file. */ char *newname = NULL; do_local = _condor_is_file_name_local( name, &newname ); if (LocalSysCalls() || do_local) { scm |= SYS_LOCAL; /* turn on SYS_LOCAL */ scm &= ~(SYS_REMOTE); /* turn off SYS_REMOTE */ } else { scm |= SYS_REMOTE; /* Turn on SYS_REMOTE */ scm &= ~(SYS_LOCAL); /* Turn off SYS_LOCAL */ } /* either way, it needs to be unmapped so we don't recurse into here */ scm |= SYS_UNMAPPED; /* turn on SYS_UNMAPPED */ scm &= ~(SYS_MAPPED); /* turn off SYS_MAPPED */ /* invoke it with where the shadow said the file was */ SetSyscalls(scm); ret = ::stat(newname, buf); SetSyscalls(oscm); /* set it back to what it was */ free( newname ); return ret; } return fstat(fd, buf); } int CondorFileTable::lstat( const char *name, struct stat *buf) { int fd; int scm, oscm; int ret; int do_local; /* See if the file is open, if so, then just do an fstat. If it isn't open then call the normal lstat in unmapped mode with whatever the shadow said the location of the file was. */ fd = find_logical_name( name ); if (fd == -1) { oscm = scm = GetSyscallMode(); /* determine where the shadow says to deal with this file. */ char *newname = NULL; do_local = _condor_is_file_name_local( name, &newname ); if (LocalSysCalls() || do_local) { scm |= SYS_LOCAL; /* turn on SYS_LOCAL */ scm &= ~(SYS_REMOTE); /* turn off SYS_REMOTE */ } else { scm |= SYS_REMOTE; /* Turn on SYS_REMOTE */ scm &= ~(SYS_LOCAL); /* Turn off SYS_LOCAL */ } /* either way, it needs to be unmapped so we don't recurse into here */ scm |= SYS_UNMAPPED; /* turn on SYS_UNMAPPED */ scm &= ~(SYS_MAPPED); /* turn off SYS_MAPPED */ SetSyscalls(scm); ret = ::lstat(newname, buf); SetSyscalls(oscm); /* set it back to what it was */ free( newname ); return ret; } return fstat(fd, buf); } /* poll converts each fd into its mapped equivalent and then does a local poll. A poll() on a non local file causes a warning and failure with EINVAL */ int CondorFileTable::poll( struct pollfd *fds, int nfds, int timeout ) { struct pollfd *realfds; realfds = (struct pollfd *) malloc( sizeof(struct pollfd)*nfds ); if(!realfds) { errno = ENOMEM; return -1; } for( int i=0; i<nfds; i++ ) { if(_condor_is_fd_local(fds[i].fd)) { realfds[i].fd = _condor_get_unmapped_fd(fds[i].fd); realfds[i].events = fds[i].events; } else { _condor_warning(CONDOR_WARNING_KIND_UNSUP,"poll() is not supported for remote files"); free(realfds); errno = EINVAL; return -1; } } int scm = SetSyscalls( SYS_LOCAL|SYS_UNMAPPED ); int result = ::poll( realfds, nfds, timeout ); SetSyscalls(scm); for( int i=0; i<nfds; i++ ) { fds[i].revents = realfds[i].revents; } free(realfds); return result; } /* select transforms its arguments into local fds and then does a local select. A select on a non-local fd causes a return with EINVAL and a warning message. */ int CondorFileTable::select( int n, fd_set *r, fd_set *w, fd_set *e, struct timeval *timeout ) { fd_set r_real, w_real, e_real; int n_real, fd, fd_real; int result, scm; FD_ZERO( &r_real ); FD_ZERO( &w_real ); FD_ZERO( &e_real ); n_real = 0; /* For each fd, put its mapped equivalent in the appropriate set */ for( fd=0; fd<n; fd++ ) { fd_real = _condor_get_unmapped_fd(fd); if( fd_real>=0 ) { if( _condor_is_fd_local(fd) ) { if( r && FD_ISSET(fd,r) ) FD_SET(fd_real,&r_real); if( w && FD_ISSET(fd,w) ) FD_SET(fd_real,&w_real); if( e && FD_ISSET(fd,e) ) FD_SET(fd_real,&e_real); n_real = MAX( n_real, fd_real+1 ); } else { if( (r && FD_ISSET(fd,r)) || (w && FD_ISSET(fd,w)) || (e && FD_ISSET(fd,e)) ) { _condor_warning(CONDOR_WARNING_KIND_UNSUP,"select() is not supported for remote files."); errno = EINVAL; return -1; } } } } /* Do a local select */ scm = SetSyscalls( SYS_LOCAL|SYS_UNMAPPED ); result = ::select( n_real, &r_real, &w_real, &e_real, timeout ); SetSyscalls(scm); if( r ) FD_ZERO( r ); if( w ) FD_ZERO( w ); if( e ) FD_ZERO( e ); /* Set the bit for each fd whose real equivalent is set. */ for( fd=0; fd<n; fd++ ) { fd_real = _condor_get_unmapped_fd(fd); if( fd_real>=0 && _condor_is_fd_local(fd) ) { if( r && FD_ISSET(fd_real,&r_real) ) FD_SET(fd,r); if( w && FD_ISSET(fd_real,&w_real) ) FD_SET(fd,w); if( e && FD_ISSET(fd_real,&e_real) ) FD_SET(fd,e); } } return result; } /* Checkpoint the state of the file table. This involves reporting the disposition of all files, and flushing and closing them. The closed files will be re-bound and re-opened lazily after a resume. Notice that these need to be closed even for a periodic checkpoint, because logical names must be re-bound to physical urls. If a close fails at this point, we must roll-back, otherwise the data on disk would not be consistent with the checkpoint image. */ void CondorFileTable::checkpoint() { int temp; dprintf(D_ALWAYS,"CondorFileTable::checkpoint\n"); dump(); if( MyImage.GetMode() != STANDALONE ) { REMOTE_CONDOR_get_buffer_info( &buffer_size, &buffer_block_size, &temp ); } dprintf(D_ALWAYS,"working dir = %s\n",working_dir); for( int i=0; i<length; i++ ) { if( pointers[i] ) { if( pointers[i]->file ) { if( count_file_uses(pointers[i]->file)==1 ) { temp = pointers[i]->file->close(); if( temp==-1 ) { _condor_error_retry("Unable to commit data to file %s!\n",pointers[i]->file->get_url()); } delete pointers[i]->file; } pointers[i]->file=0; } } } report_all(); } /* Resume the state of the file table after a checkpoint. There isn't much to do here except move back to the current working directory. All the files should be resumed lazily. */ void CondorFileTable::resume() { int result; int temp; dprintf(D_ALWAYS,"CondorFileTable::resume\n"); dprintf(D_ALWAYS,"working dir = %s\n",working_dir); if(MyImage.GetMode()!=STANDALONE) { REMOTE_CONDOR_get_buffer_info( &buffer_size, &buffer_block_size, &temp ); result = REMOTE_CONDOR_chdir(working_dir); } else { result = ::chdir( working_dir ); } if(result<0) _condor_error_retry("Couldn't move to '%s' (%s). Please fix it.\n",working_dir,strerror(errno)); dump(); } /* Examine a particular fd. If there is a valid file object on this fd, return 0. If this is not a valid fd, return -1 and set errno. If this is a valid fd, but no valid file object, attempt a lazy resume of the file. If that fails, die with _condor_error_retry. */ int CondorFileTable::resume( int fd ) { CondorFilePointer *p; if( fd<0 || fd>=length || !pointers[fd] ) { errno = EBADF; return -1; } p = pointers[fd]; if( !p->file ) { p->file = open_file_unique( p->logical_name, p->flags, 0 ); if( !p->file ) { _condor_error_retry("Couldn't re-open '%s' after a restart. Please fix it.\n",p->logical_name); } } return 0; } int CondorFileTable::get_unmapped_fd( int fd ) { if( resume(fd)<0 ) return -1; return pointers[fd]->file->get_unmapped_fd(); } int CondorFileTable::is_fd_local( int fd ) { if( resume(fd)<0 ) return -1; return pointers[fd]->file->is_file_local(); } int CondorFileTable::is_file_name_local( const char *incomplete_name, char **local_name ) { char *url = NULL; char *logical_name = NULL; assert( local_name != NULL && *local_name == NULL ); // Convert the incomplete name into a complete path complete_path( incomplete_name, &logical_name ); // Now look to see if the file is already open. // If it is, ask the file if it is local. int match = find_logical_name( logical_name ); if(match!=-1) { CondorFile *file; resume(match); file = pointers[match]->file; *local_name = strdup(strrchr(file->get_url(),':')+1); free( logical_name ); return file->is_file_local(); } // Otherwise, resolve the url by normal methods. lookup_url( logical_name, &url ); free( logical_name ); // Copy the local path name out *local_name = strdup(strrchr(url,':')+1); // Create a URL chain and ask it if it is local. CondorFile *f = create_url_chain(url); free( url ); if(f) { if( f->is_file_local() ) { delete f; return 1; } else { delete f; return 0; } } return 0; }
// // StatusLayer.cpp // FlappyBird // // Created by 夏旸 on 16/7/19. // // #include "StatusLayer.h" #include "NumberSeries.h" #include "SimpleAudioEngine.h" using namespace CocosDenshion; StatusLayer::StatusLayer(){}; StatusLayer::~StatusLayer(){}; bool StatusLayer::init(){ if (!Layer::init()){ return false; } // init numbers this->bestScore = 0; this->currentScore = 0; this->isNewRecord = false; Number::getInstance()->loadNumber(NUMBER_FONT.c_str(), "font_0%02d", 48); Number::getInstance()->loadNumber(NUMBER_SCORE.c_str(), "number_score_%02d"); this->visibleSize = Director::getInstance()->getVisibleSize(); this->originPoint = Director::getInstance()->getVisibleOrigin(); this->showReadyStatus(); this->loadWhiteSprite(); return true; } void StatusLayer::showReadyStatus() { scoreSprite = (Sprite *)Number::getInstance()->convert(NUMBER_FONT.c_str(), 0); scoreSprite->setPosition(Point(this->originPoint.x + this->visibleSize.width / 2, this->originPoint.y + this->visibleSize.height * 5 / 6)); this->addChild(scoreSprite); getreadySprite = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("text_ready")); getreadySprite->setPosition(Point(this->originPoint.x + this->visibleSize.width / 2, this->originPoint.y + this->visibleSize.height * 2 / 3)); this->addChild(getreadySprite); tutorialSprite = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("tutorial")); tutorialSprite->setPosition(Point(this->originPoint.x + this->visibleSize.width / 2, this->originPoint.y + this->visibleSize.height * 1 / 2)); this->addChild(tutorialSprite); } void StatusLayer::showStartStatus() { this->getreadySprite->runAction(FadeOut::create(0.4f)); this->tutorialSprite->runAction(FadeOut::create(0.4f)); } void StatusLayer::showOverStatus(int curScore, int bestScore) { this->currentScore = curScore; this->bestScore = bestScore; if (curScore > bestScore){ this->bestScore = curScore; this->isNewRecord = true; } else{ this->isNewRecord = false; } this->removeChild(scoreSprite); this->blinkFullScreen(); } void StatusLayer::onGameStart(){ this->showStartStatus(); } void StatusLayer::onGamePlaying(int score){ this->removeChild(scoreSprite); this->scoreSprite = (Sprite*)Number::getInstance()->convert(NUMBER_FONT.c_str(), score); scoreSprite->setPosition(Point(this->originPoint.x + this->visibleSize.width / 2, this->originPoint.y + this->visibleSize.height * 5 / 6)); this->addChild(scoreSprite); } void StatusLayer::onGameEnd(int curScore, int bestScore){ this->showOverStatus(curScore, bestScore); } void StatusLayer::loadWhiteSprite(){ //this white sprite is used for blinking the screen for a short while whiteSprite = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("white")); whiteSprite->setScale(100); whiteSprite->setOpacity(0); this->addChild(whiteSprite, 10000); } void StatusLayer::blinkFullScreen(){ //display a flash blink auto fadeOut = FadeOut::create(0.1f); auto fadeIn = FadeIn::create(0.1f); auto blinkAction = Sequence::create(fadeIn, fadeOut, NULL); CallFunc *actionDone = CallFunc::create(CC_CALLBACK_0(StatusLayer::fadeInGameOver, this)); auto sequence = Sequence::createWithTwoActions(blinkAction, actionDone); whiteSprite->stopAllActions(); whiteSprite->runAction(sequence); } void StatusLayer::fadeInGameOver(){ // create the game over panel Sprite* gameoverSprite = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("text_game_over")); gameoverSprite->setPosition(Point(this->originPoint.x + this->visibleSize.width / 2, this->originPoint.y + this->visibleSize.height * 2 / 3)); this->addChild(gameoverSprite); auto gameoverFadeIn = FadeIn::create(0.5f); // Start next action CallFunc *actionDone = CallFunc::create(CC_CALLBACK_0(StatusLayer::jumpToScorePanel, this)); auto sequence = Sequence::createWithTwoActions(gameoverFadeIn, actionDone); gameoverSprite->stopAllActions(); gameoverSprite->runAction(sequence); } void StatusLayer::jumpToScorePanel(){ // create the score panel Sprite* scorepanelSprite = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("score_panel")); scorepanelSprite->setPosition(Point(this->originPoint.x + this->visibleSize.width / 2, this->originPoint.y - scorepanelSprite->getContentSize().height)); this->addChild(scorepanelSprite); //display the best score on the score panel auto bestScoreSprite = (Sprite *)Number::getInstance()->convert(NUMBER_SCORE.c_str(), this->bestScore, Gravity::GRAVITY_RIGHT); bestScoreSprite->setAnchorPoint(Point(1, 1)); bestScoreSprite->setPosition(scorepanelSprite->getContentSize().width - 28, 50); scorepanelSprite->addChild(bestScoreSprite); string medalsName = this->getMedalsName(currentScore); if (medalsName != "") { Sprite* medalsSprite = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName(medalsName)); medalsSprite->addChild(this->blink); medalsSprite->setPosition(54, 58); scorepanelSprite->addChild(medalsSprite); } //if the current score is higher than the best score. //the panel will appear a "new" tag. if (this->isNewRecord){ Sprite* newTagSprite = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("new")); newTagSprite->setPosition(-16, 12); bestScoreSprite->addChild(newTagSprite); } // Start next action auto scorePanelMoveTo = MoveTo::create(0.8f, Point(this->originPoint.x + this->visibleSize.width / 2, this->originPoint.y + this->visibleSize.height / 2 - 10.0f)); // add variable motion for the action EaseExponentialOut* sineIn = EaseExponentialOut::create(scorePanelMoveTo); CallFunc *actionDone = CallFunc::create(bind(&StatusLayer::fadeInRestartBtn, this)); auto sequence = Sequence::createWithTwoActions(sineIn, actionDone); scorepanelSprite->stopAllActions(); SimpleAudioEngine::getInstance()->playEffect("sfx_swooshing.ogg"); scorepanelSprite->runAction(sequence); } void StatusLayer::fadeInRestartBtn(){ Node * tmpNode = Node::create(); //create the restart menu; Sprite* restartBtn = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("button_play")); Sprite* restartBtnActive = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("button_play")); restartBtnActive->setPositionY(-4); auto menuItem = MenuItemSprite::create(restartBtn, restartBtnActive, NULL, CC_CALLBACK_1(StatusLayer::menuRestartCallback, this)); auto menu = Menu::create(menuItem, NULL); menu->setPosition(Point(this->originPoint.x + this->visibleSize.width / 2 - restartBtn->getContentSize().width / 2, this->originPoint.y + this->visibleSize.height * 2 / 7 - 10.0f)); tmpNode->addChild(menu); //create the rate button. however ,this button is not available yet = = Sprite* rateBtn = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("button_score")); rateBtn->setPosition(Point(this->originPoint.x + this->visibleSize.width / 2 + rateBtn->getContentSize().width / 2, this->originPoint.y + this->visibleSize.height * 2 / 7 - 10.0f)); tmpNode->addChild(rateBtn); this->addChild(tmpNode); //fade in the two buttons auto fadeIn = FadeIn::create(0.1f); //tmpNode->stopAllActions(); //tmpNode->runAction(fadeIn); CallFunc *actionDone = CallFunc::create(bind(&StatusLayer::refreshScoreCallback, this)); auto sequence = Sequence::createWithTwoActions(fadeIn, actionDone); tmpNode->stopAllActions(); tmpNode->runAction(sequence); } void StatusLayer::refreshScoreCallback(){ this->tmpScore = 0; schedule(schedule_selector(StatusLayer::refreshScoreExecutor), 0.1f); } void StatusLayer::refreshScoreExecutor(float dt){ if (this->getChildByTag(CURRENT_SCORE_SPRITE_TAG)){ this->removeChildByTag(CURRENT_SCORE_SPRITE_TAG); } scoreSprite = (Sprite *)Number::getInstance()->convert(NUMBER_SCORE.c_str(), this->tmpScore, Gravity::GRAVITY_RIGHT); scoreSprite->setAnchorPoint(Point(1, 0)); scoreSprite->setPosition(Point(this->originPoint.x + this->visibleSize.width * 3 / 4 + 20.0f, this->originPoint.y + this->visibleSize.height * 1 / 2)); scoreSprite->setTag(CURRENT_SCORE_SPRITE_TAG); this->addChild(scoreSprite, 1000); this->tmpScore++; if (this->tmpScore > this->currentScore){ unschedule(schedule_selector(StatusLayer::refreshScoreExecutor)); } } void StatusLayer::setBlinkSprite() { this->blink = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("blink_00")); Animation *animation = Animation::create(); animation->setDelayPerUnit(0.1f); for (int i = 0; i < 3; i++){ const char *filename = String::createWithFormat("blink_%02d", i)->getCString(); SpriteFrame *frame = AtlasLoader::getInstance()->getSpriteFrameByName(filename); animation->addSpriteFrame(frame); } for (int i = 2; i >= 0; i--){ const char *filename = String::createWithFormat("blink_%02d", i)->getCString(); SpriteFrame *frame = AtlasLoader::getInstance()->getSpriteFrameByName(filename); animation->addSpriteFrame(frame); } auto animate = Animate::create(animation); auto actionDone = CallFunc::create(bind(&StatusLayer::blinkAction, this)); auto sequence = Sequence::createWithTwoActions(animate, actionDone); blink->runAction(RepeatForever::create(sequence)); } void StatusLayer::blinkAction() { if (this->blink && this->blink->getParent()) { Size activeSize = this->blink->getParent()->getContentSize(); this->blink->setPosition(rand() % ((int)(activeSize.width)), rand() % ((int)(activeSize.height))); } } string StatusLayer::getMedalsName(int score){ this->setBlinkSprite(); //display the golden silver or bronze iron string medalsName = ""; if (this->currentScore >= 10 && this->currentScore < 20){//iron medals medalsName = "medals_0"; } else if (this->currentScore >= 20 && currentScore < 30){//bronze medals medalsName = "medals_1"; } else if (currentScore >= 30 && currentScore < 50){//silver medals medalsName = "medals_2"; } else if (currentScore >= 50){//golden medals medalsName = "medals_3"; } return medalsName; } void StatusLayer::menuRestartCallback(Ref* pSender){ SimpleAudioEngine::getInstance()->playEffect("sfx_swooshing.ogg"); auto scene = GameScene::createScene(); TransitionScene *transition = TransitionFade::create(1, scene); Director::getInstance()->replaceScene(transition); }
#pragma once #include "agl/glsl/vec/vec.hpp" namespace agl { template<typename T> constexpr T max(T t0, T t1) { return (t0 > t1) ? t0 : t1; } template<typename T, std::size_t N> constexpr Vec<T, N> max(const Vec<T, N>& v0, const Vec<T, N>& v1) { auto m = Vec<T, N>(); for(std::size_t i = 0; i < size(m); ++i) { m[i] = max(v0[i], v1[i]); } return m; } }
#include "modulate.h" namespace weserv { namespace api { namespace processors { VImage Modulate::process(const VImage &image) const { auto brightness = query_->get_if<float>( /*"bri"*/"mod", [](float b) { // Brightness needs to be in range of 0 - 10000 return b >= 0 && b <= 10000; }, 1.0F); auto saturation = query_->get_if<float>( "sat", [](float s) { // Saturation needs to be in range of 0 - 10000 return s >= 0 && s <= 10000; }, 1.0F); auto hue = query_->get<int>("hue", 0); // Normalized to [0, 360] below // Should we process the image? if (brightness == 1.0 && saturation == 1.0 && hue == 0) { return image; } // Normalize hue rotation to [0, 360] hue %= 360; if (hue < 0) { hue = 360 + hue; } // Get original colorspace VipsInterpretation type_before_modulate = image.interpretation(); // Modulate brightness, saturation and hue if (image.has_alpha()) { // Separate alpha channel auto image_without_alpha = image.extract_band( 0, VImage::option()->set("n", image.bands() - 1)); auto alpha = image[image.bands() - 1]; return image_without_alpha.colourspace(VIPS_INTERPRETATION_LCH) .linear({brightness, saturation, 1}, {0.0, 0.0, static_cast<double>(hue)}) .colourspace(type_before_modulate) .bandjoin(alpha); } else { return image.colourspace(VIPS_INTERPRETATION_LCH) .linear({brightness, saturation, 1}, {0.0, 0.0, static_cast<double>(hue)}) .colourspace(type_before_modulate); } } } // namespace processors } // namespace api } // namespace weserv
#include <SFML/Graphics.hpp> int main() { const unsigned int HOR = 192; const unsigned int VERT = 108; const unsigned int PIXELS_PER_UNIT = 10; sf::RenderWindow* window = new sf::RenderWindow( sf::VideoMode(HOR * PIXELS_PER_UNIT, VERT * PIXELS_PER_UNIT), "Conway's Game of Life - https://github.com/manoyes"); // template object for drawing a cell sf::RectangleShape* shape = new sf::RectangleShape(sf::Vector2f(10, 10)); bool(*grid)[VERT] = new bool[HOR][VERT]; bool(*nextGrid)[VERT] = new bool[HOR][VERT]; // Seed our random number generator srand(static_cast<unsigned int>(time(nullptr))); // Initialize the grid for (int i = 0; i < HOR; i++) { for (int j = 0; j < VERT; j++) { grid[i][j] = (bool)(rand() % 2); } } window->setFramerateLimit(30); //Main loop while (window->isOpen()) { sf::Event event; while (window->pollEvent(event)) { if (event.type == sf::Event::Closed) { window->close(); } } // Draw the grid window->clear(); for (int i = 0; i < HOR; i++) { for (int j = 0; j < VERT; j++) { shape->setFillColor((grid[i][j] ? sf::Color::White : sf::Color::Black)); shape->setPosition((float)i * PIXELS_PER_UNIT, (float)j * PIXELS_PER_UNIT); window->draw(*shape); } } window->display(); // Tally the neighbors for (int i = 1; i < HOR - 1; i++) { for (int j = 1; j < VERT - 1; j++) { int neighborCounts = 0; for (int x = -1; x <= 1; x++) { for (int y = -1; y <= 1; y++) { neighborCounts += grid[i + x][j + y]; } } neighborCounts -= grid[i][j]; // If cell is alive and has fewer than two or greater than 3 //neighbors, OR cell is dead and has exactly 3 neighbors, //invert the state. Otherwise, the state continues. if ((grid[i][j] && (neighborCounts < 2 || neighborCounts > 3)) || (!grid[i][j] && neighborCounts == 3)) { nextGrid[i][j] = !grid[i][j]; } else { nextGrid[i][j] = grid[i][j]; } } } // Update the grid for (int i = 0; i < HOR; i++) { for (int j = 0; j < VERT; j++) { grid[i][j] = nextGrid[i][j]; } } } return 0; }
/*============================================================================== Copyright (c) Kapteyn Astronomical Institute University of Groningen, Groningen, Netherlands. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Davide Punzo, Kapteyn Astronomical Institute, and was supported through the European Research Council grant nr. 291531. ==============================================================================*/ // STD includes #include <string> #include <cstdlib> #include <math.h> // VTK includes #include <vtkImageData.h> #include <vtkNew.h> #include <vtkObjectFactory.h> #include <vtkPointData.h> // AstroVolume includes #include <vtkSlicerAstroConfigure.h> // MRML includes #include <vtkMRMLAnnotationROINode.h> #include <vtkMRMLAstroLabelMapVolumeNode.h> #include <vtkMRMLAstroVolumeDisplayNode.h> #include <vtkMRMLAstroVolumeNode.h> #include <vtkMRMLAstroVolumeStorageNode.h> #include <vtkMRMLVolumeNode.h> #include <vtkMRMLTransformNode.h> #include <vtkMRMLVolumePropertyNode.h> #include <vtkMRMLVolumeRenderingDisplayNode.h> // OpenMP includes #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #include <omp.h> #endif //------------------------------------------------------------------------------ const char* vtkMRMLAstroVolumeNode::PRESET_REFERENCE_ROLE = "preset"; const char* vtkMRMLAstroVolumeNode::VOLUMEPROPERTY_REFERENCE_ROLE = "volumeProperty"; const char* vtkMRMLAstroVolumeNode::ROI_REFERENCE_ROLE = "ROI"; const char* vtkMRMLAstroVolumeNode::ROI_ALIGNMENTTRANSFORM_REFERENCE_ROLE = "roiAlignmentTransform"; //---------------------------------------------------------------------------- vtkMRMLNodeNewMacro(vtkMRMLAstroVolumeNode); //---------------------------------------------------------------------------- vtkMRMLAstroVolumeNode::vtkMRMLAstroVolumeNode() { } //---------------------------------------------------------------------------- vtkMRMLAstroVolumeNode::~vtkMRMLAstroVolumeNode() { } //---------------------------------------------------------------------------- const char *vtkMRMLAstroVolumeNode::GetPresetNodeReferenceRole() { return vtkMRMLAstroVolumeNode::PRESET_REFERENCE_ROLE; } //---------------------------------------------------------------------------- const char *vtkMRMLAstroVolumeNode::GetVolumePropertyNodeReferenceRole() { return vtkMRMLAstroVolumeNode::VOLUMEPROPERTY_REFERENCE_ROLE; } //---------------------------------------------------------------------------- const char *vtkMRMLAstroVolumeNode::GetROINodeReferenceRole() { return vtkMRMLAstroVolumeNode::ROI_REFERENCE_ROLE; } //---------------------------------------------------------------------------- const char *vtkMRMLAstroVolumeNode::GetROIAlignmentTransformNodeReferenceRole() { return vtkMRMLAstroVolumeNode::ROI_ALIGNMENTTRANSFORM_REFERENCE_ROLE; } namespace { //---------------------------------------------------------------------------- template <typename T> std::string NumberToString(T V) { std::string stringValue; std::stringstream strstream; strstream << V; strstream >> stringValue; return stringValue; } //---------------------------------------------------------------------------- std::string DoubleToString(double Value) { return NumberToString<double>(Value); } //---------------------------------------------------------------------------- template <typename T> T StringToNumber(const char* num) { std::stringstream ss; ss << num; T result; return ss >> result ? result : 0; } //---------------------------------------------------------------------------- int StringToInt(const char* str) { return StringToNumber<int>(str); } //---------------------------------------------------------------------------- double StringToDouble(const char* str) { return StringToNumber<double>(str); } //---------------------------------------------------------------------------- template <typename T> bool isNaN(T value) { return value != value; } //---------------------------------------------------------------------------- bool DoubleIsNaN(double Value) { return isNaN<double>(Value); } //---------------------------------------------------------------------------- bool FloatIsNaN(float Value) { return isNaN<float>(Value); } //---------------------------------------------------------------------------- bool ShortIsNaN(short Value) { return isNaN<short>(Value); } }// end namespace //---------------------------------------------------------------------------- void vtkMRMLAstroVolumeNode::ReadXMLAttributes(const char** atts) { this->Superclass::ReadXMLAttributes(atts); } //---------------------------------------------------------------------------- void vtkMRMLAstroVolumeNode::WriteXML(ostream& of, int nIndent) { this->Superclass::WriteXML(of, nIndent); } //---------------------------------------------------------------------------- void vtkMRMLAstroVolumeNode::Copy(vtkMRMLNode *anode) { vtkMRMLAstroVolumeNode *astroVolumeNode = vtkMRMLAstroVolumeNode::SafeDownCast(anode); if (!astroVolumeNode) { return; } this->Superclass::Copy(astroVolumeNode); } //---------------------------------------------------------------------------- void vtkMRMLAstroVolumeNode::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //--------------------------------------------------------------------------- vtkMRMLAstroVolumeDisplayNode* vtkMRMLAstroVolumeNode::GetAstroVolumeDisplayNode() { return vtkMRMLAstroVolumeDisplayNode::SafeDownCast(this->GetDisplayNode()); } //--------------------------------------------------------------------------- vtkMRMLVolumeRenderingDisplayNode *vtkMRMLAstroVolumeNode::GetAstroVolumeRenderingDisplayNode() { return vtkMRMLVolumeRenderingDisplayNode::SafeDownCast(this->GetNthDisplayNode(this->GetNumberOfDisplayNodes() - 1)); } //--------------------------------------------------------------------------- bool vtkMRMLAstroVolumeNode::UpdateRangeAttributes() { if (!this->GetImageData()) { return false; } this->GetImageData()->Modified(); int *dims = this->GetImageData()->GetDimensions(); int numElements = dims[0] * dims[1] * dims[2]; const int DataType = this->GetImageData()->GetPointData()->GetScalars()->GetDataType(); double max_val = this->GetImageData()->GetScalarTypeMin(), min_val = this->GetImageData()->GetScalarTypeMax(); short *inSPixel = nullptr; float *inFPixel = nullptr; double *inDPixel = nullptr; #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP omp_set_num_threads(omp_get_num_procs()); #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP switch (DataType) { case VTK_SHORT: inSPixel = static_cast<short*> (this->GetImageData()->GetScalarPointer()); #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(max : max_val), reduction(min : min_val) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elementCnt = 0; elementCnt < numElements; elementCnt++) { if (ShortIsNaN(*(inSPixel + elementCnt))) { continue; } if (*(inSPixel + elementCnt) > max_val) { max_val = *(inSPixel + elementCnt); } if (*(inSPixel + elementCnt) < min_val) { min_val = *(inSPixel + elementCnt); } } break; case VTK_FLOAT: inFPixel = static_cast<float*> (this->GetImageData()->GetScalarPointer()); #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(max : max_val), reduction(min : min_val) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elementCnt = 0; elementCnt < numElements; elementCnt++) { if (FloatIsNaN(*(inFPixel + elementCnt))) { continue; } if (*(inFPixel + elementCnt) > max_val) { max_val = *(inFPixel + elementCnt); } if (*(inFPixel + elementCnt) < min_val) { min_val = *(inFPixel + elementCnt); } } break; case VTK_DOUBLE: inDPixel = static_cast<double*> (this->GetImageData()->GetScalarPointer()); #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(max : max_val), reduction(min : min_val) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elementCnt = 0; elementCnt < numElements; elementCnt++) { if (DoubleIsNaN(*(inDPixel + elementCnt))) { continue; } if (*(inDPixel + elementCnt) > max_val) { max_val = *(inDPixel + elementCnt); } if (*(inDPixel + elementCnt) < min_val) { min_val = *(inDPixel + elementCnt); } } break; default: vtkErrorMacro("vtkSlicerAstroVolumeLogic::UpdateRangeAttributes : " "attempt to allocate scalars of type not allowed"); return false; } int wasModifying = this->StartModify(); this->SetAttribute("SlicerAstro.DATAMAX", DoubleToString(max_val).c_str()); this->SetAttribute("SlicerAstro.DATAMIN", DoubleToString(min_val).c_str()); vtkMRMLAstroVolumeDisplayNode* displayNode = this->GetAstroVolumeDisplayNode(); if (displayNode) { double window = max_val - min_val; double level = 0.5 * (max_val + min_val); int disModify = displayNode->StartModify(); displayNode->SetWindowLevel(window, level); displayNode->SetThreshold(min_val, max_val); displayNode->EndModify(disModify); } this->EndModify(wasModifying); inSPixel = nullptr; inFPixel = nullptr; inDPixel = nullptr; delete inSPixel; delete inFPixel; delete inDPixel; return true; } //--------------------------------------------------------------------------- bool vtkMRMLAstroVolumeNode::UpdateDisplayThresholdAttributes() { if (!this->GetImageData()) { return false; } // Calculate the noise as the std of 6 slices of the datacube. // The DisplayThreshold = noise // 3D color function starts from 3 times the value of DisplayThreshold. int *dims = this->GetImageData()->GetDimensions(); const int DataType = this->GetImageData()->GetPointData()->GetScalars()->GetDataType(); short *outSPixel = nullptr; float *outFPixel = nullptr; double *outDPixel = nullptr; switch (DataType) { case VTK_SHORT: outSPixel = static_cast<short*> (this->GetImageData()->GetScalarPointer(0,0,0)); break; case VTK_FLOAT: outFPixel = static_cast<float*> (this->GetImageData()->GetScalarPointer(0,0,0)); break; case VTK_DOUBLE: outDPixel = static_cast<double*> (this->GetImageData()->GetScalarPointer(0,0,0)); break; default: vtkErrorMacro("vtkMRMLAstroVolumeNode::UpdateDisplayThresholdAttributes : " "attempt to allocate scalars of type not allowed"); return false; } double sum = 0., noise1 = 0., noise2 = 0, noise = 0.; int lowBoundary; int highBoundary; if (StringToInt(this->GetAttribute("SlicerAstro.NAXIS")) == 3) { lowBoundary = dims[0] * dims[1] * 2; highBoundary = dims[0] * dims[1] * 4; } else if (StringToInt(this->GetAttribute("SlicerAstro.NAXIS")) == 2) { lowBoundary = dims[0] * 2; highBoundary = dims[0] * 4; } else { lowBoundary = 2; highBoundary = 4; } int cont = highBoundary - lowBoundary; #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP omp_set_num_threads(omp_get_num_procs()); #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP switch (DataType) { case VTK_SHORT: #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:sum) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (ShortIsNaN(*(outSPixel + elemCnt))) { continue; } sum += *(outSPixel + elemCnt); } sum /= cont; #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:noise1) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (ShortIsNaN(*(outSPixel + elemCnt))) { continue; } noise1 += (*(outSPixel + elemCnt) - sum) * (*(outSPixel + elemCnt) - sum); } noise1 = sqrt(noise1 / cont); break; case VTK_FLOAT: #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:sum) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (FloatIsNaN(*(outFPixel + elemCnt))) { continue; } sum += *(outFPixel + elemCnt); } sum /= cont; #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:noise1) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (FloatIsNaN(*(outFPixel + elemCnt))) { continue; } noise1 += (*(outFPixel + elemCnt) - sum) * (*(outFPixel + elemCnt) - sum); } noise1 = sqrt(noise1 / cont); break; case VTK_DOUBLE: #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:sum) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (DoubleIsNaN(*(outDPixel + elemCnt))) { continue; } sum += *(outDPixel + elemCnt); } sum /= cont; #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:noise1) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (DoubleIsNaN(*(outDPixel + elemCnt))) { continue; } noise1 += (*(outDPixel + elemCnt) - sum) * (*(outDPixel + elemCnt) - sum); } noise1 = sqrt(noise1 / cont); break; } if (StringToInt(this->GetAttribute("SlicerAstro.NAXIS")) == 3) { lowBoundary = dims[0] * dims[1] * (dims[2] - 4); highBoundary = dims[0] * dims[1] * (dims[2] - 2); } else if (StringToInt(this->GetAttribute("SlicerAstro.NAXIS")) == 2) { lowBoundary = dims[0] * (dims[1] - 4); highBoundary = dims[0] * (dims[1] - 2); } else { lowBoundary = dims[0] - 4; highBoundary = dims[0] - 2; } sum = 0.; switch (DataType) { case VTK_SHORT: #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:sum) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (ShortIsNaN(*(outSPixel + elemCnt))) { continue; } sum += *(outSPixel + elemCnt); } sum /= cont; #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:noise2) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (ShortIsNaN(*(outSPixel + elemCnt))) { continue; } noise2 += (*(outSPixel + elemCnt) - sum) * (*(outSPixel + elemCnt) - sum); } noise2 = sqrt(noise2 / cont); break; case VTK_FLOAT: #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:sum) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (FloatIsNaN(*(outFPixel + elemCnt))) { continue; } sum += *(outFPixel + elemCnt); } sum /= cont; #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:noise2) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (FloatIsNaN(*(outFPixel + elemCnt))) { continue; } noise2 += (*(outFPixel + elemCnt) - sum) * (*(outFPixel + elemCnt) - sum); } noise2 = sqrt(noise2 / cont); break; case VTK_DOUBLE: #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:sum) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (DoubleIsNaN(*(outDPixel + elemCnt))) { continue; } sum += *(outDPixel + elemCnt); } sum /= cont; #ifdef VTK_SLICER_ASTRO_SUPPORT_OPENMP #pragma omp parallel for schedule(static) reduction(+:noise2) #endif // VTK_SLICER_ASTRO_SUPPORT_OPENMP for (int elemCnt = lowBoundary; elemCnt <= highBoundary; elemCnt++) { if (DoubleIsNaN(*(outDPixel + elemCnt))) { continue; } noise2 += (*(outDPixel + elemCnt) - sum) * (*(outDPixel + elemCnt) - sum); } noise2 = sqrt(noise2 / cont); break; } noise = (noise1 + noise2) * 0.5; outSPixel = nullptr; outFPixel = nullptr; outDPixel = nullptr; delete outSPixel; delete outFPixel; delete outDPixel; if (noise < 1.E-6) { double MAX = StringToDouble(this->GetAttribute("SlicerAstro.DATAMAX")); double MIN = StringToDouble(this->GetAttribute("SlicerAstro.DATAMIN")); noise = (MAX - MIN) * 0.01; } this->SetDisplayThreshold(noise); return true; } //----------------------------------------------------------- void vtkMRMLAstroVolumeNode::SetDisplayThreshold(double DisplayThreshold) { this->SetAttribute("SlicerAstro.DisplayThreshold", DoubleToString(DisplayThreshold).c_str()); this->InvokeCustomModifiedEvent(vtkMRMLAstroVolumeNode::DisplayThresholdModifiedEvent); } //---------------------------------------------------------------------------- double vtkMRMLAstroVolumeNode::GetDisplayThreshold() { return StringToDouble(this->GetAttribute("SlicerAstro.DisplayThreshold")); } //---------------------------------------------------------------------------- void vtkMRMLAstroVolumeNode::SetROINode(vtkMRMLAnnotationROINode* node) { this->SetNodeReferenceID(this->GetROINodeReferenceRole(), (node ? node->GetID() : nullptr)); } //---------------------------------------------------------------------------- vtkMRMLAnnotationROINode *vtkMRMLAstroVolumeNode::GetROINode() { return vtkMRMLAnnotationROINode::SafeDownCast(this->GetNodeReference(this->GetROINodeReferenceRole())); } //---------------------------------------------------------------------------- void vtkMRMLAstroVolumeNode::SetROIAlignmentTransformNode(vtkMRMLTransformNode* node) { this->SetNodeReferenceID(this->GetROIAlignmentTransformNodeReferenceRole(), (node ? node->GetID() : nullptr)); } //---------------------------------------------------------------------------- void vtkMRMLAstroVolumeNode::DeleteROIAlignmentTransformNode() { vtkMRMLTransformNode* transformNode = this->GetROIAlignmentTransformNode(); if (transformNode) { this->SetROIAlignmentTransformNodeID(nullptr); if (this->GetScene()) { this->GetScene()->RemoveNode(transformNode); } } } //---------------------------------------------------------------------------- vtkMRMLTransformNode *vtkMRMLAstroVolumeNode::GetROIAlignmentTransformNode() { return vtkMRMLTransformNode::SafeDownCast(this->GetNodeReference (this->GetROIAlignmentTransformNodeReferenceRole())); } //---------------------------------------------------------------------------- void vtkMRMLAstroVolumeNode::SetROIAlignmentTransformNodeID(const char *nodeID) { this->SetNodeReferenceID(this->GetROIAlignmentTransformNodeReferenceRole(), nodeID); } //----------------------------------------------------------- void vtkMRMLAstroVolumeNode::SetPresetNode(vtkMRMLVolumePropertyNode *node) { this->SetNodeReferenceID(this->GetPresetNodeReferenceRole(), (node ? node->GetID() : nullptr)); } //----------------------------------------------------------- void vtkMRMLAstroVolumeNode::SetPresetNode(vtkMRMLNode *node) { this->SetPresetNode(vtkMRMLVolumePropertyNode::SafeDownCast(node)); } //----------------------------------------------------------- vtkMRMLNode *vtkMRMLAstroVolumeNode::GetPresetNode() { return this->GetNodeReference(this->GetPresetNodeReferenceRole()); } //----------------------------------------------------------- int vtkMRMLAstroVolumeNode::GetPresetIndex() { vtkMRMLNode* presetNode = this->GetPresetNode(); if (!presetNode) { return vtkMRMLAstroVolumeNode::LowConstantOpacityPreset; } std::string presetName = presetNode->GetName(); if (presetName.find("LowConstantOpacity") != std::string::npos) { return vtkMRMLAstroVolumeNode::LowConstantOpacityPreset; } else if (presetName.find("MediumConstantOpacity") != std::string::npos) { return vtkMRMLAstroVolumeNode::MediumConstantOpacityPreset; } else if (presetName.find("HighConstantOpacity") != std::string::npos) { return vtkMRMLAstroVolumeNode::HighConstantOpacityPreset; } else if (presetName.find("OneSurfaceGreen") != std::string::npos) { return vtkMRMLAstroVolumeNode::OneSurfaceGreenPreset; } else if (presetName.find("OneSurfaceWhite") != std::string::npos) { return vtkMRMLAstroVolumeNode::OneSurfaceWhitePreset; } else if (presetName.find("TwoSurfaces") != std::string::npos) { return vtkMRMLAstroVolumeNode::TwoSurfacesPreset; } else if (presetName.find("ThreeSurfaces") != std::string::npos) { return vtkMRMLAstroVolumeNode::ThreeSurfacesPreset; } else if (presetName.find("BrightSurface") != std::string::npos) { return vtkMRMLAstroVolumeNode::BrightSurface; } else { return vtkMRMLAstroVolumeNode::LowConstantOpacityPreset; } } //----------------------------------------------------------- void vtkMRMLAstroVolumeNode::SetVolumePropertyNode(vtkMRMLVolumePropertyNode *node) { this->SetNodeReferenceID(this->GetVolumePropertyNodeReferenceRole(), (node ? node->GetID() : nullptr)); } //----------------------------------------------------------- void vtkMRMLAstroVolumeNode::SetVolumePropertyNode(vtkMRMLNode *node) { this->SetVolumePropertyNode(vtkMRMLVolumePropertyNode::SafeDownCast(node)); } //----------------------------------------------------------- vtkMRMLNode *vtkMRMLAstroVolumeNode::GetVolumePropertyNode() { return this->GetNodeReference(this->GetVolumePropertyNodeReferenceRole()); } //----------------------------------------------------------- void vtkMRMLAstroVolumeNode::CreateNoneNode(vtkMRMLScene *scene) { // Create a None volume RGBA of 0, 0, 0 so the filters won't complain // about missing input vtkNew<vtkImageData> id; id->SetDimensions(1, 1, 1); id->AllocateScalars(VTK_DOUBLE, 4); id->GetPointData()->GetScalars()->FillComponent(0, 0.0); id->GetPointData()->GetScalars()->FillComponent(1, 125.0); id->GetPointData()->GetScalars()->FillComponent(2, 0.0); id->GetPointData()->GetScalars()->FillComponent(3, 0.0); vtkNew<vtkMRMLAstroVolumeNode> n; n->SetName("None"); // the scene will set the id n->SetAndObserveImageData(id.GetPointer()); scene->AddNode(n.GetPointer()); } //--------------------------------------------------------------------------- vtkMRMLStorageNode* vtkMRMLAstroVolumeNode::CreateDefaultStorageNode() { return vtkMRMLAstroVolumeStorageNode::New(); } //--------------------------------------------------------------------------- void vtkMRMLAstroVolumeNode::CreateDefaultDisplayNodes() { vtkMRMLAstroVolumeDisplayNode *displayNode = vtkMRMLAstroVolumeDisplayNode::SafeDownCast(this->GetDisplayNode()); if(displayNode == nullptr) { displayNode = vtkMRMLAstroVolumeDisplayNode::New(); if(this->GetScene()) { displayNode->SetScene(this->GetScene()); this->GetScene()->AddNode(displayNode); displayNode->SetDefaultColorMap(); displayNode->Delete(); this->SetAndObserveDisplayNodeID(displayNode->GetID()); vtkWarningMacro("Display node set and observed" << endl); } } }
/**************************************************************************** * * Copyright (c) 2018 - 2019 PX4 Development Team. 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. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "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 THE * COPYRIGHT OWNER 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. * ****************************************************************************/ /** * @file PositionControl.cpp */ #include "PositionControl.hpp" #include "ControlMath.hpp" #include <float.h> #include <mathlib/mathlib.h> #include <px4_platform_common/defines.h> using namespace matrix; void PositionControl::setVelocityGains(const Vector3f &P, const Vector3f &I, const Vector3f &D) { _gain_vel_p = P; _gain_vel_i = I; _gain_vel_d = D; } void PositionControl::setVelocityLimits(const float vel_horizontal, const float vel_up, const float vel_down) { _lim_vel_horizontal = vel_horizontal; _lim_vel_up = vel_up; _lim_vel_down = vel_down; } void PositionControl::setThrustLimits(const float min, const float max) { _lim_thr_min = min; _lim_thr_max = max; } void PositionControl::setState(const PositionControlStates &states) { _pos = states.position; _vel = states.velocity; _yaw = states.yaw; _vel_dot = states.acceleration; } bool PositionControl::setInputSetpoint(const vehicle_local_position_setpoint_s &setpoint) { _pos_sp = Vector3f(setpoint.x, setpoint.y, setpoint.z); _vel_sp = Vector3f(setpoint.vx, setpoint.vy, setpoint.vz); _acc_sp = Vector3f(setpoint.acceleration); _thr_sp = Vector3f(setpoint.thrust); _yaw_sp = setpoint.yaw; _yawspeed_sp = setpoint.yawspeed; bool mapping_succeeded = _interfaceMapping(); // If full manual is required (thrust already generated), don't run position/velocity // controller and just return thrust. _skip_controller = PX4_ISFINITE(_thr_sp(0)) && PX4_ISFINITE(_thr_sp(1)) && PX4_ISFINITE(_thr_sp(2)); return mapping_succeeded; } void PositionControl::setConstraints(const vehicle_constraints_s &constraints) { _constraints = constraints; // For safety check if adjustable constraints are below global constraints. If they are not stricter than global // constraints, then just use global constraints for the limits. if (!PX4_ISFINITE(constraints.tilt) || (constraints.tilt > _lim_tilt)) { _constraints.tilt = _lim_tilt; } if (!PX4_ISFINITE(constraints.speed_up) || (constraints.speed_up > _lim_vel_up)) { _constraints.speed_up = _lim_vel_up; } if (!PX4_ISFINITE(constraints.speed_down) || (constraints.speed_down > _lim_vel_down)) { _constraints.speed_down = _lim_vel_down; } // ignore _constraints.speed_xy TODO: remove it completely as soon as no task uses it anymore to avoid confusion } void PositionControl::update(const float dt) { if (_skip_controller) { // Already received a valid thrust set-point. // Limit the thrust vector. float thr_mag = _thr_sp.length(); if (thr_mag > _lim_thr_max) { _thr_sp = _thr_sp.normalized() * _lim_thr_max; } else if (thr_mag < _lim_thr_min && thr_mag > FLT_EPSILON) { _thr_sp = _thr_sp.normalized() * _lim_thr_min; } // Just set the set-points equal to the current vehicle state. _pos_sp = _pos; _vel_sp = _vel; _acc_sp = _vel_dot; return; } _positionControl(); _velocityControl(dt); } bool PositionControl::_interfaceMapping() { // if nothing is valid, then apply failsafe landing bool failsafe = false; // Respects FlightTask interface, where NAN-set-points are of no interest // and do not require control. A valid position and velocity setpoint will // be mapped to a desired position setpoint with a feed-forward term. // States and setpoints which are integrals of the reference setpoint are set to 0. // For instance: reference is velocity-setpoint -> position and position-setpoint = 0 // reference is thrust-setpoint -> position, velocity, position-/velocity-setpoint = 0 for (int i = 0; i <= 2; i++) { if (PX4_ISFINITE(_pos_sp(i))) { // Position control is required if (!PX4_ISFINITE(_vel_sp(i))) { // Velocity is not used as feedforward term. _vel_sp(i) = 0.0f; } // thrust setpoint is not supported in position control _thr_sp(i) = NAN; // to run position control, we require valid position and velocity if (!PX4_ISFINITE(_pos(i)) || !PX4_ISFINITE(_vel(i))) { failsafe = true; } } else if (PX4_ISFINITE(_vel_sp(i))) { // Velocity controller is active without position control. // Set integral states and setpoints to 0 _pos_sp(i) = _pos(i) = 0.0f; // thrust setpoint is not supported in velocity control _thr_sp(i) = NAN; // to run velocity control, we require valid velocity if (!PX4_ISFINITE(_vel(i))) { failsafe = true; } } else if (PX4_ISFINITE(_thr_sp(i))) { // Thrust setpoint was generated from sticks directly. // Set all integral states and setpoints to 0 _pos_sp(i) = _pos(i) = 0.0f; _vel_sp(i) = _vel(i) = 0.0f; // Reset the Integral term. _vel_int(i) = 0.0f; // Don't require velocity derivative. _vel_dot(i) = 0.0f; } else { // nothing is valid. do failsafe failsafe = true; } } // ensure that vel_dot is finite, otherwise set to 0 if (!PX4_ISFINITE(_vel_dot(0)) || !PX4_ISFINITE(_vel_dot(1))) { _vel_dot(0) = _vel_dot(1) = 0.0f; } if (!PX4_ISFINITE(_vel_dot(2))) { _vel_dot(2) = 0.0f; } if (!PX4_ISFINITE(_yawspeed_sp)) { // Set the yawspeed to 0 since not used. _yawspeed_sp = 0.0f; } if (!PX4_ISFINITE(_yaw_sp)) { // Set the yaw-sp equal the current yaw. // That is the best we can do and it also // agrees with FlightTask-interface definition. if (PX4_ISFINITE(_yaw)) { _yaw_sp = _yaw; } else { failsafe = true; } } // check failsafe if (failsafe) { // point the thrust upwards _thr_sp(0) = _thr_sp(1) = 0.0f; // throttle down such that vehicle goes down with // 70% of throttle range between min and hover _thr_sp(2) = -(_lim_thr_min + (_hover_thrust - _lim_thr_min) * 0.7f); // position and velocity control-loop is currently unused (flag only for logging purpose) } return !(failsafe); } void PositionControl::_positionControl() { // P-position controller const Vector3f vel_sp_position = (_pos_sp - _pos).emult(_gain_pos_p); _vel_sp = vel_sp_position + _vel_sp; // Constrain horizontal velocity by prioritizing the velocity component along the // the desired position setpoint over the feed-forward term. const Vector2f vel_sp_xy = ControlMath::constrainXY(Vector2f(vel_sp_position), Vector2f(_vel_sp - vel_sp_position), _lim_vel_horizontal); _vel_sp(0) = vel_sp_xy(0); _vel_sp(1) = vel_sp_xy(1); // Constrain velocity in z-direction. _vel_sp(2) = math::constrain(_vel_sp(2), -_constraints.speed_up, _constraints.speed_down); } void PositionControl::_velocityControl(const float dt) { // Generate desired thrust setpoint. // PID // u_des = P(vel_err) + D(vel_err_dot) + I(vel_integral) // Umin <= u_des <= Umax // // Anti-Windup: // u_des = _thr_sp; r = _vel_sp; y = _vel // u_des >= Umax and r - y >= 0 => Saturation = true // u_des >= Umax and r - y <= 0 => Saturation = false // u_des <= Umin and r - y <= 0 => Saturation = true // u_des <= Umin and r - y >= 0 => Saturation = false // // Notes: // - PID implementation is in NED-frame // - control output in D-direction has priority over NE-direction // - the equilibrium point for the PID is at hover-thrust // - the maximum tilt cannot exceed 90 degrees. This means that it is // not possible to have a desired thrust direction pointing in the positive // D-direction (= downward) // - the desired thrust in D-direction is limited by the thrust limits // - the desired thrust in NE-direction is limited by the thrust excess after // consideration of the desired thrust in D-direction. In addition, the thrust in // NE-direction is also limited by the maximum tilt. const Vector3f vel_err = _vel_sp - _vel; // Consider thrust in D-direction. float thrust_desired_D = _gain_vel_p(2) * vel_err(2) + _gain_vel_d(2) * _vel_dot(2) + _vel_int( 2) - _hover_thrust; // The Thrust limits are negated and swapped due to NED-frame. float uMax = -_lim_thr_min; float uMin = -_lim_thr_max; // make sure there's always enough thrust vector length to infer the attitude uMax = math::min(uMax, -10e-4f); // Apply Anti-Windup in D-direction. bool stop_integral_D = (thrust_desired_D >= uMax && vel_err(2) >= 0.0f) || (thrust_desired_D <= uMin && vel_err(2) <= 0.0f); if (!stop_integral_D) { _vel_int(2) += vel_err(2) * _gain_vel_i(2) * dt; // limit thrust integral _vel_int(2) = math::min(fabsf(_vel_int(2)), _lim_thr_max) * math::sign(_vel_int(2)); } // Saturate thrust setpoint in D-direction. _thr_sp(2) = math::constrain(thrust_desired_D, uMin, uMax); if (PX4_ISFINITE(_thr_sp(0)) && PX4_ISFINITE(_thr_sp(1))) { // Thrust set-point in NE-direction is already provided. Only // scaling by the maximum tilt is required. float thr_xy_max = fabsf(_thr_sp(2)) * tanf(_constraints.tilt); _thr_sp(0) *= thr_xy_max; _thr_sp(1) *= thr_xy_max; } else { // PID-velocity controller for NE-direction. Vector2f thrust_desired_NE; thrust_desired_NE(0) = _gain_vel_p(0) * vel_err(0) + _gain_vel_d(0) * _vel_dot(0) + _vel_int(0); thrust_desired_NE(1) = _gain_vel_p(1) * vel_err(1) + _gain_vel_d(1) * _vel_dot(1) + _vel_int(1); // Get maximum allowed thrust in NE based on tilt and excess thrust. float thrust_max_NE_tilt = fabsf(_thr_sp(2)) * tanf(_constraints.tilt); float thrust_max_NE = sqrtf(_lim_thr_max * _lim_thr_max - _thr_sp(2) * _thr_sp(2)); thrust_max_NE = math::min(thrust_max_NE_tilt, thrust_max_NE); // Saturate thrust in NE-direction. _thr_sp(0) = thrust_desired_NE(0); _thr_sp(1) = thrust_desired_NE(1); if (thrust_desired_NE * thrust_desired_NE > thrust_max_NE * thrust_max_NE) { float mag = thrust_desired_NE.length(); _thr_sp(0) = thrust_desired_NE(0) / mag * thrust_max_NE; _thr_sp(1) = thrust_desired_NE(1) / mag * thrust_max_NE; } // Use tracking Anti-Windup for NE-direction: during saturation, the integrator is used to unsaturate the output // see Anti-Reset Windup for PID controllers, L.Rundqwist, 1990 float arw_gain = 2.f / _gain_vel_p(0); Vector2f vel_err_lim; vel_err_lim(0) = vel_err(0) - (thrust_desired_NE(0) - _thr_sp(0)) * arw_gain; vel_err_lim(1) = vel_err(1) - (thrust_desired_NE(1) - _thr_sp(1)) * arw_gain; // Update integral _vel_int(0) += _gain_vel_i(0) * vel_err_lim(0) * dt; _vel_int(1) += _gain_vel_i(1) * vel_err_lim(1) * dt; } } void PositionControl::getLocalPositionSetpoint(vehicle_local_position_setpoint_s &local_position_setpoint) const { local_position_setpoint.x = _pos_sp(0); local_position_setpoint.y = _pos_sp(1); local_position_setpoint.z = _pos_sp(2); local_position_setpoint.yaw = _yaw_sp; local_position_setpoint.yawspeed = _yawspeed_sp; local_position_setpoint.vx = _vel_sp(0); local_position_setpoint.vy = _vel_sp(1); local_position_setpoint.vz = _vel_sp(2); _acc_sp.copyTo(local_position_setpoint.acceleration); _thr_sp.copyTo(local_position_setpoint.thrust); } void PositionControl::getAttitudeSetpoint(vehicle_attitude_setpoint_s &attitude_setpoint) const { ControlMath::thrustToAttitude(_thr_sp, _yaw_sp, attitude_setpoint); attitude_setpoint.yaw_sp_move_rate = _yawspeed_sp; }
#include "bits/stdc++.h" using namespace std; using namespace std; typedef long long ll; typedef vector<ll> vli; typedef vector< vli > vvli; ///////////////////////// #define F first #define S second #define PB push_back #define MP make_pair #define loop(i,a,b) for (ll i = a; i < b; i++) ////////////////////////// #define printvector(n) for(int i=0;i<n.size();i++){cout<<n[i]<<" ";}cout<<'\n' #define printstack(n) for(int i=0;i<n.size();i++){cout<<n[i]<<" ";}cout<<'\n' #define PI_val 3.14159265359 #define vasort(v) sort((v).begin(), (v).end()) #define vdsort(v) sort((v).begin(), (v).end(),greater<int>()) #define printpair(n) cout<<n.F<<" "<<n.S #define printvop(n) loop(i,0,n.size()-1){printpair(n[i])<<endl;} #define fio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) #define endl "\n" #define ln endl #define out1(x1) cout << x1 << ln #define out2(x1,x2) cout << x1 << " " << x2 << ln #define out3(x1,x2,x3) cout << x1 << " " << x2 << " " << x3 << ln #define out4(x1,x2,x3,x4) cout << x1 << " " << x2 << " " << x3 << " " << x4 << ln #define out5(x1,x2,x3,x4,x5) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << ln #define out6(x1,x2,x3,x4,x5,x6) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << " " << x6 << ln long long mod=1000000007; ////////////////////////// int main() { #ifndef ONLINE_JUDGE // for getting input from input.txt freopen("E:/codes/testcases/input.in", "r", stdin); // for writing output to output.txt freopen("E:/codes/testcases/output.in", "w", stdout); #endif fio; ll t; cin >> t; while(t--) { ll x,y,p,q,n,m,k,sum=0,ans=0,res=0; string s,r; cin>>n; cin>>s; ll a=0,b=n-1; while(a<b){ while(s[a]!='t'&&a<n){ a++; } while(s[b]!='b'&&b>=0){ b--; } if(a>=n||b<0||a>=b){ break; } s[a]='b'; s[b]='t'; continue; } cout<<s<<endl; // printvector(arr); // sort(arr.begin(),arr.end()); } return 0; }
/*========================== begin_copyright_notice ============================ Copyright (C) 2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ #include <cm-cl/vector.h> #include <opencl_def.h> using namespace cm; extern "C" { #include "spirv_math.h" } #define IGC_OCL_BUILTIN_NAME_1ARG_SCALAR(FUNC_NAME, POSTFIX_TYPE) \ __builtin_spirv_OpenCL_##FUNC_NAME##_##POSTFIX_TYPE #define SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(FUNC_NAME, TYPE, \ OCL_TYPE_POST_FIX) \ CM_NODEBUG CM_INLINE TYPE __spirv_ocl_##FUNC_NAME(TYPE x) { \ return IGC_OCL_BUILTIN_NAME_1ARG_SCALAR(FUNC_NAME, OCL_TYPE_POST_FIX)(x); \ } SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(exp, float, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(exp, double, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(log, float, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(log, double, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(sin, float, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(sin, double, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(asin, float, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(asin, double, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(cos, float, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(cos, double, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(acos, float, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(acos, double, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(tan, float, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(tan, double, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(atan, float, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_SCALAR(atan, double, f64); #define IGC_OCL_BUILTIN_NAME_2ARG_SCALAR(FUNC_NAME, POSTFIX_TYPE) \ __builtin_spirv_OpenCL_##FUNC_NAME##_##POSTFIX_TYPE##_##POSTFIX_TYPE #define SPIRV_MATH_BUILTIN_DECL_2ARG_SCALAR(FUNC_NAME, TYPE, \ OCL_TYPE_POST_FIX) \ CM_NODEBUG CM_INLINE TYPE __spirv_ocl_##FUNC_NAME(TYPE x, TYPE y) { \ return IGC_OCL_BUILTIN_NAME_2ARG_SCALAR(FUNC_NAME, OCL_TYPE_POST_FIX)(x, \ y); \ } SPIRV_MATH_BUILTIN_DECL_2ARG_SCALAR(pow, float, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_SCALAR(pow, double, f64); SPIRV_MATH_BUILTIN_DECL_2ARG_SCALAR(atan2, float, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_SCALAR(atan2, double, f64); #define IGC_OCL_BUILTIN_NAME_1ARG_VECTOR(FUNC_NAME, N, POSTFIX_TYPE) \ __builtin_spirv_OpenCL_##FUNC_NAME##_v##N##POSTFIX_TYPE #define SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(FUNC_NAME, TYPE, N, \ OCL_TYPE_POST_FIX) \ CM_NODEBUG CM_INLINE cl_vector<TYPE, N> __spirv_ocl_##FUNC_NAME( \ cl_vector<TYPE, N> x) { \ return IGC_OCL_BUILTIN_NAME_1ARG_VECTOR(FUNC_NAME, N, \ OCL_TYPE_POST_FIX)(x); \ } SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(exp, float, 2, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(exp, float, 3, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(exp, float, 4, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(exp, float, 8, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(exp, float, 16, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(exp, double, 2, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(exp, double, 3, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(exp, double, 4, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(exp, double, 8, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(exp, double, 16, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(log, float, 2, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(log, float, 3, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(log, float, 4, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(log, float, 8, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(log, float, 16, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(log, double, 2, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(log, double, 3, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(log, double, 4, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(log, double, 8, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(log, double, 16, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(sin, float, 2, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(sin, float, 3, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(sin, float, 4, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(sin, float, 8, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(sin, float, 16, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(sin, double, 2, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(sin, double, 3, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(sin, double, 4, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(sin, double, 8, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(sin, double, 16, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(asin, float, 2, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(asin, float, 3, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(asin, float, 4, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(asin, float, 8, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(asin, float, 16, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(asin, double, 2, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(asin, double, 3, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(asin, double, 4, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(asin, double, 8, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(asin, double, 16, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(cos, float, 2, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(cos, float, 3, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(cos, float, 4, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(cos, float, 8, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(cos, float, 16, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(cos, double, 2, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(cos, double, 3, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(cos, double, 4, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(cos, double, 8, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(cos, double, 16, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(acos, float, 2, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(acos, float, 3, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(acos, float, 4, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(acos, float, 8, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(acos, float, 16, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(acos, double, 2, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(acos, double, 3, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(acos, double, 4, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(acos, double, 8, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(acos, double, 16, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(tan, float, 2, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(tan, float, 3, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(tan, float, 4, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(tan, float, 8, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(tan, float, 16, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(tan, double, 2, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(tan, double, 3, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(tan, double, 4, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(tan, double, 8, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(tan, double, 16, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(atan, float, 2, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(atan, float, 3, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(atan, float, 4, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(atan, float, 8, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(atan, float, 16, f32); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(atan, double, 2, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(atan, double, 3, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(atan, double, 4, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(atan, double, 8, f64); SPIRV_MATH_BUILTIN_DECL_1ARG_VECTOR(atan, double, 16, f64); #define IGC_OCL_BUILTIN_NAME_2ARG_VECTOR(FUNC_NAME, N, POSTFIX_TYPE) \ __builtin_spirv_OpenCL_##FUNC_NAME##_v##N##POSTFIX_TYPE##_##v##N##POSTFIX_TYPE #define SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(FUNC_NAME, TYPE, N, \ OCL_TYPE_POST_FIX) \ CM_NODEBUG CM_INLINE cl_vector<TYPE, N> __spirv_ocl_##FUNC_NAME( \ cl_vector<TYPE, N> x, cl_vector<TYPE, N> y) { \ return IGC_OCL_BUILTIN_NAME_2ARG_VECTOR(FUNC_NAME, N, \ OCL_TYPE_POST_FIX)(x, y); \ } SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(pow, float, 2, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(pow, float, 3, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(pow, float, 4, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(pow, float, 8, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(pow, float, 16, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(pow, double, 2, f64); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(pow, double, 3, f64); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(pow, double, 4, f64); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(pow, double, 8, f64); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(pow, double, 16, f64); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(atan2, float, 2, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(atan2, float, 3, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(atan2, float, 4, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(atan2, float, 8, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(atan2, float, 16, f32); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(atan2, double, 2, f64); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(atan2, double, 3, f64); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(atan2, double, 4, f64); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(atan2, double, 8, f64); SPIRV_MATH_BUILTIN_DECL_2ARG_VECTOR(atan2, double, 16, f64);
#include <ros/ros.h> #include <std_msgs/String.h> #include <std_msgs/Char.h> #include <std_msgs/Int32.h> #include <vector> #include <sys/stat.h> #include <termios.h> //#include <term.h> #include <unistd.h> //socket #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <arpa/inet.h> #include <unistd.h> #include <errno.h> #include <netinet/in.h> #include <sstream> #include <stdlib.h> #include <string> #define SERVER_PORT 5005 #define LENGTH_OF_LISTEN_QUEUE 20 using namespace std; int main(int argc, char** argv) { ros::init(argc, argv, "server2topic"); ros::NodeHandle nh_; ros::Publisher topic_pub_; //topic_pub_ = nh_.advertise<std_msgs::Int32>("socket2topic", 1); topic_pub_ = nh_.advertise<std_msgs::String>("socket2topic", 1); //设置一个socket地址结构server_addr,代表服务器internet地址, 端口 struct sockaddr_in server_addr; bzero(&server_addr,sizeof(server_addr)); //把一段内存区的内容全部设置为0 server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htons(INADDR_ANY); server_addr.sin_port = htons(SERVER_PORT); cout<<"start socket2topic_nd"<<endl; //创建用于internet的流协议(TCP)socket,用server_socket代表服务器socket int server_socket = socket(PF_INET,SOCK_STREAM,0); if( server_socket < 0) { printf("Create Socket Failed!"); exit(1); } int opt =1; setsockopt(server_socket,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); //把socket和socket地址结构联系起来 if( bind(server_socket,(struct sockaddr*)&server_addr,sizeof(server_addr))) { printf("Server Bind Port : %d Failed!", SERVER_PORT); exit(1); } //server_socket用于监听 if ( listen(server_socket, LENGTH_OF_LISTEN_QUEUE) ) { printf("Server Listen Failed!"); exit(1); } cout<<"server is listening...\n"; while(1) //服务器端要一直运行 { //定义客户端的socket地址结构client_addr struct sockaddr_in client_addr; socklen_t length = sizeof(client_addr); int new_server_socket = accept(server_socket,(struct sockaddr*)&client_addr,&length); if ( new_server_socket < 0) { printf("Server Accept Failed!\n"); break; } char ssvepClass[1]; //length = recv(new_server_socket, (char*)&ssvepClass, sizeof(ssvepClass), 0); length = recv(new_server_socket, ssvepClass, sizeof(ssvepClass), 0); if (length < 0) { printf("Server Recieve Data Failed!\n"); return false; } else { std_msgs::String msg; msg.data = ssvepClass[0]; std::cout << "msg.data:" << msg.data << endl; topic_pub_.publish(msg); } //close //关闭与客户端的连接(new_server_socket); } //关闭监听用的socket close(server_socket); return 0; }
/* * Copyright (c) 2022, Idan Horowitz <idan.horowitz@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/Intl/SegmentIterator.h> #include <LibJS/Runtime/Intl/Segments.h> namespace JS::Intl { // 18.6.1 CreateSegmentIterator ( segmenter, string ), https://tc39.es/ecma402/#sec-createsegmentsobject SegmentIterator* SegmentIterator::create(GlobalObject& global_object, Segmenter& segmenter, Utf16View const& string, Segments const& segments) { // 1. Let internalSlotsList be « [[IteratingSegmenter]], [[IteratedString]], [[IteratedStringNextSegmentCodeUnitIndex]] ». // 2. Let iterator be ! OrdinaryObjectCreate(%SegmentIteratorPrototype%, internalSlotsList). // 3. Set iterator.[[IteratingSegmenter]] to segmenter. // 4. Set iterator.[[IteratedString]] to string. // 5. Set iterator.[[IteratedStringNextSegmentCodeUnitIndex]] to 0. // 6. Return iterator. return global_object.heap().allocate<SegmentIterator>(global_object, global_object, segmenter, move(string), segments); } // 18.6 Segment Iterator Objects, https://tc39.es/ecma402/#sec-segment-iterator-objects SegmentIterator::SegmentIterator(GlobalObject& global_object, Segmenter& segmenter, Utf16View const& string, Segments const& segments) : Object(*global_object.intl_segment_iterator_prototype()) , m_iterating_segmenter(segmenter) , m_iterated_string(string) , m_segments(segments) { } void SegmentIterator::visit_edges(Cell::Visitor& visitor) { Base::visit_edges(visitor); visitor.visit(&m_iterating_segmenter); visitor.visit(&m_segments); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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. */ /*! * \file buffer.cc */ #include <tvm/tir/buffer.h> #include <tvm/runtime/device_api.h> #include <tvm/tir/expr.h> #include <tvm/tir/ir_pass.h> #include <iterator> #include <stack> #include "../../arith/compute_expr.h" namespace tvm { namespace tir { // TODO(tqchen): change to floormod/div using IndexMod = tir::FloorModNode; using IndexDiv = tir::FloorDivNode; Array<PrimExpr> SimplifyArray(Array<PrimExpr> array) { for (size_t i = 0; i < array.size(); ++i) { array.Set(i, tir::Simplify(array[i])); } return array; } Buffer decl_buffer(Array<PrimExpr> shape, DataType dtype, std::string name) { return BufferNode::make( Var(name, DataType::Handle()), dtype, shape, Array<PrimExpr>(), PrimExpr(), name, "", 0, 0, kDefault); } // Split the given expression w.r.t the add operator inline std::vector<const PrimExpr*> ExprSplitAddition(const PrimExpr &expr) { using namespace tir; std::vector<const PrimExpr*> ret; std::stack<const PrimExpr*> split_buffer; split_buffer.push(&expr); while (!split_buffer.empty()) { const PrimExpr* top_ele = split_buffer.top(); split_buffer.pop(); auto expr_add_match = top_ele->as<AddNode>(); if (expr_add_match) { split_buffer.push(&expr_add_match->b); split_buffer.push(&expr_add_match->a); } else { ret.emplace_back(top_ele); } } return ret; } // Searches for the following types of expr: // mult_expr = (a1 + a2 + ... + aj + c / (k1 * k2 * ... * ki) * k1 * ... * kt-1 ) * kt * ... * ki // mod_l_expr = c // mod_r_expr = k1 * k2 * ... * ki // If it can be optimized, returns (true, (a1 + a2 + ... + aj) * kt * ... * ki + c) // Currently the we will not search the add/mult combinations exhaustively // as it will take too much computation. inline std::pair<bool, PrimExpr> MergeMulModInner(const PrimExpr &mult_expr, const PrimExpr &mod_l_expr, const PrimExpr &mod_r_expr) { using namespace tir; const MulNode* mult_ptr = mult_expr.as<MulNode>(); if (!mult_ptr) return std::make_pair(false, PrimExpr()); PrimExpr mult_outer = mult_ptr->b; const PrimExpr* inner = &(mult_ptr->a); // 1. Calculate the outer multiplier while (true) { mult_ptr = inner->as<MulNode>(); if (mult_ptr) { inner = &(mult_ptr->a); mult_outer = mult_ptr->b * mult_outer; } else { break; } } // 2. Search for the pattern c / (...) * (...) + c % (...) // We match the search element with Add, Mul and Div. // If Add is found, we need to continue our search for the rhs // If Mult is found, we will expand the inner multiplication factor // If Div is found, we will go on testing whether lhs matches the lhs of mod expr // and returns the optimization result. const PrimExpr* search_ptr = inner; PrimExpr mult_inner; // The inner multiplication factor PrimExpr no_opt_sum; // Sum of the exprs that cannot be optimized while (true) { auto inner_div_ptr = search_ptr->as<IndexDiv>(); auto inner_mult_ptr = search_ptr->as<MulNode>(); auto inner_add_ptr = search_ptr->as<AddNode>(); if (!inner_div_ptr && !inner_mult_ptr && !inner_add_ptr) { return std::make_pair(false, PrimExpr()); } else if (inner_div_ptr) { PrimExpr overall_mult = mult_inner.get() ? mult_inner * mult_outer : mult_outer; if (Equal(overall_mult, inner_div_ptr->b) && Equal(overall_mult, mod_r_expr) && Equal(inner_div_ptr->a, mod_l_expr)) { // Found! PrimExpr ret = no_opt_sum.get() ? no_opt_sum * mult_outer + mod_l_expr : mod_l_expr; return std::make_pair(true, ret); } else { return std::make_pair(false, PrimExpr()); } } else if (inner_mult_ptr) { mult_inner = mult_inner.get() ? inner_mult_ptr->b * mult_inner : inner_mult_ptr->b; search_ptr = &(inner_mult_ptr->a); } else if (inner_add_ptr) { if (mult_inner.get()) { return std::make_pair(false, PrimExpr()); } no_opt_sum = no_opt_sum.get() ? no_opt_sum + inner_add_ptr->a : inner_add_ptr->a; search_ptr = &(inner_add_ptr->b); } else { LOG(FATAL) << "Unexpected search result!"; break; } } return std::make_pair(false, PrimExpr()); } // Insert the elements into the corresponding mult_exprs and mod_exprs. // If the element is found to match Mul, it will be pushed to the mult_exprs. // If the element it found to match Mod, it will be pused to the mod_exprs. // Otherwise, the elements will be added to the no_opt_sum variable inline void MergeMulModInsertElements(const std::vector<const PrimExpr*>& eles, std::list<PrimExpr>* mult_exprs, std::list<std::pair<PrimExpr, PrimExpr> >* mod_exprs, PrimExpr* no_opt_sum, bool* has_mult, bool* has_mod) { using namespace tir; *has_mult = false; *has_mod = false; for (const PrimExpr* ele : eles) { auto mod_ptr = ele->as<IndexMod>(); auto mult_ptr = ele->as<MulNode>(); if (mod_ptr) { *has_mod = true; mod_exprs->emplace_back(std::make_pair(std::move(mod_ptr->a), std::move(mod_ptr->b))); } else if (mult_ptr) { *has_mult = true; mult_exprs->emplace_back(*ele); } else { *no_opt_sum = no_opt_sum->get() ? *no_opt_sum + *ele : *ele; } } } // Searches for this types of expr: // (a1 + a2 + ... + aj + c / (k1 * k2 * ... * ki) * k1 * ... * kt-1 ) * kt * ... * ki // + c % (k1 * k2 * ... * ki) // and simplifies to (a1 + a2 + ... + aj) * kt * ... * ki + c // The search will be performed repeatively until no pattern is found. // Return: a pair with (false, Expr()) if cannot be optimized. // a pair with (true, optimized_expr) if can be optimized inline PrimExpr MergeMulMod(const PrimExpr &base) { using namespace tir; // 1. Prepare the lists. // We store two lists, a list that contain all the elements that match Mul and // a list that contain all the elements that match Mod. // The elements in the Mod will be used to match against the elements in Mul. // The result will then be split and pushed back to these two lists. PrimExpr simplified_base = Simplify(base); std::vector<const PrimExpr*> eles = ExprSplitAddition(simplified_base); std::list<PrimExpr> mult_exprs; std::list<std::pair<PrimExpr, PrimExpr> > mod_exprs; PrimExpr no_opt_sum; bool has_mult; bool has_mod; MergeMulModInsertElements(eles, &mult_exprs, &mod_exprs, &no_opt_sum, &has_mult, &has_mod); bool find_opt = false; std::list<std::pair<PrimExpr, PrimExpr> >::iterator search_mod_it = mod_exprs.begin(); // 2. Exhaustive Search while (search_mod_it != mod_exprs.end()) { std::list<PrimExpr>::iterator mult_it = mult_exprs.begin(); bool inner_find_opt = false; while (mult_it != mult_exprs.end()) { std::pair<bool, PrimExpr> ret = MergeMulModInner(*mult_it, search_mod_it->first, search_mod_it->second); if (ret.first) { inner_find_opt = true; auto temp_mod_it = search_mod_it; ++search_mod_it; mod_exprs.erase(temp_mod_it); mult_exprs.erase(mult_it); std::vector<const PrimExpr*> ret_eles = ExprSplitAddition(ret.second); MergeMulModInsertElements(ret_eles, &mult_exprs, &mod_exprs, &no_opt_sum, &has_mult, &has_mod); if (has_mult) { search_mod_it = mod_exprs.begin(); } else if (has_mod && search_mod_it == mod_exprs.end()) { search_mod_it--; } break; } else { ++mult_it; } } find_opt = find_opt || inner_find_opt; if (!inner_find_opt) { ++search_mod_it; } } if (!find_opt) { return simplified_base; } for (std::list<PrimExpr>::iterator it = mult_exprs.begin(); it != mult_exprs.end(); ++it) { no_opt_sum = no_opt_sum.get() ? no_opt_sum + *it : *it; } for (std::list<std::pair<PrimExpr, PrimExpr> >::iterator it = mod_exprs.begin(); it != mod_exprs.end(); ++it) { no_opt_sum = no_opt_sum.get() ? no_opt_sum + indexmod(it->first, it->second) : indexmod(it->first, it->second); } return no_opt_sum; } // The buffer offset in convention of number of elements of // original data ignoring number of lanes. // We also perform optimization to simplify the indexing expression. inline PrimExpr ElemOffset(const BufferNode* n, Array<PrimExpr> index) { PrimExpr base = n->elem_offset; if (n->strides.size() == 0) { // Scalar case if (n->shape.size() == 0 && index.size() == 1) { auto is_int = index[0].as<IntImmNode>(); CHECK(is_int && is_int->value == 0); base = base + index[0]; } else { CHECK_EQ(n->shape.size(), index.size()); if (index.size() > 0) { PrimExpr offset = index[0]; for (size_t i = 1; i < index.size(); ++i) { offset = MergeMulMod(offset * n->shape[i] + index[i]); } base = base + offset; } } } else { CHECK_EQ(n->strides.size(), index.size()); if (is_zero(base)) { base = MergeMulMod(index[0] * n->strides[0]); } else { base = MergeMulMod(base + index[0] * n->strides[0]); } for (size_t i = 1; i < index.size(); ++i) { base = MergeMulMod(base + index[i] * n->strides[i]); } } return base; } inline PrimExpr BufferOffset(const BufferNode* n, Array<PrimExpr> index, DataType dtype) { PrimExpr offset = ElemOffset(n, index); if (n->dtype.lanes() != 1) { offset = offset * make_const(offset.dtype(), dtype.lanes()); } if (dtype.lanes() != 1) { return tir::RampNode::make(offset, make_const(offset.dtype(), 1), dtype.lanes()); } else { return offset; } } PrimExpr Buffer::vload(Array<PrimExpr> begin, DataType dtype) const { // specially handle bool, stored asDataType::Int(8) const BufferNode* n = operator->(); CHECK(dtype.element_of() == n->dtype.element_of() && dtype.lanes() % n->dtype.lanes() == 0) << "Cannot load " << dtype << " from buffer of " << n->dtype; if (dtype == DataType::Bool()) { return tir::CastNode::make( DataType::Bool(), tir::LoadNode::make( DataType::Int(8), n->data, BufferOffset(n, begin, DataType::Int(8)), const_true())); } else { return tir::LoadNode::make( dtype, n->data, BufferOffset(n, begin, dtype), const_true(dtype.lanes())); } } Stmt Buffer::vstore(Array<PrimExpr> begin, PrimExpr value) const { // specially handle bool, stored asDataType::Int(8) const BufferNode* n = operator->(); DataType dtype = value.dtype(); CHECK(dtype.element_of() == n->dtype.element_of() && dtype.lanes() % n->dtype.lanes() == 0) << "Cannot load " << dtype << " from buffer of " << n->dtype; if (value.dtype() == DataType::Bool()) { return tir::StoreNode::make(n->data, tir::CastNode::make(DataType::Int(8), value), BufferOffset(n, begin, DataType::Int(8)), const_true()); } else { return tir::StoreNode::make(n->data, value, BufferOffset(n, begin, dtype), const_true(dtype.lanes())); } } Buffer Buffer::MakeStrideView() const { if ((*this)->strides.size() != 0) return *this; if ((*this)->shape.size() == 0) return *this; std::vector<PrimExpr> temp; auto n = make_object<BufferNode>(*operator->()); PrimExpr acc = make_const(n->DefaultIndexType(), 1); for (size_t i = n->shape.size(); i != 0 ; --i) { temp.push_back(acc); acc = acc * n->shape[i - 1]; } for (size_t i = temp.size(); i != 0; --i) { n->strides.push_back(temp[i - 1]); } return Buffer(n); } Buffer Buffer::MakeSlice(Array<PrimExpr> begins, Array<PrimExpr> extents) const { const BufferNode* n = operator->(); begins = SimplifyArray(begins); PrimExpr elem_offset = tir::Simplify(ElemOffset(n, begins)); Array<PrimExpr> strides = n->strides; if (strides.size() == 0) { bool can_relax = true; bool need_stride = false; // check if stride is needed. for (size_t i = 0; i < extents.size(); ++i) { if (!can_relax) { if (!is_zero(begins[i]) || !is_zero(tir::Simplify(extents[i] - n->shape[i]))) { need_stride = true; } } if (!is_one(extents[i])) can_relax = false; } // make stride. if (need_stride) { return MakeStrideView().MakeSlice(begins, extents); } } return BufferNode::make(n->data, n->dtype, extents, strides, elem_offset, n->name + "_slice", n->scope, n->data_alignment, 0, n->buffer_type); } PrimExpr Buffer::access_ptr(int access_mask, DataType ptr_type, int content_lanes, PrimExpr offset) const { const BufferNode* self = operator->(); PrimExpr e_dtype; PrimExpr extent; if (self->shape.size() == 0) { extent = make_const(self->DefaultIndexType(), 1); } else if (self->strides.size() == self->shape.size()) { int highest_dim = 0; extent = self->strides[highest_dim] * self->shape[highest_dim] - offset; } else { extent = arith::ComputeReduce<tir::MulNode>(self->shape, PrimExpr()) - offset; } PrimExpr elem_offset = self->elem_offset + offset; if (content_lanes > 1) { e_dtype = tir::TypeAnnotation(self->dtype.with_lanes(content_lanes)); extent = extent / make_const(self->elem_offset.dtype(), content_lanes); elem_offset = self->elem_offset / make_const(self->elem_offset.dtype(), content_lanes); } else { e_dtype = tir::TypeAnnotation(self->dtype); } Array<PrimExpr> acc_args{ e_dtype, self->data, elem_offset, extent, make_const(DataType::Int(32), access_mask)}; return tir::CallNode::make( ptr_type, tir::intrinsic::tvm_access_ptr, acc_args, tir::CallNode::Intrinsic); } Buffer BufferNode::make(Var data, DataType dtype, Array<PrimExpr> shape, Array<PrimExpr> strides, PrimExpr elem_offset, std::string name, std::string scope, int data_alignment, int offset_factor, BufferType buffer_type) { auto n = make_object<BufferNode>(); n->data = std::move(data); n->dtype = dtype; n->shape = std::move(shape); n->strides = std::move(strides); n->name = std::move(name); if (scope.length() == 0) { scope = "global"; } n->scope = std::move(scope); if (!elem_offset.defined()) { elem_offset = make_const(n->DefaultIndexType(), 0); } if (data_alignment <= 0) { data_alignment = runtime::kAllocAlignment; } if (offset_factor == 0) { offset_factor = 1; } n->elem_offset = std::move(elem_offset); n->data_alignment = data_alignment; n->offset_factor = offset_factor; n->buffer_type = buffer_type; if (n->buffer_type == kAutoBroadcast && n->shape.size() > 0 && n->strides.empty()) { for (size_t i = 0; i < n->shape.size(); ++i) { n->strides.push_back(Var("stride")); } } return Buffer(n); } TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable) .set_dispatch<BufferNode>([](const ObjectRef& node, ReprPrinter* p) { auto* op = static_cast<const BufferNode*>(node.get()); p->stream << "buffer(" << op->name << ", " << op << ")"; }); TVM_REGISTER_NODE_TYPE(BufferNode); } // namespace tir } // namespace tvm
// Copyright 2010 Google Inc. All Rights Reserved. // Authors: gpike@google.com (Geoff Pike), jyrki@google.com (Jyrki Alakuijala) // // This file provides CityHash64() and related functions. // // The externally visible functions follow the naming conventions of // hash.h, where the size of the output is part of the name. For // example, CityHash64 returns a 64-bit hash. The internal helpers do // not have the return type in their name, but instead have names like // HashLenXX or HashLenXXtoYY, where XX and YY are input string lengths. // // Most of the constants and tricks here were copied from murmur.cc or // hash.h, or discovered by trial and error. It's probably possible to further // optimize the code here by writing a program that systematically explores // more of the space of possible hash functions, or by using SIMD instructions. #include "gutil/hash/city.h" #include <sys/types.h> #include <algorithm> using std::copy; using std::max; using std::min; using std::reverse; using std::sort; using std::swap; #include <utility> using std::make_pair; using std::pair; #include "gutil/int128.h" #include "gutil/integral_types.h" #include <common/logging.h> #include "gutil/hash/hash128to64.h" #include "gutil/endian.h" namespace util_hash { // Some primes between 2^63 and 2^64 for various uses. static const uint64 k0 = 0xa5b85c5e198ed849ULL; static const uint64 k1 = 0x8d58ac26afe12e47ULL; static const uint64 k2 = 0xc47b6e9e3a970ed3ULL; static const uint64 k3 = 0xc70f6907e782aa0bULL; // Bitwise right rotate. Normally this will compile to a single // instruction, especially if the shift is a manifest constant. static uint64 Rotate(uint64 val, int shift) { DCHECK_GE(shift, 0); DCHECK_LE(shift, 63); // Avoid shifting by 64: doing so yields an undefined result. return shift == 0 ? val : ((val >> shift) | (val << (64 - shift))); } // Equivalent to Rotate(), but requires the second arg to be non-zero. // On x86-64, and probably others, it's possible for this to compile // to a single instruction if both args are already in registers. static uint64 RotateByAtLeast1(uint64 val, int shift) { DCHECK_GE(shift, 1); DCHECK_LE(shift, 63); return (val >> shift) | (val << (64 - shift)); } static uint64 ShiftMix(uint64 val) { return val ^ (val >> 47); } static uint64 HashLen16(uint64 u, uint64 v) { return Hash128to64(uint128(u, v)); } static uint64 HashLen0to16(const char *s, size_t len) { DCHECK_GE(len, 0); DCHECK_LE(len, 16); if (len > 8) { uint64 a = LittleEndian::Load64(s); uint64 b = LittleEndian::Load64(s + len - 8); return HashLen16(a, RotateByAtLeast1(b + len, len)) ^ b; } if (len >= 4) { uint64 a = LittleEndian::Load32(s); return HashLen16(len + (a << 3), LittleEndian::Load32(s + len - 4)); } if (len > 0) { uint8 a = s[0]; uint8 b = s[len >> 1]; uint8 c = s[len - 1]; uint32 y = static_cast<uint32>(a) + (static_cast<uint32>(b) << 8); uint32 z = len + (static_cast<uint32>(c) << 2); return ShiftMix(y * k2 ^ z * k3) * k2; } return k2; } // This probably works well for 16-byte strings as well, but it may be overkill // in that case. static uint64 HashLen17to32(const char *s, size_t len) { DCHECK_GE(len, 17); DCHECK_LE(len, 32); uint64 a = LittleEndian::Load64(s) * k1; uint64 b = LittleEndian::Load64(s + 8); uint64 c = LittleEndian::Load64(s + len - 8) * k2; uint64 d = LittleEndian::Load64(s + len - 16) * k0; return HashLen16(Rotate(a - b, 43) + Rotate(c, 30) + d, a + Rotate(b ^ k3, 20) - c + len); } // Return a 16-byte hash for 48 bytes. Quick and dirty. // Callers do best to use "random-looking" values for a and b. // (For more, see the code review discussion of CL 18799087.) static pair<uint64, uint64> WeakHashLen32WithSeeds( uint64 w, uint64 x, uint64 y, uint64 z, uint64 a, uint64 b) { a += w; b = Rotate(b + a + z, 51); uint64 c = a; a += x; a += y; b += Rotate(a, 23); return make_pair(a + z, b + c); } // Return a 16-byte hash for s[0] ... s[31], a, and b. Quick and dirty. static pair<uint64, uint64> WeakHashLen32WithSeeds( const char* s, uint64 a, uint64 b) { return WeakHashLen32WithSeeds(LittleEndian::Load64(s), LittleEndian::Load64(s + 8), LittleEndian::Load64(s + 16), LittleEndian::Load64(s + 24), a, b); } // Return an 8-byte hash for 33 to 64 bytes. static uint64 HashLen33to64(const char *s, size_t len) { uint64 z = LittleEndian::Load64(s + 24); uint64 a = LittleEndian::Load64(s) + (len + LittleEndian::Load64(s + len - 16)) * k0; uint64 b = Rotate(a + z, 52); uint64 c = Rotate(a, 37); a += LittleEndian::Load64(s + 8); c += Rotate(a, 7); a += LittleEndian::Load64(s + 16); uint64 vf = a + z; uint64 vs = b + Rotate(a, 31) + c; a = LittleEndian::Load64(s + 16) + LittleEndian::Load64(s + len - 32); z += LittleEndian::Load64(s + len - 8); b = Rotate(a + z, 52); c = Rotate(a, 37); a += LittleEndian::Load64(s + len - 24); c += Rotate(a, 7); a += LittleEndian::Load64(s + len - 16); uint64 wf = a + z; uint64 ws = b + Rotate(a, 31) + c; uint64 r = ShiftMix((vf + ws) * k2 + (wf + vs) * k0); return ShiftMix(r * k0 + vs) * k2; } uint64 CityHash64(const char *s, size_t len) { if (len <= 32) { if (len <= 16) { return HashLen0to16(s, len); } else { return HashLen17to32(s, len); } } else if (len <= 64) { return HashLen33to64(s, len); } // For strings over 64 bytes we hash the end first, and then as we // loop we keep 56 bytes of state: v, w, x, y, and z. uint64 x = LittleEndian::Load64(s + len - 40); uint64 y = LittleEndian::Load64(s + len - 16) + LittleEndian::Load64(s + len - 56); uint64 z = HashLen16(LittleEndian::Load64(s + len - 48) + len, LittleEndian::Load64(s + len - 24)); pair<uint64, uint64> v = WeakHashLen32WithSeeds(s + len - 64, len, z); pair<uint64, uint64> w = WeakHashLen32WithSeeds(s + len - 32, y + k1, x); x = x * k1 + LittleEndian::Load64(s); // Decrease len to the nearest multiple of 64, and operate on 64-byte chunks. len = (len - 1) & ~static_cast<size_t>(63); DCHECK_GT(len, 0); DCHECK_EQ(len, len / 64 * 64); do { x = Rotate(x + y + v.first + LittleEndian::Load64(s + 8), 37) * k1; y = Rotate(y + v.second + LittleEndian::Load64(s + 48), 42) * k1; x ^= w.second; y += v.first + LittleEndian::Load64(s + 40); z = Rotate(z + w.first, 33) * k1; v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y + LittleEndian::Load64(s + 16)); std::swap(z, x); s += 64; len -= 64; } while (len != 0); return HashLen16(HashLen16(v.first, w.first) + ShiftMix(y) * k1 + z, HashLen16(v.second, w.second) + x); } uint64 CityHash64WithSeed(const char *s, size_t len, uint64 seed) { return CityHash64WithSeeds(s, len, k2, seed); } uint64 CityHash64WithSeeds(const char *s, size_t len, uint64 seed0, uint64 seed1) { return HashLen16(CityHash64(s, len) - seed0, seed1); } // A subroutine for CityHash128(). Returns a decent 128-bit hash for strings // of any length representable in ssize_t. Based on City and Murmur128. static uint128 CityMurmur(const char *s, size_t len, uint128 seed) { uint64 a = Uint128Low64(seed); uint64 b = Uint128High64(seed); uint64 c = 0; uint64 d = 0; ssize_t l = len - 16; if (l <= 0) { // len <= 16 c = b * k1 + HashLen0to16(s, len); d = Rotate(a + (len >= 8 ? LittleEndian::Load64(s) : c), 32); } else { // len > 16 c = HashLen16(LittleEndian::Load64(s + len - 8) + k1, a); d = HashLen16(b + len, c + LittleEndian::Load64(s + len - 16)); a += d; do { a ^= ShiftMix(LittleEndian::Load64(s) * k1) * k1; a *= k1; b ^= a; c ^= ShiftMix(LittleEndian::Load64(s + 8) * k1) * k1; c *= k1; d ^= c; s += 16; l -= 16; } while (l > 0); } a = HashLen16(a, c); b = HashLen16(d, b); return uint128(a ^ b, HashLen16(b, a)); } uint128 CityHash128WithSeed(const char *s, size_t len, uint128 seed) { // TODO(user): As of February 2011, there's a beta of Murmur3 that would // most likely be useful here. E.g., if (len < 900) return Murmur3(...) if (len < 128) { return CityMurmur(s, len, seed); } // We expect len >= 128 to be the common case. Keep 56 bytes of state: // v, w, x, y, and z. pair<uint64, uint64> v, w; uint64 x = Uint128Low64(seed); uint64 y = Uint128High64(seed); uint64 z = len * k1; v.first = Rotate(y ^ k1, 49) * k1 + LittleEndian::Load64(s); v.second = Rotate(v.first, 42) * k1 + LittleEndian::Load64(s + 8); w.first = Rotate(y + z, 35) * k1 + x; w.second = Rotate(x + LittleEndian::Load64(s + 88), 53) * k1; // This is similar to the inner loop of CityHash64(), manually unrolled. do { x = Rotate(x + y + v.first + LittleEndian::Load64(s + 16), 37) * k1; y = Rotate(y + v.second + LittleEndian::Load64(s + 48), 42) * k1; x ^= w.second; y ^= v.first; z = Rotate(z ^ w.first, 33); v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y); std::swap(z, x); s += 64; x = Rotate(x + y + v.first + LittleEndian::Load64(s + 16), 37) * k1; y = Rotate(y + v.second + LittleEndian::Load64(s + 48), 42) * k1; x ^= w.second; y ^= v.first; z = Rotate(z ^ w.first, 33); v = WeakHashLen32WithSeeds(s, v.second * k1, x + w.first); w = WeakHashLen32WithSeeds(s + 32, z + w.second, y); std::swap(z, x); s += 64; len -= 128; } while (PREDICT_TRUE(len >= 128)); y += Rotate(w.first, 37) * k0 + z; x += Rotate(v.first + z, 49) * k0; // If 0 < len < 128, hash up to 4 chunks of 32 bytes each from the end of s. for (size_t tail_done = 0; tail_done < len; ) { tail_done += 32; y = Rotate(y - x, 42) * k0 + v.second; w.first += LittleEndian::Load64(s + len - tail_done + 16); x = Rotate(x, 49) * k0 + w.first; w.first += v.first; v = WeakHashLen32WithSeeds(s + len - tail_done, v.first, v.second); } // At this point our 48 bytes of state should contain more than // enough information for a strong 128-bit hash. We use two // different 48-byte-to-8-byte hashes to get a 16-byte final result. x = HashLen16(x, v.first); y = HashLen16(y, w.first); return uint128(HashLen16(x + v.second, w.second) + y, HashLen16(x + w.second, y + v.second)); } uint128 CityHash128(const char *s, size_t len) { if (len >= 16) { return CityHash128WithSeed(s + 16, len - 16, uint128(LittleEndian::Load64(s) ^ k3, LittleEndian::Load64(s + 8))); } else if (len >= 8) { return CityHash128WithSeed(nullptr, 0, uint128(LittleEndian::Load64(s) ^ (len * k0), LittleEndian::Load64(s + len - 8) ^ k1)); } else { return CityHash128WithSeed(s, len, uint128(k0, k1)); } } } // namespace util_hash
// Copyright (c) 2015-2017 The BitCore Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <vector> #include "prevector.h" #include "serialize.h" #include "streams.h" #include "test/test_bitcore.h" #include "test/test_random.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup) template<unsigned int N, typename T> class prevector_tester { typedef std::vector<T> realtype; realtype real_vector; realtype real_vector_alt; typedef prevector<N, T> pretype; pretype pre_vector; pretype pre_vector_alt; typedef typename pretype::size_type Size; bool passed = true; FastRandomContext rand_cache; template <typename A, typename B> void local_check_equal(A a, B b) { local_check(a == b); } void local_check(bool b) { passed &= b; } void test() { const pretype& const_pre_vector = pre_vector; local_check_equal(real_vector.size(), pre_vector.size()); local_check_equal(real_vector.empty(), pre_vector.empty()); for (Size s = 0; s < real_vector.size(); s++) { local_check(real_vector[s] == pre_vector[s]); local_check(&(pre_vector[s]) == &(pre_vector.begin()[s])); local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s)); local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size())); } // local_check(realtype(pre_vector) == real_vector); local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector); local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector); size_t pos = 0; BOOST_FOREACH(const T& v, pre_vector) { local_check(v == real_vector[pos++]); } BOOST_REVERSE_FOREACH(const T& v, pre_vector) { local_check(v == real_vector[--pos]); } BOOST_FOREACH(const T& v, const_pre_vector) { local_check(v == real_vector[pos++]); } BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) { local_check(v == real_vector[--pos]); } CDataStream ss1(SER_DISK, 0); CDataStream ss2(SER_DISK, 0); ss1 << real_vector; ss2 << pre_vector; local_check_equal(ss1.size(), ss2.size()); for (Size s = 0; s < ss1.size(); s++) { local_check_equal(ss1[s], ss2[s]); } } public: void resize(Size s) { real_vector.resize(s); local_check_equal(real_vector.size(), s); pre_vector.resize(s); local_check_equal(pre_vector.size(), s); test(); } void reserve(Size s) { real_vector.reserve(s); local_check(real_vector.capacity() >= s); pre_vector.reserve(s); local_check(pre_vector.capacity() >= s); test(); } void insert(Size position, const T& value) { real_vector.insert(real_vector.begin() + position, value); pre_vector.insert(pre_vector.begin() + position, value); test(); } void insert(Size position, Size count, const T& value) { real_vector.insert(real_vector.begin() + position, count, value); pre_vector.insert(pre_vector.begin() + position, count, value); test(); } template<typename I> void insert_range(Size position, I first, I last) { real_vector.insert(real_vector.begin() + position, first, last); pre_vector.insert(pre_vector.begin() + position, first, last); test(); } void erase(Size position) { real_vector.erase(real_vector.begin() + position); pre_vector.erase(pre_vector.begin() + position); test(); } void erase(Size first, Size last) { real_vector.erase(real_vector.begin() + first, real_vector.begin() + last); pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last); test(); } void update(Size pos, const T& value) { real_vector[pos] = value; pre_vector[pos] = value; test(); } void push_back(const T& value) { real_vector.push_back(value); pre_vector.push_back(value); test(); } void pop_back() { real_vector.pop_back(); pre_vector.pop_back(); test(); } void clear() { real_vector.clear(); pre_vector.clear(); } void assign(Size n, const T& value) { real_vector.assign(n, value); pre_vector.assign(n, value); } Size size() { return real_vector.size(); } Size capacity() { return pre_vector.capacity(); } void shrink_to_fit() { pre_vector.shrink_to_fit(); test(); } void swap() { real_vector.swap(real_vector_alt); pre_vector.swap(pre_vector_alt); test(); } void move() { real_vector = std::move(real_vector_alt); real_vector_alt.clear(); pre_vector = std::move(pre_vector_alt); pre_vector_alt.clear(); } void copy() { real_vector = real_vector_alt; pre_vector = pre_vector_alt; } ~prevector_tester() { BOOST_CHECK_MESSAGE(passed, "insecure_rand_Rz: " << rand_cache.Rz << ", insecure_rand_Rw: " << rand_cache.Rw); } prevector_tester() { seed_insecure_rand(); rand_cache = insecure_rand_ctx; } }; BOOST_AUTO_TEST_CASE(PrevectorTestInt) { for (int j = 0; j < 64; j++) { prevector_tester<8, int> test; for (int i = 0; i < 2048; i++) { int r = insecure_rand(); if ((r % 4) == 0) { test.insert(insecure_rand() % (test.size() + 1), insecure_rand()); } if (test.size() > 0 && ((r >> 2) % 4) == 1) { test.erase(insecure_rand() % test.size()); } if (((r >> 4) % 8) == 2) { int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_rand() % 5) - 2)); test.resize(new_size); } if (((r >> 7) % 8) == 3) { test.insert(insecure_rand() % (test.size() + 1), 1 + (insecure_rand() % 2), insecure_rand()); } if (((r >> 10) % 8) == 4) { int del = std::min<int>(test.size(), 1 + (insecure_rand() % 2)); int beg = insecure_rand() % (test.size() + 1 - del); test.erase(beg, beg + del); } if (((r >> 13) % 16) == 5) { test.push_back(insecure_rand()); } if (test.size() > 0 && ((r >> 17) % 16) == 6) { test.pop_back(); } if (((r >> 21) % 32) == 7) { int values[4]; int num = 1 + (insecure_rand() % 4); for (int k = 0; k < num; k++) { values[k] = insecure_rand(); } test.insert_range(insecure_rand() % (test.size() + 1), values, values + num); } if (((r >> 26) % 32) == 8) { int del = std::min<int>(test.size(), 1 + (insecure_rand() % 4)); int beg = insecure_rand() % (test.size() + 1 - del); test.erase(beg, beg + del); } r = insecure_rand(); if (r % 32 == 9) { test.reserve(insecure_rand() % 32); } if ((r >> 5) % 64 == 10) { test.shrink_to_fit(); } if (test.size() > 0) { test.update(insecure_rand() % test.size(), insecure_rand()); } if (((r >> 11) % 1024) == 11) { test.clear(); } if (((r >> 21) % 512) == 12) { test.assign(insecure_rand() % 32, insecure_rand()); } if (((r >> 15) % 8) == 3) { test.swap(); } if (((r >> 15) % 16) == 8) { test.copy(); } if (((r >> 15) % 32) == 18) { test.move(); } } } } BOOST_AUTO_TEST_SUITE_END()
/* * UAVCAN data structure definition for libuavcan. * * Autogenerated, do not edit. * * Source file: /Users/bendyer/Projects/ARM/workspace/libuavcan/dsdl/uavcan/equipment/air_data/1028.StaticPressure.uavcan */ #ifndef UAVCAN_EQUIPMENT_AIR_DATA_STATICPRESSURE_HPP_INCLUDED #define UAVCAN_EQUIPMENT_AIR_DATA_STATICPRESSURE_HPP_INCLUDED #include <uavcan/build_config.hpp> #include <uavcan/node/global_data_type_registry.hpp> #include <uavcan/marshal/types.hpp> /******************************* Source text ********************************** # # Static pressure. # float32 static_pressure # Pascal float16 static_pressure_variance # Pascal^2 ******************************************************************************/ /********************* DSDL signature source definition *********************** uavcan.equipment.air_data.StaticPressure saturated float32 static_pressure saturated float16 static_pressure_variance ******************************************************************************/ #undef static_pressure #undef static_pressure_variance namespace uavcan { namespace equipment { namespace air_data { template <int _tmpl> struct UAVCAN_EXPORT StaticPressure_ { typedef const StaticPressure_<_tmpl>& ParameterType; typedef StaticPressure_<_tmpl>& ReferenceType; struct ConstantTypes { }; struct FieldTypes { typedef ::uavcan::FloatSpec< 32, ::uavcan::CastModeSaturate > static_pressure; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > static_pressure_variance; }; enum { MinBitLen = FieldTypes::static_pressure::MinBitLen + FieldTypes::static_pressure_variance::MinBitLen }; enum { MaxBitLen = FieldTypes::static_pressure::MaxBitLen + FieldTypes::static_pressure_variance::MaxBitLen }; // Constants // Fields typename ::uavcan::StorageType< typename FieldTypes::static_pressure >::Type static_pressure; typename ::uavcan::StorageType< typename FieldTypes::static_pressure_variance >::Type static_pressure_variance; StaticPressure_() : static_pressure() , static_pressure_variance() { ::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check #if UAVCAN_DEBUG /* * Cross-checking MaxBitLen provided by the DSDL compiler. * This check shall never be performed in user code because MaxBitLen value * actually depends on the nested types, thus it is not invariant. */ ::uavcan::StaticAssert<48 == MaxBitLen>::check(); #endif } bool operator==(ParameterType rhs) const; bool operator!=(ParameterType rhs) const { return !operator==(rhs); } /** * This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of * floating point fields at any depth. */ bool isClose(ParameterType rhs) const; static int encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); /* * Static type info */ enum { DataTypeKind = ::uavcan::DataTypeKindMessage }; enum { DefaultDataTypeID = 1028 }; static const char* getDataTypeFullName() { return "uavcan.equipment.air_data.StaticPressure"; } static void extendDataTypeSignature(::uavcan::DataTypeSignature& signature) { signature.extend(getDataTypeSignature()); } static ::uavcan::DataTypeSignature getDataTypeSignature(); }; /* * Out of line struct method definitions */ template <int _tmpl> bool StaticPressure_<_tmpl>::operator==(ParameterType rhs) const { return static_pressure == rhs.static_pressure && static_pressure_variance == rhs.static_pressure_variance; } template <int _tmpl> bool StaticPressure_<_tmpl>::isClose(ParameterType rhs) const { return ::uavcan::areClose(static_pressure, rhs.static_pressure) && ::uavcan::areClose(static_pressure_variance, rhs.static_pressure_variance); } template <int _tmpl> int StaticPressure_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::static_pressure::encode(self.static_pressure, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::static_pressure_variance::encode(self.static_pressure_variance, codec, tao_mode); return res; } template <int _tmpl> int StaticPressure_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::static_pressure::decode(self.static_pressure, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::static_pressure_variance::decode(self.static_pressure_variance, codec, tao_mode); return res; } /* * Out of line type method definitions */ template <int _tmpl> ::uavcan::DataTypeSignature StaticPressure_<_tmpl>::getDataTypeSignature() { ::uavcan::DataTypeSignature signature(0xCDC7C43412BDC89AULL); FieldTypes::static_pressure::extendDataTypeSignature(signature); FieldTypes::static_pressure_variance::extendDataTypeSignature(signature); return signature; } /* * Out of line constant definitions */ /* * Final typedef */ typedef StaticPressure_<0> StaticPressure; namespace { const ::uavcan::DefaultDataTypeRegistrator< ::uavcan::equipment::air_data::StaticPressure > _uavcan_gdtr_registrator_StaticPressure; } } // Namespace air_data } // Namespace equipment } // Namespace uavcan /* * YAML streamer specialization */ namespace uavcan { template <> class UAVCAN_EXPORT YamlStreamer< ::uavcan::equipment::air_data::StaticPressure > { public: template <typename Stream> static void stream(Stream& s, ::uavcan::equipment::air_data::StaticPressure::ParameterType obj, const int level); }; template <typename Stream> void YamlStreamer< ::uavcan::equipment::air_data::StaticPressure >::stream(Stream& s, ::uavcan::equipment::air_data::StaticPressure::ParameterType obj, const int level) { (void)s; (void)obj; (void)level; if (level > 0) { s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } } s << "static_pressure: "; YamlStreamer< ::uavcan::equipment::air_data::StaticPressure::FieldTypes::static_pressure >::stream(s, obj.static_pressure, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "static_pressure_variance: "; YamlStreamer< ::uavcan::equipment::air_data::StaticPressure::FieldTypes::static_pressure_variance >::stream(s, obj.static_pressure_variance, level + 1); } } namespace uavcan { namespace equipment { namespace air_data { template <typename Stream> inline Stream& operator<<(Stream& s, ::uavcan::equipment::air_data::StaticPressure::ParameterType obj) { ::uavcan::YamlStreamer< ::uavcan::equipment::air_data::StaticPressure >::stream(s, obj, 0); return s; } } // Namespace air_data } // Namespace equipment } // Namespace uavcan #endif // UAVCAN_EQUIPMENT_AIR_DATA_STATICPRESSURE_HPP_INCLUDED
// // Created by xiaoyong on 2021/1/27. // #include "Video2Mat.h" int main(int argc, char** argvs){ if(argc <= 2) return -1; Logger log; log.Info("Start process."); Video2Mat v2m; v2m.params.file = argvs[1]; v2m.params.folder = argvs[2]; v2m.params.skip = 1; v2m.params.ext = "png"; v2m.params.start = 0; v2m.params.stop = -1; v2m.params.logger = &log; v2m.run(); log.Info("Stop process."); return 0; }
// Boost.Geometry (aka GGL, Generic Geometry Library) // Unit Test // Copyright (c) 2012-2014 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <test_buffer.hpp> static std::string const simplex = "POLYGON ((0 0,1 5,6 1,0 0))"; static std::string const concave_simplex = "POLYGON ((0 0,3 5,3 3,5 3,0 0))"; static std::string const concave_b = "POLYGON((0 10,5 15,6 13,8 11,0 10))"; static std::string const square_simplex = "POLYGON ((0 0,0 1,1 1,1 0,0 0))"; static std::string const spike_simplex = "POLYGON ((0 0,1 5,3 3,5 5,3 3,5 1,0 0))"; static std::string const chained_box = "POLYGON((0 0,0 4,4 4,8 4,12 4,12 0,8 0,4 0,0 0))"; static std::string const join_types = "POLYGON ((0 0,0 4,4 4,2 6,0 8,2 6,4 8,8 4,4 0,0 0))"; // first 4 join types are all different: convex, concave, continue, spike static std::string const donut_simplex = "POLYGON ((0 0,1 9,8 1,0 0),(1 1,4 1,1 4,1 1))"; static std::string const donut_diamond = "POLYGON((15 0,15 15,30 15,30 0,15 0),(26 11,22 14,19 10,23 07,26 11))"; static std::string const letter_L = "POLYGON ((0 0,0 4,1 4,1 1,3 1,3 0,0 0))"; static std::string const indentation = "POLYGON ((0 0,0 5,4 5,4 4,3 3,2 4,2 1,3 2,4 1,4 0,0 0))"; static std::string const funnelgate = "POLYGON((0 0,0 7,7 7,7 0,5 0,5 1,6 6,1 6,2 1,2 0,0 0))"; static std::string const gammagate = "POLYGON((0 0,0 6,9 6,9 0,4 0,4 2,7 2,7 4,2 4,2 0,0 0))"; static std::string const fork_a = "POLYGON((0 0,0 6,9 6,9 0,4 0,4 2,7 2,7 4,6 4,6 5,5 5,5 4,4 4,4 5,3 5,3 4,2 4,2 0,0 0))"; static std::string const fork_b = "POLYGON((0 0,0 8,14 8,14 0,4 0,4 2,13 2,13 4,12 4,12 7,9 7,9 4,7 4,7 7,4 7,4 4,2 4,2 0,0 0))"; static std::string const fork_c = "POLYGON((0 0,0 9,12 9,12 0,4 0,4 4,6 4,6 2,8 2,8 4,10 4,10 7,6 7,6 6,2 6,2 0,0 0))"; static std::string const arrow = "POLYGON ((1 0,1 5,0.5 4.5,2 10,3.5 4.5,3 5,3 0,1 0))"; static std::string const tipped_aitch = "POLYGON ((0 0,0 3,3 3,3 4,0 4,0 7,7 7,7 4,4 4,4 3,7 3,7 0,0 0))"; static std::string const snake = "POLYGON ((0 0,0 3,3 3,3 4,0 4,0 7,8 7,8 4,6 4,6 3,8 3,8 0,7 0,7 2,5 2" ",5 5,7 5,7 6,1 6,1 5,4 5,4 2,1 2,1 1,6 1,6 0,0 0))"; static std::string const church = "POLYGON ((0 0,0 3,2.999 3,3 8,3 0,0 0))"; static std::string const flower = "POLYGON ((1 0,1 10,9 10,9 0,4.99 0,4.99 5.5,4.5 6,5 6.5,5.5 6,5.01 5.5,5.01 0.01,5.25 0.01,5.25 5,6 3,8 5,6 6,8 7,6 9,5 7,4 9,2 7,4 6,2 5,4 3,4.75 5,4.75 0,1 0))"; static std::string const saw = "POLYGON((1 3,1 8,1.5 6,5 8,5.5 6,9 8,9.5 6,13 8,13 3,1 3))"; static std::string const bowl = "POLYGON((1 2,1 7,2 7,3 5,5 4,7 5,8 7,9 7,9 2,1 2))"; // Triangle with segmented sides, closing point at longest side static std::string const triangle = "POLYGON((4 5,5 4,4 4,3 4,3 5,3 6,4 5))"; // Triangle which caused acos in join_round to fail with larger side strategy static std::string const sharp_triangle = "POLYGON((2 0,3 8,4 0,2 0))"; static std::string const right_triangle = "POLYGON((0 1,20 0,0 0,0 1))"; static std::string const degenerate0 = "POLYGON(())"; static std::string const degenerate1 = "POLYGON((5 5))"; static std::string const degenerate2 = "POLYGON((5 5,5 5,5 5,5 5))"; static std::string const degenerate3 = "POLYGON((0 0,0 10,10 10,10 0,0 0),(5 5,5 5,5 5,5 5))"; // Real-life examples static std::string const county1 = "POLYGON((-111.700 41.200 ,-111.681388 41.181739 ,-111.682453 41.181506 ,-111.684052 41.180804 ,-111.685295 41.180538 ,-111.686318 41.180776 ,-111.687517 41.181416 ,-111.688982 41.181520 ,-111.690670 41.181523 ,-111.692135 41.181460 ,-111.693646 41.182034 ,-111.695156 41.182204 ,-111.696489 41.182274 ,-111.697775 41.182075 ,-111.698974 41.181539 ,-111.700485 41.182348 ,-111.701374 41.182955 ,-111.700 41.200))"; //static std::string const invalid_parcel // = "POLYGON((116042.20 464335.07,116056.35 464294.59,116066.41 464264.16,116066.44 464264.09,116060.35 464280.93,116028.89 464268.43,116028.89 464268.44,116024.74 464280.7,116018.91 464296.71,116042.2 464335.07))"; static std::string const parcel1 = "POLYGON((225343.489 585110.376,225319.123 585165.731,225323.497 585167.287,225323.134 585167.157,225313.975 585169.208,225321.828 585172,225332.677 585175.83,225367.032 585186.977,225401.64 585196.671,225422.799 585201.029,225429.784 585202.454,225418.859 585195.112,225423.803 585196.13,225425.389 585196.454,225397.027 585165.48,225363.802 585130.372,225354.086 585120.261,225343.489 585110.376))"; static std::string const parcel2 = "POLYGON((173356.986490154 605912.122380707,173358.457939143 605902.891897507,173358.458257372 605902.889901239,173214.162964795 605901.13020255,173214.162746654 605901.132200038,173213.665 605905.69,173212.712441616 605913.799985923,173356.986490154 605912.122380707))"; static std::string const parcel3 = "POLYGON((120528.56 462115.62,120533.4 462072.1,120533.4 462072.01,120533.39 462071.93,120533.36 462071.86,120533.33 462071.78,120533.28 462071.72,120533.22 462071.66,120533.15 462071.61,120533.08 462071.58,120533 462071.55,120532.92 462071.54,120467.68 462068.66,120468.55 462059.04,120517.39 462062.87,120517.47 462062.87,120517.55 462062.86,120517.62 462062.83,120517.69 462062.79,120517.76 462062.74,120517.81 462062.68,120517.86 462062.62,120517.89 462062.55,120517.92 462062.47,120530.49 461998.63,120530.5 461998.55,120530.49 461998.47,120530.47 461998.39,120530.44 461998.31,120530.4 461998.24,120530.35 461998.18,120530.28 461998.13,120530.21 461998.09,120530.13 461998.06,120482.19 461984.63,120485 461963.14,120528.2 461950.66,120528.28 461950.63,120528.35 461950.59,120528.42 461950.53,120528.47 461950.47,120528.51 461950.4,120528.54 461950.32,120528.56 461950.24,120528.56 461950.15,120528.55 461950.07,120528.53 461949.99,120528.49 461949.92,120528.44 461949.85,120497.49 461915.03,120497.43 461914.98,120497.37 461914.93,120497.3 461914.9,120497.23 461914.88,120497.15 461914.86,120424.61 461910.03,120424.53 461910.03,120424.45 461910.05,120424.37 461910.07,120424.3 461910.11,120424.24 461910.16,120424.18 461910.22,120424.14 461910.29,120424.11 461910.37,120424.09 461910.45,120424.08 461910.53,120424.08 461967.59,120424.08 461967.67,120424.1 461967.75,120424.14 461967.82,120424.18 461967.89,120424.23 461967.95,120424.3 461968,120424.37 461968.04,120424.44 461968.07,120424.52 461968.09,120473.31 461973.83,120469.63 461993.16,120399.48 461986.43,120399.4 461986.43,120399.32 461986.44,120399.25 461986.47,120399.17 461986.5,120399.11 461986.55,120399.05 461986.61,120399.01 461986.67,120398.97 461986.74,120398.95 461986.82,120398.93 461986.9,120394.1 462057.5,120394.1 462057.58,120394.11 462057.66,120394.14 462057.74,120394.18 462057.81,120394.23 462057.87,120394.29 462057.93,120394.35 462057.97,120394.43 462058,120394.5 462058.03,120394.58 462058.03,120458.74 462059.95,120455.16 462072.48,120396.57 462067.68,120396.49 462067.68,120396.4 462067.69,120396.32 462067.72,120396.25 462067.76,120396.18 462067.82,120396.13 462067.88,120396.08 462067.96,120396.05 462068.04,120396.03 462068.12,120392.17 462103.9,120392.16 462103.99,120392.18 462104.07,120392.2 462104.15,120392.24 462104.22,120392.29 462104.29,120392.35 462104.35,120392.42 462104.4,120392.5 462104.43,120392.58 462104.45,120392.66 462104.46,120393.63 462104.46,120393.63 462103.46,120393.22 462103.46,120396.98 462068.71,120455.49 462073.51,120455.57 462073.51,120455.66 462073.49,120455.74 462073.46,120455.81 462073.42,120455.88 462073.37,120455.93 462073.3,120455.98 462073.23,120456.01 462073.15,120459.88 462059.61,120459.89 462059.52,120459.9 462059.44,120459.88 462059.36,120459.86 462059.28,120459.82 462059.21,120459.77 462059.14,120459.72 462059.08,120459.65 462059.04,120459.57 462059,120459.49 462058.98,120459.41 462058.97,120395.13 462057.05,120399.9 461987.48,120469.99 461994.2,120470.07 461994.2,120470.15 461994.19,120470.23 461994.16,120470.3 461994.13,120470.37 461994.08,120470.42 461994.02,120470.47 461993.95,120470.5 461993.88,120470.53 461993.8,120474.4 461973.48,120474.4 461973.4,120474.4 461973.32,120474.38 461973.24,120474.35 461973.16,120474.31 461973.09,120474.25 461973.03,120474.19 461972.98,120474.12 461972.94,120474.04 461972.91,120473.96 461972.9,120425.08 461967.14,120425.08 461911.06,120496.88 461915.85,120527.16 461949.92,120484.4 461962.27,120484.33 461962.3,120484.25 461962.35,120484.19 461962.4,120484.14 461962.46,120484.09 461962.53,120484.06 461962.61,120484.05 461962.69,120481.14 461984.93,120481.14 461985.01,120481.15 461985.09,120481.17 461985.17,120481.2 461985.24,120481.25 461985.31,120481.3 461985.36,120481.36 461985.41,120481.43 461985.45,120481.51 461985.48,120529.42 461998.9,120517.02 462061.84,120468.14 462058,120468.05 462058,120467.97 462058.02,120467.89 462058.05,120467.81 462058.09,120467.75 462058.15,120467.69 462058.22,120467.65 462058.29,120467.62 462058.37,120467.6 462058.46,120466.64 462069.1,120466.63 462069.18,120466.65 462069.26,120466.67 462069.33,120466.71 462069.4,120466.76 462069.47,120466.81 462069.53,120466.88 462069.57,120466.95 462069.61,120467.03 462069.63,120467.11 462069.64,120532.34 462072.52,120527.62 462115.03,120391.73 462106.36,120391.66 462107.36,120528.03 462116.06,120528.12 462116.06,120528.2 462116.04,120528.28 462116.02,120528.35 462115.97,120528.42 462115.92,120528.47 462115.85,120528.51 462115.78,120528.54 462115.7,120528.56 462115.62))"; static std::string const parcel3_bend // of parcel_3 - clipped = "POLYGON((120399.40000152588 461986.43000030518, 120399.47999954224 461986.43000030518, 120403 461986.76769953477, 120403 461987.777217312, 120399.90000152588 461987.47999954224, 120399.72722010587 461990, 120398.71791817161 461990, 120398.93000030518 461986.90000152588, 120398.95000076294 461986.81999969482, 120398.9700012207 461986.74000167847, 120399.00999832153 461986.66999816895, 120399.04999923706 461986.61000061035, 120399.11000061035 461986.54999923706, 120399.16999816895 461986.5, 120399.25 461986.4700012207, 120399.31999969482 461986.43999862671, 120399.40000152588 461986.43000030518))"; // Has concavety static std::string const italy_part1 = "POLYGON ((1660000 5190000 , 1651702.9375 5167014.5, 1650311.34375 5167763.53125, 1643318.59375 5172188.15625, 1642488.03125 5172636.75, 1640818.25 5173802.75, 1640107.03125 5174511.21875, 1638931.9375 5176054.03125, 1638684.5625 5177095.75, 1660000 5190000))"; // Did have a self-intersection for first flat/convex solution static std::string const nl_part1 = "POLYGON ((471871.966884626832325 6683515.683521211147308,470695.876464393688366 6681756.129975977353752,469211.542374156008009 6679924.978601523675025,464542.357652322971262 6674631.078279769048095,463243.59315323777264 6673494.345109832473099,459502.033748187706806 6670774.304660517722368,452204.484529234410729 6666030.372161027044058,439990.287360413349234 6659313.515823394991457,434547.988775020290632 6657783.034025833010674,433867.715366783668287 6657685.311832630075514,433063.65468478546245 6657783.034025833010674,423725.285241116478574 6659758.338574352674186,422581.143514745577704 6660350.880751021206379,422333.791606202081311 6660844.461689073592424,421993.599242338153999 6662622.453031159006059,421993.599242338153999 6663363.130126810632646,422612.090333183819894 6667314.244697011075914,422241.062470370030496 6667759.324870104901493,421096.80942450783914 6668303.522556710988283,408449.802075482031796 6673245.655735924839973,401646.845354124438018 6675273.665065255947411,400842.895991614612285 6675372.844085373915732,400255.351719210040756 6675224.699206517077982,392370.258227849320974 6672455.311684883199632,391968.283546594379004 6672009.975794731639326,391875.554410762328189 6671219.573235900141299,391937.336728153284639 6670527.121663697995245,392122.906319305824582 6669933.841785561293364,392339.311409408226609 6667957.501854715868831,392308.475910458364524 6665733.178529324010015,391937.336728153284639 6665289.631341196596622,387793.802641845482867 6664449.731981083750725,385814.7647345236619 6664202.740090588107705,384268.648326894966885 6664300.5401631873101,382846.319193030707538 6664646.406163938343525,382289.610419573145919 6664943.560305980034173,377186.502322628628463 6668957.888622742146254,376352.608017096004914 6669834.728738470934331,376197.985244384559337 6670428.001423852518201,375548.658654586179182 6676313.056885857135057,375243.086652359867003 6687692.866469252854586,379228.324422756850254 6689778.692146780900657,391782.713955441897269 6694388.125634397380054,393885.427817036863416 6694487.537080916576087,395215.139134563156404 6694091.147844122722745,405171.999669074953999 6689084.665672835893929,414263.128523688821588 6684478.40333267301321,415778.298112876422238 6683439.398042757064104,416396.677884233708028 6683192.009851422160864,419025.042381353967357 6682597.809754087589681,429909.63955213711597 6681508.792763692326844,430497.183824544539675 6681656.873437026515603,440979.806314075656701 6686955.330480101518333,467325.344922157470137 6687797.546342735178769,468129.294284664443694 6687698.216345063410699,468747.785375512961764 6687450.699095219373703,469211.542374156008009 6687054.651439971290529,469489.952420631831046 6686707.835750493220985,471871.966884626832325 6683515.683521211147308))"; // Ticket 10398, fails at next distances ( /10.0 ): // #1: 5,25,84 // #2: 5,13,45,49,60,62,66,73 // #3: 4,8,12,35,45,54 // #4: 6,19,21,23,30,43,45,66,78,91 static std::string const ticket_10398_1 = "POLYGON((897866.5 6272518.7,897882.5 6272519.2,897882.6 6272519,897883.3 6272508.7,897883.5 6272505.5,897855 6272503.5,897852.4 6272505.6,897850.1 6272517.6,897860.8 6272518.5,897866.5 6272518.7))"; static std::string const ticket_10398_2 = "POLYGON((898882.3 6271337.3,898895.7 6271339.9,898898 6271328.3,898881.6 6271325.1,898879.3 6271336.7,898882.3 6271337.3))"; static std::string const ticket_10398_3 = "POLYGON((897558.7 6272055,897552.5 6272054.2,897552.5 6272053.7,897546.1 6272052.7,897545.6 6272057.7,897560.7 6272059.6,897560.9 6272055.3,897558.7 6272055))"; static std::string const ticket_10398_4 = "POLYGON((898563.3 6272366.9,898554.7 6272379.2,898559.7 6272382.3,898561.6 6272379.4,898568.7 6272369.1,898563.8 6272366.2,898563.3 6272366.9))"; static std::string const ticket_10412 = "POLYGON((897747.8 6270564.3,897764.3 6270569.7,897776.5 6270529.5,897768.1 6270527.1,897767.6 6270529.4,897756.3 6270525.8,897745.8 6270522.3,897752 6270502.9,897749.7 6270502,897750.7 6270499.1,897751.8 6270498.6,897752.3 6270499.3,897754.6 6270497.9,897755.8 6270500.2,897766.8 6270494.1,897765.6 6270491.5,897768.3 6270490.5,897770.9 6270491.5,897770.2 6270494.6,897780.1 6270497.5,897781 6270494.6,897786.8 6270496.6,897790.8 6270482.5,897785.3 6270480.7,897785.9 6270478.2,897768.9 6270473.2,897768.1 6270475.8,897766.1 6270475.2,897758.7 6270479.2,897753.2 6270481.8,897751.9 6270479,897746.5 6270481.9,897748 6270484.6,897745.2 6270486.1,897743.9 6270483.3,897741.4 6270484.7,897742.6 6270487.3,897739.4 6270488.9,897738.3 6270486.3,897735.6 6270487.8,897733.1 6270496.8,897731.2 6270502.7,897732.4 6270503.2,897731.5 6270506.1,897730.3 6270505.7,897725.8 6270520.2,897726.8 6270520.7,897726 6270523,897728 6270523.7,897726.3 6270529.6,897742.8 6270534.5,897741.2 6270539.9,897751.4 6270543.4,897750.7 6270546.4,897753.2 6270547.2,897747.8 6270564.3))"; static std::string const ticket_11580 = "POLYGON((14.02 474.96,14.02 494.96,14.022 494.96,14.022 486.24,14.02 474.96))"; // CCW Polygons not working in 1.56 static std::string const mysql_report_2014_10_24 = "POLYGON((0 0, 0 8, 8 8, 8 10, -10 10, -10 0, 0 0))"; static std::string const mysql_report_2014_10_28_1 = "POLYGON((0 0,10 10,0 8,0 0))"; static std::string const mysql_report_2014_10_28_2 = "POLYGON((1 1,10 10,0 8,1 1))"; static std::string const mysql_report_2014_10_28_3 = "POLYGON((2 2,8 2,8 8,2 8,2 2))"; // Polygons having problems with negative distances in 1.57 static std::string const mysql_report_2015_02_17_1 = "POLYGON((0 0,0 10,10 10,10 0,0 0),(4 4,4 6,6 6,6 4,4 4))"; static std::string const mysql_report_2015_02_17_2 = "POLYGON((0 0,0 10,10 10,10 0,0 0))"; static std::string const mysql_report_2015_02_17_3 = "POLYGON((10 10,10 20,20 20,20 10,10 10))"; // Polygons causing assertion failure static std::string const mysql_report_2015_07_05_0 = "POLYGON((0 0,0 30000,30000 20000,25000 0,0 0),(-11 3,4.99294e+306 1.78433e+307,15 -14,-11 3))"; static std::string const mysql_report_2015_07_05_1 = "POLYGON((9192 27876,128 4.5036e+15,-1 5,3 9,9192 27876),(-11 3,4.99294e+306 1.78433e+307,15 -14,-11 3))"; static std::string const mysql_report_2015_07_05_2 = "POLYGON((-15 -15,1.31128e+308 2.47964e+307,-20 -9,-15 -15),(11 -4,1.04858e+06 5.36871e+08,7.03687e+13 -1.15292e+18,-12 17,10284 -21812,11 -4),(-28066 -10001,2.19902e+12 3.35544e+07,8.80784e+306 1.04773e+308,1.42177e+308 1.6141e+308,-28066 -10001))"; static std::string const mysql_report_2015_07_05_3 = "POLYGON((-2.68435e+08 -12,27090 -14130,5.76461e+17 5.49756e+11,-2.68435e+08 -12),(2.68435e+08 65539,1.42845e+308 1.63164e+308,-1 -8,-4 10,2.68435e+08 65539),(13 17,8.79609e+12 -2.2518e+15,1.02101e+308 3.13248e+306,17868 780,5 -4,13 17),(-1 14,1.35905e+308 2.09331e+307,1.37439e+11 -2047,-1 14))"; static std::string const mysql_report_2015_07_05_4 = "POLYGON((2.19902e+12 524287,1.13649e+308 1.36464e+308,-10 -19,2.19902e+12 524287),(1.44115e+17 -1.09951e+12,-14 0,-4347 16243,1.44115e+17 -1.09951e+12))"; static std::string const mysql_report_2015_07_05_5 = "POLYGON((9 3,-8193 8.38861e+06,-2 -4,9 3),(-10 -2,32268 -2557,1.72036e+308 5.67867e+307,4.91634e+307 1.41031e+308,-2.68435e+08 -19,-10 -2),(-5 4,9.50167e+307 1.05883e+308,-422 -25737,-5 4))"; class buffer_custom_side_strategy { public : template < typename Point, typename OutputRange, typename DistanceStrategy > static inline bg::strategy::buffer::result_code apply( Point const& input_p1, Point const& input_p2, bg::strategy::buffer::buffer_side_selector side, DistanceStrategy const& distance, OutputRange& output_range) { // Generate a block along (left or right of) the segment double const dx = bg::get<0>(input_p2) - bg::get<0>(input_p1); double const dy = bg::get<1>(input_p2) - bg::get<1>(input_p1); // For normalization [0,1] (=dot product d.d, sqrt) double const length = bg::math::sqrt(dx * dx + dy * dy); if (bg::math::equals(length, 0)) { return bg::strategy::buffer::result_no_output; } // Generate the perpendicular p, to the left (ccw), and use an adapted distance double const d = 1.1 * distance.apply(input_p1, input_p2, side); double const px = d * -dy / length; double const py = d * dx / length; output_range.resize(2); bg::set<0>(output_range.front(), bg::get<0>(input_p1) + px); bg::set<1>(output_range.front(), bg::get<1>(input_p1) + py); bg::set<0>(output_range.back(), bg::get<0>(input_p2) + px); bg::set<1>(output_range.back(), bg::get<1>(input_p2) + py); return bg::strategy::buffer::result_normal; } }; template <bool Clockwise, typename P> void test_all() { typedef bg::model::polygon<P, Clockwise, true> polygon_type; bg::strategy::buffer::join_miter join_miter(10.0); bg::strategy::buffer::join_round join_round(100); bg::strategy::buffer::join_round join_round_rough(12); bg::strategy::buffer::end_flat end_flat; bg::strategy::buffer::end_round end_round(100); test_one<polygon_type, polygon_type>("simplex", simplex, join_round, end_flat, 47.9408, 1.5); test_one<polygon_type, polygon_type>("simplex", simplex, join_miter, end_flat, 52.8733, 1.5); test_one<polygon_type, polygon_type>("simplex", simplex, join_round, end_flat, 7.04043, -0.5); test_one<polygon_type, polygon_type>("simplex", simplex, join_miter, end_flat, 7.04043, -0.5); test_one<polygon_type, polygon_type>("square_simplex", square_simplex, join_round, end_flat, 14.0639, 1.5); test_one<polygon_type, polygon_type>("square_simplex", square_simplex, join_miter, end_flat, 16.0000, 1.5); test_one<polygon_type, polygon_type>("square_simplex01", square_simplex, join_miter, end_flat, 0.6400, -0.1); test_one<polygon_type, polygon_type>("square_simplex04", square_simplex, join_miter, end_flat, 0.0400, -0.4); test_one<polygon_type, polygon_type>("square_simplex05", square_simplex, join_miter, end_flat, 0.0, -0.5); test_one<polygon_type, polygon_type>("square_simplex06", square_simplex, join_miter, end_flat, 0.0, -0.6); test_one<polygon_type, polygon_type>("concave_simplex", concave_simplex, join_round, end_flat, 14.5616, 0.5); test_one<polygon_type, polygon_type>("concave_simplex", concave_simplex, join_miter, end_flat, 16.3861, 0.5); test_one<polygon_type, polygon_type>("concave_simplex", concave_simplex, join_round, end_flat, 0.777987, -0.5); test_one<polygon_type, polygon_type>("concave_simplex", concave_simplex, join_miter, end_flat, 0.724208, -0.5); test_one<polygon_type, polygon_type>("concave_b10", concave_b, join_miter, end_flat, 836.9106, 10.0); test_one<polygon_type, polygon_type>("concave_b25", concave_b, join_miter, end_flat, 4386.6479, 25.0); test_one<polygon_type, polygon_type>("concave_b50", concave_b, join_miter, end_flat, 16487.2000, 50.0); test_one<polygon_type, polygon_type>("concave_b75", concave_b, join_miter, end_flat, 36318.1506, 75.0); test_one<polygon_type, polygon_type>("concave_b100", concave_b, join_miter, end_flat, 63879.5186, 100.0); test_one<polygon_type, polygon_type>("concave_b10", concave_b, join_round, end_flat, 532.2875, 10.0); test_one<polygon_type, polygon_type>("concave_b25", concave_b, join_round, end_flat, 2482.8329, 25.0); test_one<polygon_type, polygon_type>("concave_b50", concave_b, join_round, end_flat, 8872.9719, 50.0); test_one<polygon_type, polygon_type>("concave_b75", concave_b, join_round, end_flat, 19187.5490, 75.0); test_one<polygon_type, polygon_type>("concave_b100", concave_b, join_round, end_flat, 33426.6139, 100.0); test_one<polygon_type, polygon_type>("concave_b_rough_10", concave_b, join_round_rough, end_flat, 520.312, 10.0); test_one<polygon_type, polygon_type>("concave_b_rough_25", concave_b, join_round_rough, end_flat, 2409.384, 25.0); test_one<polygon_type, polygon_type>("concave_b_rough_50", concave_b, join_round_rough, end_flat, 8586.812, 50.0); test_one<polygon_type, polygon_type>("concave_b_rough_75", concave_b, join_round_rough, end_flat, 18549.018, 75.0); test_one<polygon_type, polygon_type>("concave_b_rough_100", concave_b, join_round_rough, end_flat, 32295.917, 100.0); test_one<polygon_type, polygon_type>("spike_simplex15", spike_simplex, join_round, end_round, 50.3633, 1.5); test_one<polygon_type, polygon_type>("spike_simplex15", spike_simplex, join_miter, end_flat, 51.5509, 1.5); test_one<polygon_type, polygon_type>("spike_simplex30", spike_simplex, join_round, end_round, 100.9199, 3.0); test_one<polygon_type, polygon_type>("spike_simplex30", spike_simplex, join_miter, end_flat, 106.6979, 3.0); test_one<polygon_type, polygon_type>("spike_simplex150", spike_simplex, join_round, end_round, 998.9821, 15.0); test_one<polygon_type, polygon_type>("spike_simplex150", spike_simplex, join_miter, end_flat, 1428.1560, 15.0); test_one<polygon_type, polygon_type>("join_types", join_types, join_round, end_flat, 88.2060, 1.5); test_one<polygon_type, polygon_type>("chained_box", chained_box, join_round, end_flat, 83.1403, 1.0); test_one<polygon_type, polygon_type>("chained_box", chained_box, join_miter, end_flat, 84, 1.0); test_one<polygon_type, polygon_type>("L", letter_L, join_round, end_flat, 13.7314, 0.5); test_one<polygon_type, polygon_type>("L", letter_L, join_miter, end_flat, 14.0, 0.5); test_one<polygon_type, polygon_type>("chained_box", chained_box, join_miter, end_flat, 84, 1.0); test_one<polygon_type, polygon_type>("chained_box", chained_box, join_round, end_flat, 83.1403, 1.0); test_one<polygon_type, polygon_type>("indentation4", indentation, join_miter, end_flat, 25.7741, 0.4); test_one<polygon_type, polygon_type>("indentation4", indentation, join_round, end_flat, 25.5695, 0.4); test_one<polygon_type, polygon_type>("indentation5", indentation, join_miter, end_flat, 28.2426, 0.5); test_one<polygon_type, polygon_type>("indentation5", indentation, join_round, end_flat, 27.9953, 0.5); test_one<polygon_type, polygon_type>("indentation6", indentation, join_miter, end_flat, 30.6712, 0.6); // SQL Server gives 30.34479159164 test_one<polygon_type, polygon_type>("indentation6", indentation, join_round, end_flat, 30.3445, 0.6); test_one<polygon_type, polygon_type>("indentation7", indentation, join_miter, end_flat, 33.0958, 0.7); test_one<polygon_type, polygon_type>("indentation7", indentation, join_round, end_flat, 32.6533, 0.7); test_one<polygon_type, polygon_type>("indentation8", indentation, join_miter, end_flat, 35.5943, 0.8); test_one<polygon_type, polygon_type>("indentation8", indentation, join_round, end_flat, 35.0164, 0.8); test_one<polygon_type, polygon_type>("indentation12", indentation, join_miter, end_flat, 46.3541, 1.2); test_one<polygon_type, polygon_type>("indentation12", indentation, join_round, end_flat, 45.0537, 1.2); // Indentation - deflated test_one<polygon_type, polygon_type>("indentation4", indentation, join_miter, end_flat, 6.991, -0.4); test_one<polygon_type, polygon_type>("indentation4", indentation, join_round, end_flat, 7.255, -0.4); test_one<polygon_type, polygon_type>("indentation8", indentation, join_miter, end_flat, 1.369, -0.8); test_one<polygon_type, polygon_type>("indentation8", indentation, join_round, end_flat, 1.374, -0.8); test_one<polygon_type, polygon_type>("indentation12", indentation, join_miter, end_flat, 0, -1.2); test_one<polygon_type, polygon_type>("indentation12", indentation, join_round, end_flat, 0, -1.2); test_one<polygon_type, polygon_type>("donut_simplex6", donut_simplex, join_miter, end_flat, 53.648, 0.6); test_one<polygon_type, polygon_type>("donut_simplex6", donut_simplex, join_round, end_flat, 52.820, 0.6); test_one<polygon_type, polygon_type>("donut_simplex8", donut_simplex, join_miter, end_flat, 61.132, 0.8); test_one<polygon_type, polygon_type>("donut_simplex8", donut_simplex, join_round, end_flat, 59.6713, 0.8); test_one<polygon_type, polygon_type>("donut_simplex10", donut_simplex, join_miter, end_flat, 68.670, 1.0); test_one<polygon_type, polygon_type>("donut_simplex10", donut_simplex, join_round, end_flat, 66.387, 1.0); test_one<polygon_type, polygon_type>("donut_simplex12", donut_simplex, join_miter, end_flat, 76.605, 1.2); test_one<polygon_type, polygon_type>("donut_simplex12", donut_simplex, join_round, end_flat, 73.3179, 1.2); test_one<polygon_type, polygon_type>("donut_simplex14", donut_simplex, join_miter, end_flat, 84.974, 1.4); test_one<polygon_type, polygon_type>("donut_simplex14", donut_simplex, join_round, end_flat, 80.500, 1.4); test_one<polygon_type, polygon_type>("donut_simplex16", donut_simplex, join_miter, end_flat, 93.777, 1.6); test_one<polygon_type, polygon_type>("donut_simplex16", donut_simplex, join_round, end_flat, 87.933, 1.6); test_one<polygon_type, polygon_type>("donut_simplex3", donut_simplex, join_miter, end_flat, 19.7636, -0.3); test_one<polygon_type, polygon_type>("donut_simplex3", donut_simplex, join_round, end_flat, 19.8861, -0.3); test_one<polygon_type, polygon_type>("donut_simplex6", donut_simplex, join_miter, end_flat, 12.8920, -0.6); test_one<polygon_type, polygon_type>("donut_simplex6", donut_simplex, join_round, end_flat, 12.9157, -0.6); test_one<polygon_type, polygon_type>("donut_diamond1", donut_diamond, join_miter, end_flat, 280.0, 1.0); test_one<polygon_type, polygon_type>("donut_diamond4", donut_diamond, join_miter, end_flat, 529.0, 4.0); test_one<polygon_type, polygon_type>("donut_diamond5", donut_diamond, join_miter, end_flat, 625.0, 5.0); test_one<polygon_type, polygon_type>("donut_diamond6", donut_diamond, join_miter, end_flat, 729.0, 6.0); test_one<polygon_type, polygon_type>("donut_diamond1", donut_diamond, join_miter, end_flat, 122.0417, -1.0); test_one<polygon_type, polygon_type>("donut_diamond2", donut_diamond, join_miter, end_flat, 56.3750, -2.0); test_one<polygon_type, polygon_type>("donut_diamond3", donut_diamond, join_miter, end_flat, 17.7084, -3.0); test_one<polygon_type, polygon_type>("arrow4", arrow, join_miter, end_flat, 28.265, 0.4); test_one<polygon_type, polygon_type>("arrow4", arrow, join_round, end_flat, 27.039, 0.4); test_one<polygon_type, polygon_type>("arrow5", arrow, join_miter, end_flat, 31.500, 0.5); test_one<polygon_type, polygon_type>("arrow5", arrow, join_round, end_flat, 29.621, 0.5); test_one<polygon_type, polygon_type>("arrow6", arrow, join_miter, end_flat, 34.903, 0.6); test_one<polygon_type, polygon_type>("arrow6", arrow, join_round, end_flat, 32.268, 0.6); test_one<polygon_type, polygon_type>("tipped_aitch3", tipped_aitch, join_miter, end_flat, 55.36, 0.3); test_one<polygon_type, polygon_type>("tipped_aitch9", tipped_aitch, join_miter, end_flat, 77.44, 0.9); test_one<polygon_type, polygon_type>("tipped_aitch13", tipped_aitch, join_miter, end_flat, 92.16, 1.3); // SQL Server: 55.205415532967 76.6468846383224 90.642916957136 test_one<polygon_type, polygon_type>("tipped_aitch3", tipped_aitch, join_round, end_flat, 55.2053, 0.3); test_one<polygon_type, polygon_type>("tipped_aitch9", tipped_aitch, join_round, end_flat, 76.6457, 0.9); test_one<polygon_type, polygon_type>("tipped_aitch13", tipped_aitch, join_round, end_flat, 90.641, 1.3); test_one<polygon_type, polygon_type>("snake4", snake, join_miter, end_flat, 64.44, 0.4); test_one<polygon_type, polygon_type>("snake5", snake, join_miter, end_flat, 72, 0.5); test_one<polygon_type, polygon_type>("snake6", snake, join_miter, end_flat, 75.44, 0.6); #if ! defined(BOOST_GEOMETRY_NO_ROBUSTNESS) test_one<polygon_type, polygon_type>("snake16", snake, join_miter, end_flat, 114.24, 1.6); #endif test_one<polygon_type, polygon_type>("funnelgate2", funnelgate, join_miter, end_flat, 120.982, 2); test_one<polygon_type, polygon_type>("funnelgate3", funnelgate, join_miter, end_flat, 13*13, 3); test_one<polygon_type, polygon_type>("funnelgate4", funnelgate, join_miter, end_flat, 15*15, 4); test_one<polygon_type, polygon_type>("gammagate1", gammagate, join_miter, end_flat, 88, 1); test_one<polygon_type, polygon_type>("fork_a1", fork_a, join_miter, end_flat, 88, 1); test_one<polygon_type, polygon_type>("fork_b1", fork_b, join_miter, end_flat, 154, 1); test_one<polygon_type, polygon_type>("fork_c1", fork_c, join_miter, end_flat, 152, 1); test_one<polygon_type, polygon_type>("triangle", triangle, join_miter, end_flat, 14.6569, 1.0); test_one<polygon_type, polygon_type>("degenerate0", degenerate0, join_round, end_round, 0.0, 1.0); test_one<polygon_type, polygon_type>("degenerate1", degenerate1, join_round, end_round, 3.1389, 1.0); test_one<polygon_type, polygon_type>("degenerate2", degenerate2, join_round, end_round, 3.1389, 1.0); test_one<polygon_type, polygon_type>("degenerate3", degenerate3, join_round, end_round, 143.1395, 1.0); test_one<polygon_type, polygon_type>("gammagate2", gammagate, join_miter, end_flat, 130, 2); test_one<polygon_type, polygon_type>("flower1", flower, join_miter, end_flat, 67.614, 0.1); test_one<polygon_type, polygon_type>("flower20", flower, join_miter, end_flat, 74.894, 0.20); test_one<polygon_type, polygon_type>("flower25", flower, join_miter, end_flat, 78.226, 0.25); test_one<polygon_type, polygon_type>("flower30", flower, join_miter, end_flat, 81.492, 0.30); test_one<polygon_type, polygon_type>("flower35", flower, join_miter, end_flat, 84.694, 0.35); test_one<polygon_type, polygon_type>("flower40", flower, join_miter, end_flat, 87.831, 0.40); test_one<polygon_type, polygon_type>("flower45", flower, join_miter, end_flat, 90.902, 0.45); test_one<polygon_type, polygon_type>("flower50", flower, join_miter, end_flat, 93.908, 0.50); test_one<polygon_type, polygon_type>("flower55", flower, join_miter, end_flat, 96.849, 0.55); test_one<polygon_type, polygon_type>("flower60", flower, join_miter, end_flat, 99.724, 0.60); test_one<polygon_type, polygon_type>("flower10", flower, join_round, end_flat, 67.486, 0.10); test_one<polygon_type, polygon_type>("flower20", flower, join_round, end_flat, 74.702, 0.20); test_one<polygon_type, polygon_type>("flower25", flower, join_round, end_flat, 78.071, 0.25); test_one<polygon_type, polygon_type>("flower30", flower, join_round, end_flat, 81.352, 0.30); test_one<polygon_type, polygon_type>("flower35", flower, join_round, end_flat, 84.547, 0.35); test_one<polygon_type, polygon_type>("flower40", flower, join_round, end_flat, 87.665, 0.40); test_one<polygon_type, polygon_type>("flower45", flower, join_round, end_flat, 90.709, 0.45); test_one<polygon_type, polygon_type>("flower50", flower, join_round, end_flat, 93.680, 0.50); test_one<polygon_type, polygon_type>("flower55", flower, join_round, end_flat, 96.580, 0.55); test_one<polygon_type, polygon_type>("flower60", flower, join_round, end_flat, 99.408, 0.60); // Flower - deflated test_one<polygon_type, polygon_type>("flower60", flower, join_round, end_flat, 19.3210, -0.60); // Saw { // SQL Server: // 68.6258859984014 90.2254986930165 112.799509089077 136.392823913949 161.224547934625 187.427508982734 //215.063576036522 244.167935815974 274.764905445676 306.878264367143 340.530496138041 375.720107548269 int const n = 12; double expected_round[n] = { 68.6252, 90.222, 112.792, 136.397, 161.230, 187.435, 215.073, 244.179, 274.779, 306.894, 340.543, 375.734 }; double expected_miter[n] = { 70.7706, 98.804, 132.101, 170.661, 214.484, 263.57, 317.92, 377.532, 442.408, 512.546, 587.948, 668.613 }; for (int i = 1; i <= n; i++) { std::ostringstream out; out << "saw_" << i; test_one<polygon_type, polygon_type>(out.str(), saw, join_round, end_flat, expected_round[i - 1], double(i) / 2.0, -999, true, 0.1); test_one<polygon_type, polygon_type>(out.str(), saw, join_miter, end_flat, expected_miter[i - 1], double(i) / 2.0); } } // Bowl { // SQL Server values - see query below. //1 43.2425133175081 60.0257800296593 78.3497997564532 98.2145746255142 119.620102487345 142.482792724034 //2 166.499856911107 191.763334982583 218.446279387336 246.615018368511 276.300134755606 307.518458532186 int const n = 12; double expected_round[n] = { 43.2423, 60.025, 78.3477, 98.2109, 119.614, 142.487, 166.505, 191.77, 218.455, 246.625, 276.312, 307.532 }; double expected_miter[n] = { 43.4895, 61.014, 80.5726, 102.166, 125.794, 151.374, 178.599, 207.443, 237.904, 270.000, 304.0, 340.000 }; for (int i = 1; i <= n; i++) { std::ostringstream out; out << "bowl_" << i; test_one<polygon_type, polygon_type>(out.str(), bowl, join_round, end_flat, expected_round[i - 1], double(i) / 2.0, -999, true, 0.1); test_one<polygon_type, polygon_type>(out.str(), bowl, join_miter, end_flat, expected_miter[i - 1], double(i) / 2.0); } } { double const small_tolerance = 0.0000001; test_one<polygon_type, polygon_type>("county1", county1, join_round, end_flat, 0.00114092, 0.01, 0.01, true, small_tolerance); test_one<polygon_type, polygon_type>("county1", county1, join_miter, end_flat, 0.00132859, 0.01, 0.01, true, small_tolerance); test_one<polygon_type, polygon_type>("county1", county1, join_round, end_flat, 3.94411299566854723e-05, -0.003, -0.003, true, small_tolerance); test_one<polygon_type, polygon_type>("county1", county1, join_miter, end_flat, 3.94301960113807581e-05, -0.003, -0.003, true, small_tolerance); } test_one<polygon_type, polygon_type>("parcel1_10", parcel1, join_round, end_flat, 7571.405, 10.0); test_one<polygon_type, polygon_type>("parcel1_10", parcel1, join_miter, end_flat, 8207.453, 10.0); test_one<polygon_type, polygon_type>("parcel1_20", parcel1, join_round, end_flat, 11648.111, 20.0); test_one<polygon_type, polygon_type>("parcel1_20", parcel1, join_miter, end_flat, 14184.022, 20.0); test_one<polygon_type, polygon_type>("parcel1_30", parcel1, join_round, end_flat, 16350.488, 30.0); test_one<polygon_type, polygon_type>("parcel1_30", parcel1, join_miter, end_flat, 22417.799, 30.0); test_one<polygon_type, polygon_type>("parcel2_10", parcel2, join_round, end_flat, 5000.867, 10.0); test_one<polygon_type, polygon_type>("parcel2_10", parcel2, join_miter, end_flat, 5091.122, 10.0); test_one<polygon_type, polygon_type>("parcel2_20", parcel2, join_round, end_flat, 9049.673, 20.0); test_one<polygon_type, polygon_type>("parcel2_20", parcel2, join_miter, end_flat, 9410.691, 20.0); test_one<polygon_type, polygon_type>("parcel2_30", parcel2, join_round, end_flat, 13726.528, 30.0); test_one<polygon_type, polygon_type>("parcel2_30", parcel2, join_miter, end_flat, 14535.232, 30.0); test_one<polygon_type, polygon_type>("parcel3_10", parcel3, join_round, end_flat, 19993.007, 10.0); test_one<polygon_type, polygon_type>("parcel3_10", parcel3, join_miter, end_flat, 20024.558, 10.0, 10.0, true, 0.05); // MSVC 14 reports 20024.51456, so we increase the tolerance test_one<polygon_type, polygon_type>("parcel3_20", parcel3, join_round, end_flat, 34505.837, 20.0); test_one<polygon_type, polygon_type>("parcel3_20", parcel3, join_miter, end_flat, 34633.261, 20.0); test_one<polygon_type, polygon_type>("parcel3_30", parcel3, join_round, end_flat, 45262.452, 30.0); test_one<polygon_type, polygon_type>("parcel3_30", parcel3, join_miter, end_flat, 45567.388, 30.0); test_one<polygon_type, polygon_type>("parcel3_bend_5", parcel3_bend, join_round, end_flat, 155.634, 5.0); test_one<polygon_type, polygon_type>("parcel3_bend_10", parcel3_bend, join_round, end_flat, 458.454, 10.0); // These cases differ a bit based on point order, because piece generation is different in one corner. Tolerance is increased test_one<polygon_type, polygon_type>("parcel3_bend_15", parcel3_bend, join_round, end_flat, 918.06, 15.0, 15.0, true, 0.25); test_one<polygon_type, polygon_type>("parcel3_bend_20", parcel3_bend, join_round, end_flat, 1534.64, 20.0, 20.0, true, 0.25); // Parcel - deflated test_one<polygon_type, polygon_type>("parcel1_10", parcel1, join_round, end_flat, 1571.9024, -10.0); test_one<polygon_type, polygon_type>("parcel1_10", parcel1, join_miter, end_flat, 1473.7325, -10.0); test_one<polygon_type, polygon_type>("parcel1_20", parcel1, join_round, end_flat, 209.3579, -20.0); test_one<polygon_type, polygon_type>("parcel1_20", parcel1, join_miter, end_flat, 188.4224, -20.0); #if ! defined(BOOST_GEOMETRY_NO_ROBUSTNESS) test_one<polygon_type, polygon_type>("nl_part1_2", nl_part1, join_round, end_flat, 1848737356.991, -0.2 * 1000.0); test_one<polygon_type, polygon_type>("nl_part1_5", nl_part1, join_round, end_flat, 1775953811.679, -0.5 * 1000.0); #else test_one<polygon_type, polygon_type>("nl_part1_2", nl_part1, join_round, end_flat, 1848737292.653, -0.2 * 1000.0); test_one<polygon_type, polygon_type>("nl_part1_5", nl_part1, join_round, end_flat, 1775953824.799, -0.5 * 1000.0); #endif #if ! defined(BOOST_GEOMETRY_NO_ROBUSTNESS) test_one<polygon_type, polygon_type>("italy_part1_30", italy_part1, join_round, end_flat, 5015638814.956, 30.0 * 1000.0); test_one<polygon_type, polygon_type>("italy_part1_50", italy_part1, join_round, end_flat, 11363180044.822, 50.0 * 1000.0); #else test_one<polygon_type, polygon_type>("italy_part1_30", italy_part1, join_round, end_flat, 5015638827.704, 30.0 * 1000.0); test_one<polygon_type, polygon_type>("italy_part1_50", italy_part1, join_round, end_flat, 11363180033.564, 50.0 * 1000.0); #endif test_one<polygon_type, polygon_type>("italy_part1_60", italy_part1, join_round, end_flat, 15479097108.720, 60.0 * 1000.0); // Tickets test_one<polygon_type, polygon_type>("ticket_10398_1_5", ticket_10398_1, join_miter, end_flat, 494.7192, 0.5, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_1_25", ticket_10398_1, join_miter, end_flat, 697.7798, 2.5, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_1_84", ticket_10398_1, join_miter, end_flat, 1470.8096, 8.4, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_2_45", ticket_10398_2, join_miter, end_flat, 535.4780, 4.5, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_2_62", ticket_10398_2, join_miter, end_flat, 705.2046, 6.2, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_2_73", ticket_10398_2, join_miter, end_flat, 827.3394, 7.3, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_3_12", ticket_10398_3, join_miter, end_flat, 122.9443, 1.2, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_3_35", ticket_10398_3, join_miter, end_flat, 258.2729, 3.5, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_3_54", ticket_10398_3, join_miter, end_flat, 402.0571, 5.4, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_4_30", ticket_10398_4, join_miter, end_flat, 257.9482, 3.0, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_4_66", ticket_10398_4, join_miter, end_flat, 553.0112, 6.6, -999, false); test_one<polygon_type, polygon_type>("ticket_10398_4_91", ticket_10398_4, join_miter, end_flat, 819.1406, 9.1, -999, false); test_one<polygon_type, polygon_type>("ticket_10412", ticket_10412, join_miter, end_flat, 3109.6616, 1.5, -999, false); test_one<polygon_type, polygon_type>("ticket_11580_100", ticket_11580, join_miter, end_flat, 52.0221000, 1.00, -999, false); #ifdef BOOST_GEOMETRY_TEST_INCLUDE_FAILING_TESTS // Larger distance, resulting in only one circle test_one<polygon_type, polygon_type>("ticket_11580_237", ticket_11580, join_miter, end_flat, 999.999, 2.37, -999, false); #endif // Tickets - deflated test_one<polygon_type, polygon_type>("ticket_10398_1_5", ticket_10398_1, join_miter, end_flat, 404.3936, -0.5); test_one<polygon_type, polygon_type>("ticket_10398_1_25", ticket_10398_1, join_miter, end_flat, 246.7329, -2.5); { bg::strategy::buffer::join_round join_round32(32); bg::strategy::buffer::end_round end_round32(32); test_one<polygon_type, polygon_type>("mysql_report_2014_10_24", mysql_report_2014_10_24, join_round32, end_round32, 174.902, 1.0); test_one<polygon_type, polygon_type>("mysql_report_2014_10_28_1", mysql_report_2014_10_28_1, join_round32, end_round32, 75.46, 1.0); test_one<polygon_type, polygon_type>("mysql_report_2014_10_28_2", mysql_report_2014_10_28_2, join_round32, end_round32, 69.117, 1.0); test_one<polygon_type, polygon_type>("mysql_report_2014_10_28_3", mysql_report_2014_10_28_3, join_round32, end_round32, 63.121, 1.0); test_one<polygon_type, polygon_type>("mysql_report_2015_02_17_1_d1", mysql_report_2015_02_17_1, join_round32, end_round32, 48.879, -1); test_one<polygon_type, polygon_type>("mysql_report_2015_02_17_1_d5", mysql_report_2015_02_17_1, join_round32, end_round32, 0, -5); test_one<polygon_type, polygon_type>("mysql_report_2015_02_17_1_d6", mysql_report_2015_02_17_1, join_round32, end_round32, 0, -6); test_one<polygon_type, polygon_type>("mysql_report_2015_02_17_1_d10", mysql_report_2015_02_17_1, join_round32, end_round32, 0, -10); test_one<polygon_type, polygon_type>("mysql_report_2015_02_17_2_d1", mysql_report_2015_02_17_2, join_round32, end_round32, 64, -1); test_one<polygon_type, polygon_type>("mysql_report_2015_02_17_2_d10", mysql_report_2015_02_17_2, join_round32, end_round32, 0, -10); test_one<polygon_type, polygon_type>("mysql_report_2015_02_17_3_d1", mysql_report_2015_02_17_3, join_round32, end_round32, 64, -1); { double high_tolerance = 1.0e+20; test_one<polygon_type, polygon_type>("mysql_report_2015_07_05_0", mysql_report_2015_07_05_0, join_round32, end_round32, 700643542.242915988, 6); test_one<polygon_type, polygon_type>("mysql_report_2015_07_05_1", mysql_report_2015_07_05_1, join_round32, end_round32, 2.07548405999982264e+19, 6); test_one<polygon_type, polygon_type>("mysql_report_2015_07_05_2", mysql_report_2015_07_05_2, join_round32, end_round32, 9.48681585720922691e+23, 549755813889, same_distance, true, high_tolerance); test_one<polygon_type, polygon_type>("mysql_report_2015_07_05_3", mysql_report_2015_07_05_3, join_round32, end_round32, 6.10005339242509925e+22, 49316, same_distance, false, high_tolerance); test_one<polygon_type, polygon_type>("mysql_report_2015_07_05_4", mysql_report_2015_07_05_4, join_round32, end_round32, 4.25405937213774089e+23, 1479986, same_distance, false, high_tolerance); test_one<polygon_type, polygon_type>("mysql_report_2015_07_05_5", mysql_report_2015_07_05_5, join_round32, end_round32, 644489321051.62439, 38141, same_distance, false, 10000.0); } } { using bg::strategy::buffer::join_round; using bg::strategy::buffer::join_miter; bg::strategy::buffer::side_straight side_strategy; bg::strategy::buffer::point_circle point_strategy; typedef bg::strategy::buffer::distance_symmetric < typename bg::coordinate_type<P>::type > distance; test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_j12", sharp_triangle, join_round(12), end_flat, distance(1.0), side_strategy, point_strategy, 29.1604); // Test very various number of points (min is 3) test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_j2", sharp_triangle, join_round(2), end_flat, distance(1.0), side_strategy, point_strategy, 27.2399); test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_j5", sharp_triangle, join_round(5), end_flat, distance(1.0), side_strategy, point_strategy, 28.8563); test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_j36", sharp_triangle, join_round(36), end_flat, distance(1.0), side_strategy, point_strategy, 29.2482); test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_j360", sharp_triangle, join_round(360), end_flat, distance(1.0), side_strategy, point_strategy, 29.2659); // Test with various miter limits test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_m2", sharp_triangle, join_miter(2), end_flat, distance(4.0), side_strategy, point_strategy, 148.500); test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_m3", sharp_triangle, join_miter(3), end_flat, distance(4.0), side_strategy, point_strategy, 164.376); test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_m4", sharp_triangle, join_miter(4), end_flat, distance(4.0), side_strategy, point_strategy, 180.2529); test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_m5", sharp_triangle, join_miter(5), end_flat, distance(4.0), side_strategy, point_strategy, 196.1293); test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_m25", sharp_triangle, join_miter(25), end_flat, distance(4.0), side_strategy, point_strategy, 244.7471); // Right triangles, testing both points around sharp corner as well as points // around right corners in join_round strategy test_with_custom_strategies<polygon_type, polygon_type>("right_triangle_j3", right_triangle, join_round(3), end_flat, distance(1.0), side_strategy, point_strategy, 53.0240); test_with_custom_strategies<polygon_type, polygon_type>("right_triangle_j4", right_triangle, join_round(4), end_flat, distance(1.0), side_strategy, point_strategy, 53.2492); test_with_custom_strategies<polygon_type, polygon_type>("right_triangle_j5", right_triangle, join_round(5), end_flat, distance(1.0), side_strategy, point_strategy, 53.7430); test_with_custom_strategies<polygon_type, polygon_type>("right_triangle_j6", right_triangle, join_round(6), end_flat, distance(1.0), side_strategy, point_strategy, 53.7430); buffer_custom_side_strategy custom_side_strategy; test_with_custom_strategies<polygon_type, polygon_type>("sharp_triangle_custom_side", sharp_triangle, join_round(49), end_flat, distance(1.0), custom_side_strategy, point_strategy, 31.1087); } } template < typename InputPoint, typename OutputPoint, bool InputClockwise, bool OutputClockwise, bool InputClosed, bool OutputClosed > void test_mixed() { typedef bg::model::polygon<InputPoint, InputClockwise, InputClosed> input_polygon_type; typedef bg::model::polygon<OutputPoint, OutputClockwise, OutputClosed> output_polygon_type; bg::strategy::buffer::join_round join_round(12); bg::strategy::buffer::end_flat end_flat; std::ostringstream name; name << "mixed_" << std::boolalpha << InputClockwise << "_" << OutputClockwise << "_" << InputClosed << "_" << OutputClosed; test_one<input_polygon_type, output_polygon_type>(name.str(), simplex, join_round, end_flat, 47.4831, 1.5); } #ifdef HAVE_TTMATH #include <ttmath_stub.hpp> #endif int test_main(int, char* []) { typedef bg::model::point<double, 2, bg::cs::cartesian> dpoint; test_all<true, dpoint>(); test_all<false, dpoint>(); #if ! defined(BOOST_GEOMETRY_TEST_ONLY_ONE_TYPE) test_mixed<dpoint, dpoint, false, false, true, true>(); test_mixed<dpoint, dpoint, false, true, true, true>(); test_mixed<dpoint, dpoint, true, false, true, true>(); test_mixed<dpoint, dpoint, true, true, true, true>(); test_mixed<dpoint, dpoint, false, false, false, true>(); test_mixed<dpoint, dpoint, false, true, false, true>(); test_mixed<dpoint, dpoint, true, false, false, true>(); test_mixed<dpoint, dpoint, true, true, false, true>(); #ifdef HAVE_TTMATH test_all<bg::model::point<tt, 2, bg::cs::cartesian> >(); #endif #endif return 0; }
/** * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include "particle_filter.h" #include <math.h> #include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <random> #include <string> #include <vector> #include <cmath> // #include <list> #include "helper_functions.h" using std::string; using std::vector; using std::normal_distribution; using std::iota; using std::sort; // argsort // https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes template <typename T> vector<size_t> sort_indexes(const vector<T> &v) { // initialize original index locations vector<size_t> idx(v.size()); iota(idx.begin(), idx.end(), 0); // sort indexes based on comparing values in v sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] < v[i2];}); return idx; } double multiv_prob(double sig_x, double sig_y, double x_obs, double y_obs, double mu_x, double mu_y); // calculate multi-variable Guassian probabilities double multiv_prob(double sig_x, double sig_y, double x_obs, double y_obs, double mu_x, double mu_y) { // calculate normalization term double gauss_norm; gauss_norm = 1 / (2 * M_PI * sig_x * sig_y); // calculate exponent double exponent; exponent = (pow(x_obs - mu_x, 2) / (2 * pow(sig_x, 2))) + (pow(y_obs - mu_y, 2) / (2 * pow(sig_y, 2))); // std::cout << "m_pi: " << M_PI << std::endl; // calculate weight using normalization terms and exponent double weight; weight = gauss_norm * exp(-exponent); return weight; } void ParticleFilter::init(double x, double y, double theta, double std[]) { /** * TODO: Set the number of particles. Initialize all particles to * first position (based on estimates of x, y, theta and their uncertainties * from GPS) and all weights to 1. * TODO: Add random Gaussian noise to each particle. * NOTE: Consult particle_filter.h for more information about this method * (and others in this file). */ num_particles = 100; // TODO: Set the number of particles std::default_random_engine gen; // set std of variables double std_x = std[0]; double std_y = std[1]; double std_theta = std[2]; normal_distribution<double> dist_x(x, std_x); normal_distribution<double> dist_y(y, std_y); normal_distribution<double> dist_theta(theta, std_theta); for (int i=0; i<num_particles; i++) { //define particle based on the struct Particle particle_; particle_.id = i; particle_.x = dist_x(gen); particle_.y = dist_y(gen); particle_.theta = dist_theta(gen); particle_.weight = 1; particles.push_back(particle_); } is_initialized = true; vector<double> set_weights(num_particles,0.0); weights = set_weights; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { /** * TODO: Add measurements to each particle and add random Gaussian noise. * NOTE: When adding noise you may find std::normal_distribution * and std::default_random_engine useful. * http://en.cppreference.com/w/cpp/numeric/random/normal_distribution * http://www.cplusplus.com/reference/random/default_random_engine/ */ std::default_random_engine gen; double std_pos_x = std_pos[0]; double std_pose_y = std_pos[1]; double std_pose_theta = std_pos[2]; normal_distribution<double> dist_x(0, std_pos_x); normal_distribution<double> dist_y(0, std_pose_y); normal_distribution<double> dist_theta(0,std_pose_theta); // pay attention to there are two cases: one is without yaw rate, one is with yaw, the motion model is different. for (int i=0; i<particles.size(); i++) { if (fabs(yaw_rate)==0) { particles[i].x += cos(particles[i].theta) * velocity * delta_t + dist_x(gen); particles[i].y += sin(particles[i].theta) * velocity * delta_t + dist_y(gen); particles[i].theta += dist_theta(gen); } else { particles[i].x += velocity/yaw_rate * (sin(particles[i].theta + yaw_rate*delta_t)-sin(particles[i].theta)) + dist_x(gen); particles[i].y += velocity/yaw_rate * (cos(particles[i].theta) - cos(particles[i].theta+yaw_rate*delta_t)) + dist_y(gen); particles[i].theta += yaw_rate*delta_t + dist_theta(gen); } // std::cout << "prediction particle theta: " << particles[i].theta << std::endl; } } void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted, vector<LandmarkObs>& observations) { /** * TODO: Find the predicted measurement that is closest to each * observed measurement and assign the observed measurement to this * particular landmark. * NOTE: this method will NOT be called by the grading code. But you will * probably find it useful to implement this method and use it as a helper * during the updateWeights phase. */ // associate the observation to the landmark within the sensor range for (int i=0; i<observations.size(); i++) { vector<double> dist_vec; vector<size_t> sort_idx; for (int j=0; j<predicted.size(); j++) { dist_vec.push_back(dist(predicted[j].x, predicted[j].y, observations[i].x, observations[i].y)); } sort_idx = sort_indexes(dist_vec); // observations[i].id = predicted[sort_idx[0]].id; observations[i].id = sort_idx[0]; // std::cout << "associated observation landmark id: " << observations[i].id << std::endl; // std::cout << "x_obs: " << observations[i].x; // std::cout << " y_obs: " << observations[i].y << std::endl; // std::cout << "landmark_x: " << predicted[sort_idx[0]].x; // std::cout << "landmark_y: " << predicted[sort_idx[0]].y << std::endl; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const vector<LandmarkObs> &observations, const Map &map_landmarks) { /** * TODO: Update the weights of each particle using a mult-variate Gaussian * distribution. You can read more about this distribution here: * https://en.wikipedia.org/wiki/Multivariate_normal_distribution * NOTE: The observations are given in the VEHICLE'S coordinate system. * Your particles are located according to the MAP'S coordinate system. * You will need to transform between the two systems. Keep in mind that * this transformation requires both rotation AND translation (but no scaling). * The following is a good resource for the theory: * https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm * and the following is a good resource for the actual equation to implement * (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html */ // double whole_weights=0.0; for (int i=0; i<particles.size(); i++) { //transform the observations in vehicle coordinate system to map coordinate system vector<LandmarkObs> transformed_observations; for (int k=0; k<observations.size(); k++) { LandmarkObs transformed_observation; transformed_observation.x = particles[i].x + (cos(particles[i].theta) * observations[k].x) - (sin(particles[i].theta) * observations[k].y); transformed_observation.y = particles[i].y + (sin(particles[i].theta) * observations[k].x) + (cos(particles[i].theta) * observations[k].y); transformed_observation.id = observations[k].id; transformed_observations.push_back(transformed_observation); } //keep the landmarks in the map within the sensor range of the vehicle vector<LandmarkObs> predictions; for (int j=0; j<map_landmarks.landmark_list.size();j++) { double dist_ = dist(particles[i].x,particles[i].y,map_landmarks.landmark_list[j].x_f, map_landmarks.landmark_list[j].y_f); if (dist_ <= sensor_range) { LandmarkObs prediction; prediction.x = map_landmarks.landmark_list[j].x_f; prediction.y = map_landmarks.landmark_list[j].y_f; prediction.id = map_landmarks.landmark_list[j].id_i; predictions.push_back(prediction); // std::cout << "prediction particle dist: " << dist_ << std::endl; } } dataAssociation(predictions, transformed_observations); double final_weight=1.0; vector<int> associations; vector<double> sense_x; vector<double> sense_y; //calculate the weight for each particle for (int k=0; k<transformed_observations.size(); k++) { int predict_idx = int(transformed_observations[k].id); double sig_x = std_landmark[0]; double sig_y = std_landmark[1]; double x_obs = transformed_observations[k].x; double y_obs = transformed_observations[k].y; double mu_x = predictions[predict_idx].x; double mu_y = predictions[predict_idx].y; // double mu_x = map_landmarks.landmark_list[land_idx].x_f; // double mu_y = map_landmarks.landmark_list[land_idx].y_f; double weight_; // particles[i].associations.push_back(predictions[predict_idx].id); // particles[i].sense_x.push_back(x_obs); // particles[i].sense_y.push_back(y_obs); associations.push_back(predictions[predict_idx].id); sense_x.push_back(x_obs); sense_y.push_back(y_obs); // std::cout << "x_obs: " << x_obs; // std::cout << " y_obs: " << x_obs << std::endl; // std::cout << "mu_x: " << mu_x; // std::cout << " mu_y: " << mu_y << std::endl; // std::cout << "multi prob: " << multiv_prob(sig_x, sig_y, x_obs, y_obs, mu_x, mu_y) << std::endl; weight_ = multiv_prob(sig_x, sig_y, x_obs, y_obs, mu_x, mu_y); if (weight_>0) { final_weight *= weight_; } // std::cout << "final_weight: " << final_weight << std::endl; } particles[i].weight = final_weight; weights[i] = particles[i].weight; // whole_weights += particles[i].weight; // for visualization in the output video SetAssociations(particles[i], associations, sense_x, sense_y); } // for (int i=0; i<particles.size(); i++) { // particles[i].weight = particles[i].weight/whole_weights; // weights[i] = particles[i].weight/whole_weights; // } } void ParticleFilter::resample() { /** * TODO: Resample particles with replacement with probability proportional * to their weight. * NOTE: You may find std::discrete_distribution helpful here. * http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution */ std::default_random_engine gen; vector<Particle> resample_particles; std::discrete_distribution<int> resample_dist(weights.begin(), weights.end()); for (int i=0; i<particles.size(); i++) { int idx = resample_dist(gen); resample_particles.push_back(particles[idx]); } particles = resample_particles; } void ParticleFilter::SetAssociations(Particle& particle, const vector<int>& associations, const vector<double>& sense_x, const vector<double>& sense_y) { // particle: the particle to which assign each listed association, // and association's (x,y) world coordinates mapping // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseCoord(Particle best, string coord) { vector<double> v; if (coord == "X") { v = best.sense_x; } else { v = best.sense_y; } std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/oak/oak_tree_model.h" #include "base/utf_string_conversions.h" #include "ui/aura/root_window.h" #include "ui/aura/window.h" #include "ui/base/models/tree_node_model.h" namespace oak { namespace internal { string16 GetNodeTitleForWindow(aura::Window* window) { std::string window_name = window->name(); if (window_name.empty()) window_name.append("Unnamed window"); return ASCIIToUTF16(window_name); } void AddChildWindows(aura::Window* parent_window, WindowNode* parent_node) { aura::Window::Windows::const_iterator it = parent_window->children().begin(); for (; it != parent_window->children().end(); ++it) { WindowNode* child_node = new WindowNode(GetNodeTitleForWindow(*it), *it); parent_node->Add(child_node, parent_node->child_count()); AddChildWindows(*it, child_node); } } TreeOfWindows* GenerateModel(aura::Window* root) { WindowNode* root_node = new WindowNode(GetNodeTitleForWindow(root), root); TreeOfWindows* tree = new TreeOfWindows(root_node); AddChildWindows(root, root_node); return tree; } } // namespace internal } // namespace oak
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. 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. ==============================================================================*/ #include "tensorflow/core/distributed_runtime/base_rendezvous_mgr.h" #include <unordered_set> #include <vector> #include "tensorflow/core/common_runtime/copy_tensor.h" #include "tensorflow/core/common_runtime/device.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/common_runtime/dma_helper.h" #include "tensorflow/core/common_runtime/process_util.h" #include "tensorflow/core/distributed_runtime/worker_cache.h" #include "tensorflow/core/distributed_runtime/worker_interface.h" #include "tensorflow/core/framework/cancellation.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { static void StartAbortRendevous(Rendezvous* rendez, const Status& s) { rendez->StartAbort(s); rendez->Unref(); } BaseRendezvousMgr::BaseRendezvousMgr(const WorkerEnv* worker_env) : worker_env_(worker_env) {} BaseRendezvousMgr::~BaseRendezvousMgr() { for (auto& p : table_) { auto rendez = p.second; StartAbortRendevous(rendez, errors::Aborted("Shutdown")); } } RemoteRendezvous* BaseRendezvousMgr::Find(int64 step_id) { return FindOrCreate(step_id); } BaseRemoteRendezvous* BaseRendezvousMgr::FindOrCreate(int64 step_id) { mutex_lock l(mu_); auto iter = table_.find(step_id); if (iter == table_.end()) { auto rr = Create(step_id, worker_env_); iter = table_.insert({step_id, rr}).first; } iter->second->Ref(); return iter->second; } void BaseRendezvousMgr::RecvLocalAsync(int64 step_id, const Rendezvous::ParsedKey& parsed, Rendezvous::DoneCallback done) { auto rendez = FindOrCreate(step_id); auto done_cb = [rendez, done = std::move(done)]( const Status& s, const Rendezvous::Args& send_args, const Rendezvous::Args& recv_args, const Tensor& v, bool dead) { rendez->Unref(); done(s, send_args, recv_args, v, dead); }; rendez->RecvLocalAsync(parsed, std::move(done_cb)); } Status BaseRendezvousMgr::RecvLocal(int64 step_id, const Rendezvous::ParsedKey& parsed, Tensor* val, bool* is_dead) { Status ret; Notification n; RecvLocalAsync(step_id, parsed, [val, is_dead, &ret, &n](const Status& s, const Rendezvous::Args& send_args, const Rendezvous::Args& recv_args, const Tensor& v, const bool dead) { ret = s; *val = v; *is_dead = dead; n.Notify(); }); n.WaitForNotification(); return ret; } void BaseRendezvousMgr::Cleanup(int64 step_id) { Rendezvous* rendez = nullptr; { mutex_lock l(mu_); auto iter = table_.find(step_id); if (iter != table_.end()) { rendez = iter->second; table_.erase(iter); } } if (rendez) { StartAbortRendevous(rendez, errors::Aborted("Cleanup ", step_id)); } } void BaseRendezvousMgr::CleanupAll() { std::vector<Rendezvous*> rendezs; { mutex_lock l(mu_); for (const auto& entry : table_) { rendezs.push_back(entry.second); } table_.clear(); } for (auto rendez : rendezs) { StartAbortRendevous(rendez, errors::Aborted("Shutdown")); } } BaseRemoteRendezvous::BaseRemoteRendezvous(const WorkerEnv* env, int64 step_id) : env_(env), step_id_(step_id), local_(NewLocalRendezvous()), session_(nullptr) {} BaseRemoteRendezvous::~BaseRemoteRendezvous() { CHECK(active_.empty()); local_->Unref(); } // Returns true if "device_name" is a valid full name of local device // of the "worker". This helper is purely based on the worker name // and device name and does no lookups in the worker->device_mgr. static bool IsLocalDevice(const StringPiece worker_name, const StringPiece device_name) { return absl::StartsWith(device_name, worker_name); } Status BaseRemoteRendezvous::Initialize(WorkerSession* session) { CHECK_NE(session, nullptr) << "session must not be null!"; std::vector<DeferredCall> deferred_calls; { mutex_lock l(init_mu_); if (session_ != nullptr) { if (session_->worker_name() == session->worker_name()) { VLOG(1) << "Skipping rendezvous re-initialization."; return Status::OK(); } Status s = errors::Internal( "Double init! Worker names would have changed from: ", session_->worker_name(), " -> ", session->worker_name()); LOG(WARNING) << s; return s; } session_ = session; std::swap(deferred_calls, deferred_calls_); } for (auto& call : deferred_calls) { RecvLocalAsyncInternal(call.parsed, std::move(call.done)); } return Status::OK(); } WorkerSession* BaseRemoteRendezvous::session() { tf_shared_lock l(init_mu_); return session_; } bool BaseRemoteRendezvous::is_initialized() { tf_shared_lock l(init_mu_); return is_initialized_locked(); } Status BaseRemoteRendezvous::Send(const Rendezvous::ParsedKey& parsed, const Rendezvous::Args& args, const Tensor& val, const bool is_dead) { VLOG(1) << "BaseRemoteRendezvous Send " << this << " " << parsed.FullKey(); WorkerSession* sess = nullptr; { tf_shared_lock l(init_mu_); if (!status_.ok()) return status_; DCHECK(is_initialized_locked()); sess = session_; } if (!IsLocalDevice(sess->worker_name(), parsed.src_device)) { return errors::InvalidArgument( "Invalid rendezvous key (src): ", parsed.FullKey(), " @ ", sess->worker_name()); } // Buffers "val" and "device_context" in local_. return local_->Send(parsed, args, val, is_dead); } Status BaseRemoteRendezvous::ValidateDevices(const ParsedKey& parsed, bool is_src) { // Cache session pointer to avoid repeatedly taking & releasing the lock // (e.g. calling session()) WorkerSession* sess = nullptr; { tf_shared_lock l(init_mu_); if (!status_.ok()) return status_; if (!is_initialized_locked()) { return errors::Internal("ValidateDevices called before initialization."); } sess = session_; } if (is_src && !IsLocalDevice(sess->worker_name(), parsed.src_device)) { return errors::InvalidArgument( "Invalid rendezvous key (src): ", parsed.FullKey(), " @ ", sess->worker_name()); } if (!is_src && !IsLocalDevice(sess->worker_name(), parsed.dst_device)) { return errors::InvalidArgument( "Invalid rendezvous key (dst): ", parsed.FullKey(), " @ ", sess->worker_name()); } return Status::OK(); } void BaseRemoteRendezvous::SameWorkerRecvDone( const Rendezvous::ParsedKey& parsed, const Rendezvous::Args& send_args, const Rendezvous::Args& recv_args, const Tensor& in, Tensor* out, StatusCallback done) { // Do a quick copy (sharing the underlying buffer) if both tensors // are on host memory. const bool src_host = (send_args.alloc_attrs.on_host() || parsed.src.type == "CPU"); const bool dst_host = (recv_args.alloc_attrs.on_host() || parsed.dst.type == "CPU"); if (src_host && dst_host) { *out = in; done(Status::OK()); return; } // This copy must involve a GPU. Hence, "in" must support DMA // (e.g., string tensors do not work on GPU). Variant copy DMA // checks happen inside CopyTensor::ViaDMA. if (!DMAHelper::CanUseDMA(&in) && in.dtype() != DT_VARIANT && in.dtype() != DT_RESOURCE) { done(errors::InvalidArgument( "Non-DMA-safe ", DataTypeString(in.dtype()), " tensor may not be copied from/to a device. Key: ", parsed.FullKey())); return; } WorkerSession* sess = session(); Device* src_device; Status s = sess->device_mgr()->LookupDevice(parsed.src_device, &src_device); if (!s.ok()) { done(s); return; } Device* dst_device; s = sess->device_mgr()->LookupDevice(parsed.dst_device, &dst_device); if (!s.ok()) { done(s); return; } ScopedMemoryDebugAnnotation op_annotation("SameWorkerRecvDone", step_id_, "dynamic", in.dtype(), &in.shape()); AllocatorAttributes attr = recv_args.alloc_attrs; attr.set_gpu_compatible(send_args.alloc_attrs.gpu_compatible() || recv_args.alloc_attrs.gpu_compatible()); Allocator* out_allocator = dst_device->GetAllocator(attr); AllocationAttributes allocation_attr; uint64 safe_alloc_frontier = dst_device->SafeAllocFrontier(0); bool sync_dst_compute = (safe_alloc_frontier == 0); std::function<uint64()> freed_by_func = [dst_device, &safe_alloc_frontier]() { safe_alloc_frontier = dst_device->SafeAllocFrontier(safe_alloc_frontier); return safe_alloc_frontier; }; if (!sync_dst_compute) { allocation_attr.freed_by_func = &freed_by_func; } if (in.dtype() != DT_VARIANT) { // Variants are handled by CopyTensor::ViaDMA. Tensor copy(out_allocator, in.dtype(), in.shape(), allocation_attr); *out = copy; } // The following function takes care of cpu->gpu, gpu->cpu, gpu->gpu copies, // etc. CopyTensor::ViaDMA( parsed.edge_name, send_args.device_context, recv_args.device_context, src_device, dst_device, send_args.alloc_attrs, recv_args.alloc_attrs, &in, out, 0 /*dev_to_dev_stream_index*/, std::move(done), sync_dst_compute); } bool BaseRemoteRendezvous::IsSameWorker(DeviceNameUtils::ParsedName src, DeviceNameUtils::ParsedName dst) { return DeviceNameUtils::IsSameAddressSpace(src, dst); } void BaseRemoteRendezvous::RecvAsync(const ParsedKey& parsed, const Rendezvous::Args& recv_args, DoneCallback done) { VLOG(1) << "RemoteRendezvous Recv " << this << " " << parsed.FullKey(); Status s = ValidateDevices(parsed, false /*!is_src*/); if (!s.ok()) { done(s, Args(), recv_args, Tensor(), false); return; } // ValidateDevices() returns an error status if the rendezvous is not // initialized. DCHECK(is_initialized()) << "RecvAsync called when uninitialized (key: " << parsed.FullKey() << ")."; ScopedMemoryDebugAnnotation op_annotation("RecvAsync", step_id_); // Are src and dst in the same worker? if (IsSameWorker(parsed.src, parsed.dst)) { // Recv the tensor from local_. local_->RecvAsync( parsed, recv_args, [this, parsed, done]( const Status& status, const Rendezvous::Args& send_args, const Rendezvous::Args& recv_args, const Tensor& in, bool is_dead) { VLOG(2) << "RemoteRendezvous Finished Recv " << this << " " << parsed.FullKey(); Tensor* out = new Tensor; StatusCallback final_callback = [done, send_args, recv_args, out, is_dead](const Status& s) { done(s, send_args, recv_args, *out, is_dead); delete out; }; if (status.ok()) { SameWorkerRecvDone(parsed, send_args, recv_args, in, out, std::move(final_callback)); } else { final_callback(status); } }); return; } else { RecvFromRemoteAsync(parsed, recv_args, std::move(done)); } } void BaseRemoteRendezvous::RecvLocalAsync(const ParsedKey& parsed, DoneCallback done) { // Test whether the rendezvous is initialized using a shared lock, to avoid // the need for exclusive access in the common case. if (TF_PREDICT_FALSE(!is_initialized())) { mutex_lock l(init_mu_); if (!is_initialized_locked()) { // RecvLocalAsync can be called (due to an incoming RecvTensor RPC from a // remote worker) before the RunStep (or PartialRunStep) RPC from the // master arrives. RecvLocalAsync thus buffers the arguments until after // the RemoteRendezvous is Initialize()'d, when it completes the // rendezvous logic. At some point after Initialize() is called, a Tensor // is produced locally that will then be sent in response to the incoming // RPC. DeferredCall call(parsed, std::move(done)); deferred_calls_.push_back(call); return; } } RecvLocalAsyncInternal(parsed, std::move(done)); } void BaseRemoteRendezvous::RecvLocalAsyncInternal(const ParsedKey& parsed, DoneCallback done) { Status s = ValidateDevices(parsed, true /* is_src */); if (!s.ok()) { done(s, Args(), Args(), Tensor(), false); return; } local_->RecvAsync(parsed, Args(), std::move(done)); } void BaseRemoteRendezvous::StartAbort(const Status& s) { CHECK(!s.ok()); // Use a "derived" status as the status for the rendezvous. Derived // status messages are ignored when aggregating errors across devices: this // allows us to prefer our original status message over any cancellation // related errors. Status derived_status = StatusGroup::MakeDerived(s); local_->StartAbort(derived_status); { // Aborts all active RecvTensor calls. mutex_lock l(init_mu_); mutex_lock l2(active_mu_); if (status_.ok()) { status_ = derived_status; for (auto& entry : active_) { entry.first->StartAbort(derived_status); entry.second(); } active_.clear(); } } } void BaseRemoteRendezvous::RegisterCall(BaseRecvTensorCall* call, const Rendezvous::Args& args) { CancellationManager* cm = args.cancellation_manager; Status captured_status; { tf_shared_lock l(init_mu_); if (!status_.ok()) { captured_status = status_; } } if (!captured_status.ok()) { call->StartAbort(captured_status); return; } bool already_cancelled = false; InactiveCallback callback = [] {}; if (cm != nullptr) { auto token = cm->get_cancellation_token(); already_cancelled = !cm->RegisterCallback(token, [this, call] { { tf_shared_lock l(active_mu_); if (active_.find(call) == active_.end()) return; } call->StartAbort(errors::Cancelled("RecvFromRemoteAsync is cancelled.")); }); callback = [cm, token] { cm->TryDeregisterCallback(token); }; } if (already_cancelled) { call->StartAbort(errors::Cancelled("RecvFromRemoteAsync is cancelled.")); } else { mutex_lock l(active_mu_); CHECK(active_.emplace(call, callback).second); } } void BaseRemoteRendezvous::DeregisterCall(BaseRecvTensorCall* call) { mutex_lock l(active_mu_); auto it = active_.find(call); if (it != active_.end()) { // Deregister the cancellation callback, if one was registered. it->second(); active_.erase(it); } } BaseRemoteRendezvous::DeferredCall::DeferredCall(const ParsedKey& parsed, DoneCallback done) : parsed(parsed), done(std::move(done)) {} } // end namespace tensorflow
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The polis Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "base58.h" #include "chain.h" #include "core_io.h" #include "init.h" #include "instantx.h" #include "net.h" #include "policy/rbf.h" #include "rpc/server.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" #include "validation.h" #include "wallet.h" #include "walletdb.h" #include "keepass.h" #include <stdint.h> #include <boost/assign/list_of.hpp> #include <univalue.h> using namespace std; int64_t nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; std::string HelpRequiringPassphrase() { return pwalletMain && pwalletMain->IsCrypted() ? "\nRequires wallet passphrase to be set with walletpassphrase call." : ""; } bool EnsureWalletIsAvailable(bool avoidException) { if (!pwalletMain) { if (!avoidException) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); else return false; } return true; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); } void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry) { int confirms = wtx.GetDepthInMainChain(false); bool fLocked = instantsend.IsLockedInstantSendTransaction(wtx.GetHash()); entry.push_back(Pair("confirmations", confirms)); entry.push_back(Pair("instantlock", fLocked)); if (wtx.IsCoinBase()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime())); } else { entry.push_back(Pair("trusted", wtx.IsTrusted())); } uint256 hash = wtx.GetHash(); entry.push_back(Pair("txid", hash.GetHex())); UniValue conflicts(UniValue::VARR); BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts()) conflicts.push_back(conflict.GetHex()); entry.push_back(Pair("walletconflicts", conflicts)); entry.push_back(Pair("time", wtx.GetTxTime())); entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived)); // Add opt-in RBF status std::string rbfStatus = "no"; if (confirms <= 0) { LOCK(mempool.cs); if (!mempool.exists(hash)) { if (SignalsOptInRBF(wtx)) { rbfStatus = "yes"; } else { rbfStatus = "unknown"; } } else if (IsRBFOptIn(*mempool.mapTx.find(hash), mempool)) { rbfStatus = "yes"; } } entry.push_back(Pair("bip125-replaceable", rbfStatus)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const UniValue& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } UniValue getnewaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress ( \"account\" )\n" "\nReturns a new polis address for receiving payments.\n" "If 'account' is specified (DEPRECATED), it is added to the address book \n" "so payments received with the address will be credited to 'account'.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The account name for the address to be linked to. If not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n" "\nResult:\n" "\"polisaddress\" (string) The new polis address\n" "\nExamples:\n" + HelpExampleCli("getnewaddress", "") + HelpExampleRpc("getnewaddress", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked(true)) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBook(keyID, strAccount, "receive"); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive"); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } UniValue getaccountaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress \"account\"\n" "\nDEPRECATED. Returns the current polis address for receiving payments to this account.\n" "\nArguments:\n" "1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n" "\nResult:\n" "\"polisaddress\" (string) The account polis address\n" "\nExamples:\n" + HelpExampleCli("getaccountaddress", "") + HelpExampleCli("getaccountaddress", "\"\"") + HelpExampleCli("getaccountaddress", "\"myaccount\"") + HelpExampleRpc("getaccountaddress", "\"myaccount\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); UniValue ret(UniValue::VSTR); ret = GetAccountAddress(strAccount).ToString(); return ret; } UniValue getrawchangeaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 1) throw runtime_error( "getrawchangeaddress\n" "\nReturns a new polis address, for receiving change.\n" "This is for use with raw transactions, NOT normal use.\n" "\nResult:\n" "\"address\" (string) The address\n" "\nExamples:\n" + HelpExampleCli("getrawchangeaddress", "") + HelpExampleRpc("getrawchangeaddress", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (!pwalletMain->IsLocked(true)) pwalletMain->TopUpKeyPool(); CReserveKey reservekey(pwalletMain); CPubKey vchPubKey; if (!reservekey.GetReservedKey(vchPubKey, true)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); reservekey.KeepKey(); CKeyID keyID = vchPubKey.GetID(); return CBitcoinAddress(keyID).ToString(); } UniValue setaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount \"polisaddress\" \"account\"\n" "\nDEPRECATED. Sets the account associated with the given address.\n" "\nArguments:\n" "1. \"polisaddress\" (string, required) The polis address to be associated with an account.\n" "2. \"account\" (string, required) The account to assign the address to.\n" "\nExamples:\n" + HelpExampleCli("setaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"tabby\"") + HelpExampleRpc("setaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", \"tabby\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid polis address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Only add the account if the address is yours. if (IsMine(*pwalletMain, address.Get())) { // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBook(address.Get(), strAccount, "receive"); } else throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address"); return NullUniValue; } UniValue getaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "getaccount \"polisaddress\"\n" "\nDEPRECATED. Returns the account associated with the given address.\n" "\nArguments:\n" "1. \"polisaddress\" (string, required) The polis address for account lookup.\n" "\nResult:\n" "\"accountname\" (string) the account address\n" "\nExamples:\n" + HelpExampleCli("getaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") + HelpExampleRpc("getaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid polis address"); string strAccount; map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty()) strAccount = (*mi).second.name; return strAccount; } UniValue getaddressesbyaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount \"account\"\n" "\nDEPRECATED. Returns the list of addresses for the given account.\n" "\nArguments:\n" "1. \"account\" (string, required) The account name.\n" "\nResult:\n" "[ (json array of string)\n" " \"polisaddress\" (string) a polis address associated with the given account\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getaddressesbyaccount", "\"tabby\"") + HelpExampleRpc("getaddressesbyaccount", "\"tabby\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account UniValue ret(UniValue::VARR); BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second.name; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } static void SendMoney(const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew, bool fUseInstantSend=false, bool fUsePrivateSend=false) { CAmount curBalance = pwalletMain->GetBalance(); // Check amount if (nValue <= 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount"); if (nValue > curBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); if (pwalletMain->GetBroadcastTransactions() && !g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); // Parse polis address CScript scriptPubKey = GetScriptForDestination(address); // Create and send the transaction CReserveKey reservekey(pwalletMain); CAmount nFeeRequired; std::string strError; vector<CRecipient> vecSend; int nChangePosRet = -1; CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount}; vecSend.push_back(recipient); if (!pwalletMain->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet, strError, NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend)) { if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance()) strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired)); throw JSONRPCError(RPC_WALLET_ERROR, strError); } if (!pwalletMain->CommitTransaction(wtxNew, reservekey, g_connman.get(), fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); } UniValue sendtoaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 7) throw runtime_error( "sendtoaddress \"polisaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount use_is use_ps )\n" "\nSend an amount to a given address.\n" + HelpRequiringPassphrase() + "\nArguments:\n" "1. \"polisaddress\" (string, required) The polis address to send to.\n" "2. \"amount\" (numeric or string, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n" "3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the \n" " transaction, just kept in your wallet.\n" "5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n" " The recipient will receive less amount of polis than you enter in the amount field.\n" "6. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n" "7. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n" "\nResult:\n" "\"transactionid\" (string) The transaction id.\n" "\nExamples:\n" + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1") + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"\" \"\" true") + HelpExampleRpc("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.1, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid polis address"); // Amount CAmount nAmount = AmountFromValue(params[1]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); // Wallet comments CWalletTx wtx; if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); bool fSubtractFeeFromAmount = false; if (params.size() > 4) fSubtractFeeFromAmount = params[4].get_bool(); bool fUseInstantSend = false; bool fUsePrivateSend = false; if (params.size() > 5) fUseInstantSend = params[5].get_bool(); if (params.size() > 6) fUsePrivateSend = params[6].get_bool(); EnsureWalletIsUnlocked(); SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, fUseInstantSend, fUsePrivateSend); return wtx.GetHash().GetHex(); } UniValue instantsendtoaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 5) throw runtime_error( "instantsendtoaddress \"polisaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount )\n" "\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" + HelpRequiringPassphrase() + "\nArguments:\n" "1. \"polisaddress\" (string, required) The polis address to send to.\n" "2. \"amount\" (numeric, required) The amount in btc to send. eg 0.1\n" "3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the \n" " transaction, just kept in your wallet.\n" "5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n" " The recipient will receive less amount of polis than you enter in the amount field.\n" "\nResult:\n" "\"transactionid\" (string) The transaction id.\n" "\nExamples:\n" + HelpExampleCli("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1") + HelpExampleCli("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleCli("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"\" \"\" true") + HelpExampleRpc("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.1, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid polis address"); // Amount CAmount nAmount = AmountFromValue(params[1]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); // Wallet comments CWalletTx wtx; if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); bool fSubtractFeeFromAmount = false; if (params.size() > 4) fSubtractFeeFromAmount = params[4].get_bool(); EnsureWalletIsUnlocked(); SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, true); return wtx.GetHash().GetHex(); } UniValue listaddressgroupings(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp) throw runtime_error( "listaddressgroupings\n" "\nLists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions\n" "\nResult:\n" "[\n" " [\n" " [\n" " \"polisaddress\", (string) The polis address\n" " amount, (numeric) The amount in " + CURRENCY_UNIT + "\n" " \"account\" (string, optional) The account (DEPRECATED)\n" " ]\n" " ,...\n" " ]\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listaddressgroupings", "") + HelpExampleRpc("listaddressgroupings", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); UniValue jsonGroupings(UniValue::VARR); map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { UniValue jsonGrouping(UniValue::VARR); BOOST_FOREACH(CTxDestination address, grouping) { UniValue addressInfo(UniValue::VARR); addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } UniValue signmessage(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 2) throw runtime_error( "signmessage \"polisaddress\" \"message\"\n" "\nSign a message with the private key of an address" + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"polisaddress\" (string, required) The polis address to use for the private key.\n" "2. \"message\" (string, required) The message to create a signature of.\n" "\nResult:\n" "\"signature\" (string) The signature of the message encoded in base 64\n" "\nExamples:\n" "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("signmessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", \"my message\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } UniValue getreceivedbyaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "getreceivedbyaddress \"polisaddress\" ( minconf addlockconf )\n" "\nReturns the total amount received by the given polisaddress in transactions with specified minimum number of confirmations.\n" "\nArguments:\n" "1. \"polisaddress\" (string, required) The polis address for transactions.\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n" "\nExamples:\n" "\nThe amount from transactions with at least 1 confirmation\n" + HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") + "\nThe amount including unconfirmed transactions, zero confirmations\n" + HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0") + "\nThe amount with at least 6 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 6") + "\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); // polis address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid polis address"); CScript scriptPubKey = GetScriptForDestination(address.Get()); if (!IsMine(*pwalletMain, scriptPubKey)) return ValueFromAmount(0); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); bool fAddLockConf = (params.size() > 2 && params[2].get_bool()); // Tally CAmount nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } UniValue getreceivedbyaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "getreceivedbyaccount \"account\" ( minconf addlockconf )\n" "\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with specified minimum number of confirmations.\n" "\nArguments:\n" "1. \"account\" (string, required) The selected account, may be the default account using \"\".\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n" "\nExamples:\n" "\nAmount received by the default account with at least 1 confirmation\n" + HelpExampleCli("getreceivedbyaccount", "\"\"") + "\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") + "\nThe amount with at least 6 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") + "\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); bool fAddLockConf = (params.size() > 2 && params[2].get_bool()); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount); // Tally CAmount nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) nAmount += txout.nValue; } } return ValueFromAmount(nAmount); } CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf) { CAmount nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain(fAddLockConf) < 0) continue; CAmount nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter); if (nReceived != 0 && wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) nBalance += nReceived; nBalance -= nSent + nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth, filter, fAddLockConf); } UniValue getbalance(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 4) throw runtime_error( "getbalance ( \"account\" minconf addlockconf includeWatchonly )\n" "\nIf account is not specified, returns the server's total available balance.\n" "If account is specified (DEPRECATED), returns the balance in the account.\n" "Note that the account \"\" is not the same as leaving the parameter out.\n" "The server total may be different to the balance in the default \"\" account.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "4. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n" "\nExamples:\n" "\nThe total amount in the wallet\n" + HelpExampleCli("getbalance", "") + "\nThe total amount in the wallet at least 5 blocks confirmed\n" + HelpExampleCli("getbalance", "\"*\" 6") + "\nAs a json rpc call\n" + HelpExampleRpc("getbalance", "\"*\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); bool fAddLockConf = (params.size() > 2 && params[2].get_bool()); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 3) if(params[3].get_bool()) filter = filter | ISMINE_WATCH_ONLY; if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and "getbalance * 1 true" should return the same number CAmount nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0) continue; CAmount allFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) nBalance += r.amount; } BOOST_FOREACH(const COutputEntry& s, listSent) nBalance -= s.amount; nBalance -= allFee; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, filter, fAddLockConf); return ValueFromAmount(nBalance); } UniValue getunconfirmedbalance(const UniValue &params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 0) throw runtime_error( "getunconfirmedbalance\n" "Returns the server's total unconfirmed balance\n"); LOCK2(cs_main, pwalletMain->cs_wallet); return ValueFromAmount(pwalletMain->GetUnconfirmedBalance()); } UniValue movecmd(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n" "\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n" "2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n" "3. amount (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n" "4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n" "5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n" "\nResult:\n" "true|false (boolean) true if successful.\n" "\nExamples:\n" "\nMove 0.01 " + CURRENCY_UNIT + " from the default account to the account named tabby\n" + HelpExampleCli("move", "\"\" \"tabby\" 0.01") + "\nMove 0.01 " + CURRENCY_UNIT + " timotei to akiko with a comment and funds have 6 confirmations\n" + HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 6 \"happy birthday!\"") + "\nAs a json rpc call\n" + HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); CAmount nAmount = AmountFromValue(params[2]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64_t nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; pwalletMain->AddAccountingEntry(debit, walletdb); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; pwalletMain->AddAccountingEntry(credit, walletdb); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } UniValue sendfrom(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 3 || params.size() > 7) throw runtime_error( "sendfrom \"fromaccount\" \"topolisaddress\" amount ( minconf addlockconf \"comment\" \"comment-to\" )\n" "\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a polis address." + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n" "2. \"topolisaddress\" (string, required) The polis address to send funds to.\n" "3. amount (numeric or string, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n" "4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n" "5. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "6. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "7. \"comment-to\" (string, optional) An optional comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the transaction, \n" " it is just kept in your wallet.\n" "\nResult:\n" "\"transactionid\" (string) The transaction id.\n" "\nExamples:\n" "\nSend 0.01 " + CURRENCY_UNIT + " from the default account to the address, must have at least 1 confirmation\n" + HelpExampleCli("sendfrom", "\"\" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.01") + "\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n" + HelpExampleCli("sendfrom", "\"tabby\" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.01 6 false \"donation\" \"seans outpost\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendfrom", "\"tabby\", \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.01, 6, false, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid polis address"); CAmount nAmount = AmountFromValue(params[2]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); bool fAddLockConf = (params.size() > 4 && params[4].get_bool()); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 5 && !params[5].isNull() && !params[5].get_str().empty()) wtx.mapValue["comment"] = params[5].get_str(); if (params.size() > 6 && !params[6].isNull() && !params[6].get_str().empty()) wtx.mapValue["to"] = params[6].get_str(); EnsureWalletIsUnlocked(); // Check funds CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, fAddLockConf); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); SendMoney(address.Get(), nAmount, false, wtx); return wtx.GetHash().GetHex(); } UniValue sendmany(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 8) throw runtime_error( "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf addlockconf \"comment\" [\"address\",...] subtractfeefromamount use_is use_ps )\n" "\nSend multiple times. Amounts are double-precision floating point numbers." + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) DEPRECATED. The account to send the funds from. Should be \"\" for the default account\n" "2. \"amounts\" (string, required) A json object with addresses and amounts\n" " {\n" " \"address\":amount (numeric or string) The polis address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value\n" " ,...\n" " }\n" "3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n" "4. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "5. \"comment\" (string, optional) A comment\n" "6. subtractfeefromamount (string, optional) A json array with addresses.\n" " The fee will be equally deducted from the amount of each selected address.\n" " Those recipients will receive less poliss than you enter in their corresponding amount field.\n" " If no addresses are specified here, the sender pays the fee.\n" " [\n" " \"address\" (string) Subtract fee from this address\n" " ,...\n" " ]\n" "7. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n" "8. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n" "\nResult:\n" "\"transactionid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n" " the number of addresses.\n" "\nExamples:\n" "\nSend two amounts to two different addresses:\n" + HelpExampleCli("sendmany", "\"tabby\" \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\"") + "\nSend two amounts to two different addresses setting the confirmation and comment:\n" + HelpExampleCli("sendmany", "\"tabby\" \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\" 6 false \"testing\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendmany", "\"tabby\", \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\", 6, false, \"testing\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (pwalletMain->GetBroadcastTransactions() && !g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); string strAccount = AccountFromValue(params[0]); UniValue sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); bool fAddLockConf = (params.size() > 3 && params[3].get_bool()); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && !params[4].isNull() && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); UniValue subtractFeeFromAmount(UniValue::VARR); if (params.size() > 5) subtractFeeFromAmount = params[5].get_array(); set<CBitcoinAddress> setAddress; vector<CRecipient> vecSend; CAmount totalAmount = 0; vector<string> keys = sendTo.getKeys(); BOOST_FOREACH(const string& name_, keys) { CBitcoinAddress address(name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid polis address: ")+name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(sendTo[name_]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); totalAmount += nAmount; bool fSubtractFeeFromAmount = false; for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) { const UniValue& addr = subtractFeeFromAmount[idx]; if (addr.get_str() == name_) fSubtractFeeFromAmount = true; } CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount}; vecSend.push_back(recipient); } EnsureWalletIsUnlocked(); // Check funds CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, fAddLockConf); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); CAmount nFeeRequired = 0; int nChangePosRet = -1; string strFailReason; bool fUseInstantSend = false; bool fUsePrivateSend = false; if (params.size() > 6) fUseInstantSend = params[6].get_bool(); if (params.size() > 7) fUsePrivateSend = params[7].get_bool(); bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason, NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend); if (!fCreated) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason); if (!pwalletMain->CommitTransaction(wtx, keyChange, g_connman.get(), fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } // Defined in rpc/misc.cpp extern CScript _createmultisig_redeemScript(const UniValue& params); UniValue addmultisigaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n" "\nAdd a nrequired-to-sign multisignature address to the wallet.\n" "Each key is a polis address or hex-encoded public key.\n" "If 'account' is specified (DEPRECATED), assign address to that account.\n" "\nArguments:\n" "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n" "2. \"keysobject\" (string, required) A json array of polis addresses or hex-encoded public keys\n" " [\n" " \"address\" (string) polis address or hex-encoded public key\n" " ...,\n" " ]\n" "3. \"account\" (string, optional) DEPRECATED. An account to assign the addresses to.\n" "\nResult:\n" "\"polisaddress\" (string) A polis address associated with the keys.\n" "\nExamples:\n" "\nAdd a multisig address from 2 addresses\n" + HelpExampleCli("addmultisigaddress", "2 \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"") + "\nAs json rpc call\n" + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"") ; throw runtime_error(msg); } LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Construct using pay-to-script-hash: CScript inner = _createmultisig_redeemScript(params); CScriptID innerID(inner); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBook(innerID, strAccount, "send"); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { CAmount nAmount; int nConf; vector<uint256> txids; bool fIsWatchonly; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); fIsWatchonly = false; } }; UniValue ListReceived(const UniValue& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); bool fAddLockConf = (params.size() > 1 && params[1].get_bool()); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 2) fIncludeEmpty = params[2].get_bool(); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 3) if(params[3].get_bool()) filter = filter | ISMINE_WATCH_ONLY; // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) continue; int nDepth = wtx.GetDepthInMainChain(fAddLockConf); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) continue; isminefilter mine = IsMine(*pwalletMain, address); if(!(mine & filter)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); item.txids.push_back(wtx.GetHash()); if (mine & ISMINE_WATCH_ONLY) item.fIsWatchonly = true; } } // Reply UniValue ret(UniValue::VARR); map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second.name; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; isminefilter mine = IsMine(*pwalletMain, address.Get()); if(!(mine & filter)) continue; CAmount nAmount = 0; int nConf = std::numeric_limits<int>::max(); bool fIsWatchonly = false; if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; fIsWatchonly = (*it).second.fIsWatchonly; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); item.fIsWatchonly = fIsWatchonly; } else { UniValue obj(UniValue::VOBJ); if(fIsWatchonly) obj.push_back(Pair("involvesWatchonly", true)); obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); if (!fByAccounts) obj.push_back(Pair("label", strAccount)); UniValue transactions(UniValue::VARR); if (it != mapTally.end()) { BOOST_FOREACH(const uint256& item, (*it).second.txids) { transactions.push_back(item.GetHex()); } } obj.push_back(Pair("txids", transactions)); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { CAmount nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; UniValue obj(UniValue::VOBJ); if((*it).second.fIsWatchonly) obj.push_back(Pair("involvesWatchonly", true)); obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } UniValue listreceivedbyaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 4) throw runtime_error( "listreceivedbyaddress ( minconf addlockconf includeempty includeWatchonly)\n" "\nList balances by receiving address.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n" "2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "3. includeempty (bool, optional, default=false) Whether to include addresses that haven't received any payments.\n" "4. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n" "\nResult:\n" "[\n" " {\n" " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n" " \"address\" : \"receivingaddress\", (string) The receiving address\n" " \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n" " \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n" " \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included.\n" " If 'addlockconf' is true, the minimum number of confirmations is calculated\n" " including additional " + std::to_string(nInstantSendDepth) + " confirmations for transactions locked via InstantSend\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listreceivedbyaddress", "") + HelpExampleCli("listreceivedbyaddress", "6 false true") + HelpExampleRpc("listreceivedbyaddress", "6, false, true, true") ); LOCK2(cs_main, pwalletMain->cs_wallet); return ListReceived(params, false); } UniValue listreceivedbyaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 4) throw runtime_error( "listreceivedbyaccount ( minconf addlockconf includeempty includeWatchonly)\n" "\nDEPRECATED. List balances by account.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n" "2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "3. includeempty (bool, optional, default=false) Whether to include accounts that haven't received any payments.\n" "4. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n" "\nResult:\n" "[\n" " {\n" " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n" " \"account\" : \"accountname\", (string) The account name of the receiving account\n" " \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n" " \"confirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listreceivedbyaccount", "") + HelpExampleCli("listreceivedbyaccount", "6 false true") + HelpExampleRpc("listreceivedbyaccount", "6, false, true, true") ); LOCK2(cs_main, pwalletMain->cs_wallet); return ListReceived(params, true); } static void MaybePushAddress(UniValue & entry, const CTxDestination &dest) { CBitcoinAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter) { CAmount nFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter); bool fAllAccounts = (strAccount == string("*")); bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY); // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const COutputEntry& s, listSent) { UniValue entry(UniValue::VOBJ); if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY)) entry.push_back(Pair("involvesWatchonly", true)); entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.destination); std::map<std::string, std::string>::const_iterator it = wtx.mapValue.find("DS"); entry.push_back(Pair("category", (it != wtx.mapValue.end() && it->second == "1") ? "privatesend" : "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.amount))); if (pwalletMain->mapAddressBook.count(s.destination)) entry.push_back(Pair("label", pwalletMain->mapAddressBook[s.destination].name)); entry.push_back(Pair("vout", s.vout)); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); entry.push_back(Pair("abandoned", wtx.isAbandoned())); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.destination)) account = pwalletMain->mapAddressBook[r.destination].name; if (fAllAccounts || (account == strAccount)) { UniValue entry(UniValue::VOBJ); if(involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY)) entry.push_back(Pair("involvesWatchonly", true)); entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.destination); if (wtx.IsCoinBase()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } entry.push_back(Pair("amount", ValueFromAmount(r.amount))); if (pwalletMain->mapAddressBook.count(r.destination)) entry.push_back(Pair("label", account)); entry.push_back(Pair("vout", r.vout)); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { UniValue entry(UniValue::VOBJ); entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } UniValue listtransactions(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 4) throw runtime_error( "listtransactions ( \"account\" count from includeWatchonly)\n" "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The account name. Should be \"*\".\n" "2. count (numeric, optional, default=10) The number of transactions to return\n" "3. from (numeric, optional, default=0) The number of transactions to skip\n" "4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n" "\nResult:\n" "[\n" " {\n" " \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. \n" " It will be \"\" for the default account.\n" " \"address\":\"polisaddress\", (string) The polis address of the transaction. Not present for \n" " move transactions (category = move).\n" " \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n" " transaction between accounts, and not associated with an address,\n" " transaction id or block. 'send' and 'receive' transactions are \n" " associated with an address, transaction id and block details\n" " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the\n" " 'move' category for moves outbound. It is positive for the 'receive' category,\n" " and for the 'move' category for inbound funds.\n" " \"vout\": n, (numeric) the vout value\n" " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n" " 'send' category of transactions.\n" " \"instantlock\" : true|false, (bool) Current transaction lock state. Available for 'send' and 'receive' category of transactions.\n" " \"confirmations\": n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and \n" " 'receive' category of transactions. Negative confirmations indicate the\n" " transation conflicts with the block chain\n" " \"trusted\": xxx (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n" " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n" " category of transactions.\n" " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive'\n" " category of transactions.\n" " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n" " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n" " \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n" " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n" " for 'send' and 'receive' category of transactions.\n" " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n" " \"label\": \"label\" (string) A comment for the address/transaction, if any\n" " \"otheraccount\": \"accountname\", (string) For the 'move' category of transactions, the account the funds came \n" " from (for receiving funds, positive amounts), or went to (for sending funds,\n" " negative amounts).\n" " \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n" " may be unknown for unconfirmed transactions not in the mempool\n" " }\n" "]\n" "\nExamples:\n" "\nList the most recent 10 transactions in the systems\n" + HelpExampleCli("listtransactions", "") + "\nList transactions 100 to 120\n" + HelpExampleCli("listtransactions", "\"*\" 20 100") + "\nAs a json rpc call\n" + HelpExampleRpc("listtransactions", "\"*\", 20, 100") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 3) if(params[3].get_bool()) filter = filter | ISMINE_WATCH_ONLY; if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); UniValue ret(UniValue::VARR); const CWallet::TxItems & txOrdered = pwalletMain->wtxOrdered; // iterate backwards until we have nCount items to return: for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret, filter); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; vector<UniValue> arrTmp = ret.getValues(); vector<UniValue>::iterator first = arrTmp.begin(); std::advance(first, nFrom); vector<UniValue>::iterator last = arrTmp.begin(); std::advance(last, nFrom+nCount); if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end()); if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first); std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest ret.clear(); ret.setArray(); ret.push_backV(arrTmp); return ret; } UniValue listaccounts(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 3) throw runtime_error( "listaccounts ( minconf addlockconf includeWatchonly)\n" "\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n" "2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "3. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n" "\nResult:\n" "{ (json object where keys are account names, and values are numeric balances\n" " \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n" " ...\n" "}\n" "\nExamples:\n" "\nList account balances where there at least 1 confirmation\n" + HelpExampleCli("listaccounts", "") + "\nList account balances including zero confirmation transactions\n" + HelpExampleCli("listaccounts", "0") + "\nList account balances for 6 or more confirmations\n" + HelpExampleCli("listaccounts", "6") + "\nAs json rpc call\n" + HelpExampleRpc("listaccounts", "6") ); LOCK2(cs_main, pwalletMain->cs_wallet); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); bool fAddLockConf = (params.size() > 1 && params[1].get_bool()); isminefilter includeWatchonly = ISMINE_SPENDABLE; if(params.size() > 2) if(params[2].get_bool()) includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY; map<string, CAmount> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me mapAccountBalances[entry.second.name] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; CAmount nFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; int nDepth = wtx.GetDepthInMainChain(fAddLockConf); if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0) continue; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const COutputEntry& s, listSent) mapAccountBalances[strSentAccount] -= s.amount; if (nDepth >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) if (pwalletMain->mapAddressBook.count(r.destination)) mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount; else mapAccountBalances[""] += r.amount; } } const list<CAccountingEntry> & acentries = pwalletMain->laccentries; BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; UniValue ret(UniValue::VOBJ); BOOST_FOREACH(const PAIRTYPE(string, CAmount)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } UniValue listsinceblock(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp) throw runtime_error( "listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n" "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n" "\nArguments:\n" "1. \"blockhash\" (string, optional) The block hash to list transactions since\n" "2. target-confirmations: (numeric, optional) The confirmations required, must be 1 or more\n" "3. includeWatchonly: (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')" "\nResult:\n" "{\n" " \"transactions\": [\n" " \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. Will be \"\" for the default account.\n" " \"address\":\"polisaddress\", (string) The polis address of the transaction. Not present for move transactions (category = move).\n" " \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n" " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n" " outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n" " \"vout\" : n, (numeric) the vout value\n" " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n" " \"instantlock\" : true|false, (bool) Current transaction lock state. Available for 'send' and 'receive' category of transactions.\n" " \"confirmations\" : n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n" " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n" " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive' category of transactions.\n" " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n" " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n" " \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n" " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n" " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " \"to\": \"...\", (string) If a comment to is associated with the transaction.\n" " ],\n" " \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n" "}\n" "\nExamples:\n" + HelpExampleCli("listsinceblock", "") + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6") + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBlockIndex *pindex = NULL; int target_confirms = 1; isminefilter filter = ISMINE_SPENDABLE; if (params.size() > 0) { uint256 blockId; blockId.SetHex(params[0].get_str()); BlockMap::iterator it = mapBlockIndex.find(blockId); if (it != mapBlockIndex.end()) pindex = it->second; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid blockhash"); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } if(params.size() > 2) if(params[2].get_bool()) filter = filter | ISMINE_WATCH_ONLY; int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1; UniValue transactions(UniValue::VARR); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain(false) < depth) ListTransactions(tx, "*", 0, true, transactions, filter); } CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms]; uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256(); UniValue ret(UniValue::VOBJ); ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } UniValue gettransaction(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "gettransaction \"txid\" ( includeWatchonly )\n" "\nGet detailed information about in-wallet transaction <txid>\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. \"includeWatchonly\" (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n" "\nResult:\n" "{\n" " \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n" " \"instantlock\" : true|false, (bool) Current transaction lock state\n" " \"confirmations\" : n, (numeric) The number of blockchain confirmations\n" " \"blockhash\" : \"hash\", (string) The block hash\n" " \"blockindex\" : xx, (numeric) The index of the transaction in the block that includes it\n" " \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n" " \"txid\" : \"transactionid\", (string) The transaction id.\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n" " \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n" " \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n" " may be unknown for unconfirmed transactions not in the mempool\n" " \"details\" : [\n" " {\n" " \"account\" : \"accountname\", (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n" " \"address\" : \"polisaddress\", (string) The polis address involved in the transaction\n" " \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n" " \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n" " \"label\" : \"label\", (string) A comment for the address/transaction, if any\n" " \"vout\" : n, (numeric) the vout value\n" " }\n" " ,...\n" " ],\n" " \"hex\" : \"data\" (string) Raw data for transaction\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true") + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); uint256 hash; hash.SetHex(params[0].get_str()); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 1) if(params[1].get_bool()) filter = filter | ISMINE_WATCH_ONLY; UniValue entry(UniValue::VOBJ); if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; CAmount nCredit = wtx.GetCredit(filter); CAmount nDebit = wtx.GetDebit(filter); CAmount nNet = nCredit - nDebit; CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe(filter)) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); UniValue details(UniValue::VARR); ListTransactions(wtx, "*", 0, false, details, filter); entry.push_back(Pair("details", details)); string strHex = EncodeHexTx(static_cast<CTransaction>(wtx)); entry.push_back(Pair("hex", strHex)); return entry; } UniValue abandontransaction(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "abandontransaction \"txid\"\n" "\nMark in-wallet transaction <txid> as abandoned\n" "This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n" "for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n" "It only works on transactions which are not included in a block and are not currently in the mempool.\n" "It has no effect on transactions which are already conflicted or abandoned.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") + HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); uint256 hash; hash.SetHex(params[0].get_str()); if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); if (!pwalletMain->AbandonTransaction(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment"); return NullUniValue; } UniValue backupwallet(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "backupwallet \"destination\"\n" "\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n" "\nArguments:\n" "1. \"destination\" (string) The destination directory or file\n" "\nExamples:\n" + HelpExampleCli("backupwallet", "\"backup.dat\"") + HelpExampleRpc("backupwallet", "\"backup.dat\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return NullUniValue; } UniValue keypoolrefill(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 1) throw runtime_error( "keypoolrefill ( newsize )\n" "\nFills the keypool." + HelpRequiringPassphrase() + "\n" "\nArguments\n" "1. newsize (numeric, optional, default=" + itostr(DEFAULT_KEYPOOL_SIZE) + ") The new keypool size\n" "\nExamples:\n" + HelpExampleCli("keypoolrefill", "") + HelpExampleRpc("keypoolrefill", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool unsigned int kpSize = 0; if (params.size() > 0) { if (params[0].get_int() < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size."); kpSize = (unsigned int)params[0].get_int(); } EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(kpSize); if (pwalletMain->GetKeyPoolSize() < (pwalletMain->IsHDEnabled() ? kpSize * 2 : kpSize)) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return NullUniValue; } static void LockWallet(CWallet* pWallet) { LOCK(cs_nWalletUnlockTime); nWalletUnlockTime = 0; pWallet->Lock(); } UniValue walletpassphrase(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3)) throw runtime_error( "walletpassphrase \"passphrase\" timeout ( mixingonly )\n" "\nStores the wallet decryption key in memory for 'timeout' seconds.\n" "This is needed prior to performing transactions related to private keys such as sending poliss\n" "\nArguments:\n" "1. \"passphrase\" (string, required) The wallet passphrase\n" "2. timeout (numeric, required) The time to keep the decryption key in seconds.\n" "3. mixingonly (boolean, optional, default=false) If is true sending functions are disabled." "\nNote:\n" "Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n" "time that overrides the old one.\n" "\nExamples:\n" "\nUnlock the wallet for 60 seconds\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") + "\nUnlock the wallet for 60 seconds but allow PrivateSend mixing only\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60 true") + "\nLock the wallet again (before 60 seconds)\n" + HelpExampleCli("walletlock", "") + "\nAs json rpc call\n" + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); int64_t nSleepTime = params[1].get_int64(); bool fForMixingOnly = false; if (params.size() >= 3) fForMixingOnly = params[2].get_bool(); if (fForMixingOnly && !pwalletMain->IsLocked(true) && pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked for mixing only."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already fully unlocked."); if (!pwalletMain->Unlock(strWalletPass, fForMixingOnly)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); pwalletMain->TopUpKeyPool(); LOCK(cs_nWalletUnlockTime); nWalletUnlockTime = GetTime() + nSleepTime; RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime); return NullUniValue; } UniValue walletpassphrasechange(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n" "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n" "\nArguments:\n" "1. \"oldpassphrase\" (string) The current passphrase\n" "2. \"newpassphrase\" (string) The new passphrase\n" "\nExamples:\n" + HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"") + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return NullUniValue; } UniValue walletlock(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "\nRemoves the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked.\n" "\nExamples:\n" "\nSet the passphrase for 2 minutes to perform a transaction\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") + "\nPerform a send (requires passphrase set)\n" + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 1.0") + "\nClear the passphrase since we are done before 2 minutes is up\n" + HelpExampleCli("walletlock", "") + "\nAs json rpc call\n" + HelpExampleRpc("walletlock", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return NullUniValue; } UniValue encryptwallet(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet \"passphrase\"\n" "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n" "After this, any calls that interact with private keys such as sending or signing \n" "will require the passphrase to be set prior the making these calls.\n" "Use the walletpassphrase call for this, and then walletlock call.\n" "If the wallet is already encrypted, use the walletpassphrasechange call.\n" "Note that this will shutdown the server.\n" "\nArguments:\n" "1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n" "\nExamples:\n" "\nEncrypt you wallet\n" + HelpExampleCli("encryptwallet", "\"my pass phrase\"") + "\nNow set the passphrase to use the wallet, such as for signing or sending polis\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") + "\nNow we can so something like sign\n" + HelpExampleCli("signmessage", "\"polisaddress\" \"test message\"") + "\nNow lock the wallet again by removing the passphrase\n" + HelpExampleCli("walletlock", "") + "\nAs a json rpc call\n" + HelpExampleRpc("encryptwallet", "\"my pass phrase\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "Wallet encrypted; polis Core server stopping, restart to run with encrypted wallet. The keypool has been flushed and a new HD seed was generated (if you are using HD). You need to make a new backup."; } UniValue lockunspent(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n" "\nUpdates list of temporarily unspendable outputs.\n" "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n" "A locked transaction output will not be chosen by automatic coin selection, when spending poliss.\n" "Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n" "is always cleared (by virtue of process exit) when a node stops or fails.\n" "Also see the listunspent call\n" "\nArguments:\n" "1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n" "2. \"transactions\" (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n" " [ (json array of json objects)\n" " {\n" " \"txid\":\"id\", (string) The transaction id\n" " \"vout\": n (numeric) The output number\n" " }\n" " ,...\n" " ]\n" "\nResult:\n" "true|false (boolean) Whether the command was successful or not\n" "\nExamples:\n" "\nList the unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") + "\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (params.size() == 1) RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)); else RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR)); bool fUnlock = params[0].get_bool(); if (params.size() == 1) { if (fUnlock) pwalletMain->UnlockAllCoins(); return true; } UniValue outputs = params[1].get_array(); for (unsigned int idx = 0; idx < outputs.size(); idx++) { const UniValue& output = outputs[idx]; if (!output.isObject()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object"); const UniValue& o = output.get_obj(); RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)); string txid = find_value(o, "txid").get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); int nOutput = find_value(o, "vout").get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); COutPoint outpt(uint256S(txid), nOutput); if (fUnlock) pwalletMain->UnlockCoin(outpt); else pwalletMain->LockCoin(outpt); } return true; } UniValue listlockunspent(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 0) throw runtime_error( "listlockunspent\n" "\nReturns list of temporarily unspendable outputs.\n" "See the lockunspent call to lock and unlock transactions for spending.\n" "\nResult:\n" "[\n" " {\n" " \"txid\" : \"transactionid\", (string) The transaction id locked\n" " \"vout\" : n (numeric) The vout value\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" "\nList the unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") + "\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("listlockunspent", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); vector<COutPoint> vOutpts; pwalletMain->ListLockedCoins(vOutpts); UniValue ret(UniValue::VARR); BOOST_FOREACH(COutPoint &outpt, vOutpts) { UniValue o(UniValue::VOBJ); o.push_back(Pair("txid", outpt.hash.GetHex())); o.push_back(Pair("vout", (int)outpt.n)); ret.push_back(o); } return ret; } UniValue settxfee(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "settxfee amount\n" "\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n" "\nArguments:\n" "1. amount (numeric or sting, required) The transaction fee in " + CURRENCY_UNIT + "/kB\n" "\nResult\n" "true|false (boolean) Returns true if successful\n" "\nExamples:\n" + HelpExampleCli("settxfee", "0.00001") + HelpExampleRpc("settxfee", "0.00001") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Amount CAmount nAmount = AmountFromValue(params[0]); payTxFee = CFeeRate(nAmount, 1000); return true; } UniValue getwalletinfo(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 0) throw runtime_error( "getwalletinfo\n" "Returns an object containing various wallet state info.\n" "\nResult:\n" "{\n" " \"walletversion\": xxxxx, (numeric) the wallet version\n" " \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n" " \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n" " \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n" " \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n" " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n" " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated (only counts external keys)\n" " \"keypoolsize_hd_internal\": xxxx, (numeric) how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)\n" " \"keys_left\": xxxx, (numeric) how many new keys are left since last automatic backup\n" " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n" " \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n" " \"hdchainid\": \"<hash>\", (string) the ID of the HD chain\n" " \"hdaccountcount\": xxx, (numeric) how many accounts of the HD chain are in this wallet\n" " [\n" " {\n" " \"hdaccountindex\": xxx, (numeric) the index of the account\n" " \"hdexternalkeyindex\": xxxx, (numeric) current external childkey index\n" " \"hdinternalkeyindex\": xxxx, (numeric) current internal childkey index\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("getwalletinfo", "") + HelpExampleRpc("getwalletinfo", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); CHDChain hdChainCurrent; bool fHDEnabled = pwalletMain->GetHDChain(hdChainCurrent); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("unconfirmed_balance", ValueFromAmount(pwalletMain->GetUnconfirmedBalance()))); obj.push_back(Pair("immature_balance", ValueFromAmount(pwalletMain->GetImmatureBalance()))); obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size())); obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int64_t)pwalletMain->KeypoolCountExternalKeys())); if (fHDEnabled) { obj.push_back(Pair("keypoolsize_hd_internal", (int64_t)(pwalletMain->KeypoolCountInternalKeys()))); } obj.push_back(Pair("keys_left", pwalletMain->nKeysLeftSinceAutoBackup)); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", nWalletUnlockTime)); obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK()))); if (fHDEnabled) { obj.push_back(Pair("hdchainid", hdChainCurrent.GetID().GetHex())); obj.push_back(Pair("hdaccountcount", (int64_t)hdChainCurrent.CountAccounts())); UniValue accounts(UniValue::VARR); for (size_t i = 0; i < hdChainCurrent.CountAccounts(); ++i) { CHDAccount acc; UniValue account(UniValue::VOBJ); account.push_back(Pair("hdaccountindex", (int64_t)i)); if(hdChainCurrent.GetAccount(i, acc)) { account.push_back(Pair("hdexternalkeyindex", (int64_t)acc.nExternalChainCounter)); account.push_back(Pair("hdinternalkeyindex", (int64_t)acc.nInternalChainCounter)); } else { account.push_back(Pair("error", strprintf("account %d is missing", i))); } accounts.push_back(account); } obj.push_back(Pair("hdaccounts", accounts)); } return obj; } UniValue keepass(const UniValue& params, bool fHelp) { string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "genkey" && strCommand != "init" && strCommand != "setpassphrase")) throw runtime_error( "keepass <genkey|init|setpassphrase>\n"); if (strCommand == "genkey") { SecureString sResult; // Generate RSA key SecureString sKey = CKeePassIntegrator::generateKeePassKey(); sResult = "Generated Key: "; sResult += sKey; return sResult.c_str(); } else if(strCommand == "init") { // Generate base64 encoded 256 bit RSA key and associate with KeePassHttp SecureString sResult; SecureString sKey; std::string strId; keePassInt.rpcAssociate(strId, sKey); sResult = "Association successful. Id: "; sResult += strId.c_str(); sResult += " - Key: "; sResult += sKey.c_str(); return sResult.c_str(); } else if(strCommand == "setpassphrase") { if(params.size() != 2) { return "setlogin: invalid number of parameters. Requires a passphrase"; } SecureString sPassphrase = SecureString(params[1].get_str().c_str()); keePassInt.updatePassphrase(sPassphrase); return "setlogin: Updated credentials."; } return "Invalid command"; } UniValue resendwallettransactions(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 0) throw runtime_error( "resendwallettransactions\n" "Immediately re-broadcast unconfirmed wallet transactions to all peers.\n" "Intended only for testing; the wallet code periodically re-broadcasts\n" "automatically.\n" "Returns array of transaction ids that were re-broadcast.\n" ); if (!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); LOCK2(cs_main, pwalletMain->cs_wallet); std::vector<uint256> txids = pwalletMain->ResendWalletTransactionsBefore(GetTime(), g_connman.get()); UniValue result(UniValue::VARR); BOOST_FOREACH(const uint256& txid, txids) { result.push_back(txid.ToString()); } return result; } UniValue listunspent(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 3) throw runtime_error( "listunspent ( minconf maxconf [\"address\",...] )\n" "\nReturns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filter to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n" "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n" "3. \"addresses\" (string) A json array of polis addresses to filter\n" " [\n" " \"address\" (string) polis address\n" " ,...\n" " ]\n" "\nResult\n" "[ (array of json object)\n" " {\n" " \"txid\" : \"txid\", (string) the transaction id \n" " \"vout\" : n, (numeric) the vout value\n" " \"address\" : \"address\", (string) the polis address\n" " \"account\" : \"account\", (string) DEPRECATED. The associated account, or \"\" for the default account\n" " \"scriptPubKey\" : \"key\", (string) the script key\n" " \"amount\" : x.xxx, (numeric) the transaction amount in " + CURRENCY_UNIT + "\n" " \"confirmations\" : n (numeric) The number of confirmations\n" " \"ps_rounds\" : n (numeric) The number of PS round\n" " \"spendable\" : xxx, (bool) Whether we have the private keys to spend this output\n" " \"solvable\" : xxx (bool) Whether we know how to spend this output, ignoring the lack of keys\n" " }\n" " ,...\n" "]\n" "\nExamples\n" + HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "6 9999999 \"[\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\",\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\"]\"") + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\",\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\"]\"") ); RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { UniValue inputs = params[2].get_array(); for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid polis address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } UniValue results(UniValue::VARR); vector<COutput> vecOutputs; assert(pwalletMain != NULL); LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->AvailableCoins(vecOutputs, false, NULL, true); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if (setAddress.size()) { CTxDestination address; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } CAmount nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; UniValue entry(UniValue::VOBJ); entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name)); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); if (pk.IsPayToScriptHash()) { CTxDestination address; if (ExtractDestination(pk, address)) { const CScriptID& hash = boost::get<CScriptID>(address); CScript redeemScript; if (pwalletMain->GetCScript(hash, redeemScript)) entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end()))); } } entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); entry.push_back(Pair("ps_rounds", pwalletMain->GetOutpointPrivateSendRounds(COutPoint(out.tx->GetHash(), out.i)))); entry.push_back(Pair("spendable", out.fSpendable)); entry.push_back(Pair("solvable", out.fSolvable)); results.push_back(entry); } return results; } UniValue fundrawtransaction(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "fundrawtransaction \"hexstring\" includeWatching\n" "\nAdd inputs to a transaction until it has enough in value to meet its out value.\n" "This will not modify existing inputs, and will add one change output to the outputs.\n" "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n" "The inputs added will not be signed, use signrawtransaction for that.\n" "Note that all existing inputs must have their previous output transaction be in the wallet.\n" "Note that all inputs selected must be of standard form and P2SH scripts must be" "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n" "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n" "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n" "\nArguments:\n" "1. \"hexstring\" (string, required) The hex string of the raw transaction\n" "2. includeWatching (boolean, optional, default false) Also select inputs which are watch only\n" "\nResult:\n" "{\n" " \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n" " \"fee\": n, (numeric) Fee the resulting transaction pays\n" " \"changepos\": n (numeric) The position of the added change output, or -1\n" "}\n" "\"hex\" \n" "\nExamples:\n" "\nCreate a transaction with no inputs\n" + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") + "\nAdd sufficient unsigned inputs to meet the output value\n" + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") + "\nSign the transaction\n" + HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") + "\nSend the transaction\n" + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"") ); RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)); // parse hex string from parameter CTransaction origTx; if (!DecodeHexTx(origTx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); if (origTx.vout.size() == 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output"); bool includeWatching = false; if (params.size() > 1) includeWatching = params[1].get_bool(); CMutableTransaction tx(origTx); CAmount nFee; string strFailReason; int nChangePos = -1; if(!pwalletMain->FundTransaction(tx, nFee, nChangePos, strFailReason, includeWatching)) throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason); UniValue result(UniValue::VOBJ); result.push_back(Pair("hex", EncodeHexTx(tx))); result.push_back(Pair("changepos", nChangePos)); result.push_back(Pair("fee", ValueFromAmount(nFee))); return result; }
#include "DP_Print_inc.h" #include "zh_printer.h" static unsigned char gucCheckPassWord=0; /* 初始化打印机,清除打印缓冲 a*/ void InitializePrint(void) { /* 初始化打印机,清除打印缓冲 */ UART_SendByte(0x1B); UART_SendByte(0x40); gucCheckPassWord = 1; } /* 每调用一次,打印位置向后移动一定字的符单位 a*/ void jump_lattice(void) { if(!gucCheckPassWord) return; UART_SendByte(0x09); } /* 打印缓冲区数据并向前推进一行 a*/ void print_And_Line(void) { /* 发送一个换行符 */ UART_SendByte(0x0A); } /* ** 函数: Print_ASCII(unsigned char *buf) ** 参数: buf 要发送的字符串数据 功能: 把要打印的字符串放入缓冲区 */ void Print_ASCII(unsigned char *buf) { while(*buf != '\0') { UART_SendByte(*buf++); } } /* 设置字符右侧的间距为interval X 0.125mm a*/ void Set_Right_Interval(unsigned char interval) { if(!gucCheckPassWord) return; UART_SendByte(0x1B); UART_SendByte(0x20); UART_SendByte(interval); } /* 选择打印模式 a*/ void Set_Print_Mode(unsigned char optbit) { if(!gucCheckPassWord) return; UART_SendByte(0x1B); UART_SendByte(0x21); UART_SendByte(optbit); } /* 设定从一行的开始到将要打印字符的位置距离为(Lpos+Hpos*256)*0.125mm a*/ void Set_Print_Position(unsigned char Lpos,unsigned char Hpos) { if(!gucCheckPassWord) return; UART_SendByte(0x1B); UART_SendByte(0x24); UART_SendByte(Lpos); UART_SendByte(Hpos); } /* 设置左边间距 a */ void Set_Left_Interval(unsigned char nL, unsigned char nH) { if(!gucCheckPassWord) return; UART_SendByte(0x1D); UART_SendByte(0x4C); UART_SendByte(nL); UART_SendByte(nH); } /* 选择/取消用户自定义字符集 a*/ void Sel_Custom_Character(unsigned char SelOpt) { if(!gucCheckPassWord) return; UART_SendByte(0x1B); UART_SendByte(0x25); UART_SendByte(SelOpt); } /* 用户自定义字符集 a*/ void UserDefineCharacter(unsigned char yByte,unsigned char xDot, unsigned char DefChar,unsigned char *pData) { unsigned short int len; if(!gucCheckPassWord) return; UART_SendByte(0x1B); UART_SendByte(0x26); UART_SendByte(yByte); UART_SendByte(DefChar); UART_SendByte(DefChar); UART_SendByte(xDot); len = yByte*xDot; while(len) { UART_SendByte(*pData++); len--; } } /* 选择位图模式 a*/ void Sel_Bitmap_Mode(unsigned char mode,unsigned char DatLenLowByte,unsigned char DatLenHightByte,unsigned char *pDotData) { unsigned short int i; if(!gucCheckPassWord) return; if((mode!=0) && (mode!=1) && (mode!=32) && (mode!=33)) return; if(DatLenHightByte > 3) return; UART_SendByte(0x1B); UART_SendByte(0x2A); UART_SendByte(mode); UART_SendByte(DatLenLowByte); UART_SendByte(DatLenHightByte); i=DatLenLowByte + DatLenHightByte*256; while(i) { UART_SendByte(*pDotData++); i--; } } /* 设置下划线有无及规格 a*/ void Set_UnderLine(unsigned char Opt) { if(!gucCheckPassWord) return; if(Opt > 2) { Opt=2; } UART_SendByte(0x1B); UART_SendByte(0x2D); UART_SendByte(Opt); } /* 设置缺省行间距3.75mm a*/ void SetDefaultLineInterval(void) { if(!gucCheckPassWord) return; UART_SendByte(0x1B); UART_SendByte(0x32); } /* 取消自定义字符 a*/ void Del_UserDefineCharacter(unsigned char SelCharacter) { if(!gucCheckPassWord) return; if((SelCharacter < 32) || (SelCharacter > 126)) return; UART_SendByte(0x1B); UART_SendByte(0x3F); UART_SendByte(SelCharacter); } /* Position 水平定位位置(设置横向跳格位置) a */ void SetHorizPosition(unsigned char Position) { if(!gucCheckPassWord) return; UART_SendByte(0x1B); UART_SendByte(0x44); UART_SendByte(Position); UART_SendByte(Position); UART_SendByte(0x00); } /* 选择/取消加粗模式 a*/ void SetBold(unsigned char opt) { if(!gucCheckPassWord) return; if(opt>0x01) { opt=0x01; } UART_SendByte(0x1B); UART_SendByte(0x45); UART_SendByte(opt); } /* 打印并进纸nstep*0.125mm a*/ void PrintGoPage(unsigned char nstep) { if(!gucCheckPassWord) return; UART_SendByte(0x1B); UART_SendByte(0x4A); UART_SendByte(nstep); } /* 选择语言字符 a*/ void SelCountryCharacter(unsigned char nsel) { if(!gucCheckPassWord) return; UART_SendByte(0x1B); UART_SendByte(0x74); UART_SendByte(nsel); } /* 选择/取消顺时针旋转 90° a*/ void Set_Rotate(unsigned char nsel) { if(!gucCheckPassWord) return; if(nsel>1) { nsel=1; } UART_SendByte(0x1B); UART_SendByte(0x56); UART_SendByte(nsel); } /* 选择对齐方式 a*/ void Sel_Align_Way(unsigned char nsel) { if(!gucCheckPassWord) return; if(nsel > 2) { nsel = 2; } UART_SendByte(0x1B); UART_SendByte(0x61); UART_SendByte(nsel); } /* 选择/取消倒置打印模式 a*/ void SetReversal(unsigned char nsel) { if(!gucCheckPassWord) return; if(nsel > 1) { nsel = 1; } UART_SendByte(0x1B); UART_SendByte(0x7B); UART_SendByte(nsel); } /* 设置/选择字符大小 a*/ void SetCharacterSize(unsigned char width,unsigned char hight) { if(!gucCheckPassWord) return; if(width > 7) { width = 7; } if(hight > 7) { hight = 7; } hight = hight&0x0f; width = (width&0x0f)<<4; width = width | hight; UART_SendByte(0x1D); UART_SendByte(0x21); UART_SendByte(width); } /* 定义下载位图 */ void DownLoadBitmap(unsigned char xDot,unsigned char yDot,unsigned char *pDat) { unsigned short int len; if(!gucCheckPassWord) return; if(yDot > 48) return; UART_SendByte(0x1D); UART_SendByte(0x2A); UART_SendByte(xDot*8); UART_SendByte(yDot*8); len = xDot*yDot/8; while(len) { UART_SendByte(*pDat++); len--; } } /* 打印下载位图 */ void PrintDownLoadBitmap(unsigned char mode) { if(!gucCheckPassWord) return; if(mode > 3) { mode = 3; } UART_SendByte(0x1D); UART_SendByte(0x2F); UART_SendByte(mode); } /* 黑白反显打印 a*/ void Set_Inverse(unsigned char opt) { if(!gucCheckPassWord) return; if(opt>1) { opt=1; } UART_SendByte(0x1D); UART_SendByte(0x42); UART_SendByte(opt); } /* 设置左边距 a*/ void Set_LeftSpaceNum(unsigned char nL,unsigned char nH) { if(!gucCheckPassWord) return; UART_SendByte(0x1D); UART_SendByte(0x4C); UART_SendByte(nL); UART_SendByte(nH); } /* 选择 HRI 字符的打印位置 a*/ void Set_HRIPosition(unsigned char opt) { if(!gucCheckPassWord) return; if(opt>3) { opt=3; } UART_SendByte(0x1D); UART_SendByte(0x48); UART_SendByte(opt); } /* 选择条码高度 a*/ void Set_BarCodeHight(unsigned char verticalDotNum) { if(!gucCheckPassWord) return; UART_SendByte(0x1D); UART_SendByte(0x68); UART_SendByte(verticalDotNum); } /* 打印条码 a*/ void PrintBarCode(unsigned char CodeType,unsigned char *pData,unsigned char pDataLen) { if(!gucCheckPassWord) return; if((CodeType == 65) || (CodeType == 66)) { if((pDataLen < 11) || (pDataLen > 12)) return; } else if(CodeType == 67) { if((pDataLen < 12) || (pDataLen > 13)) return; } else if(CodeType == 68) { if((pDataLen < 7) || (pDataLen > 8)) return; } UART_SendByte(0x1D); UART_SendByte(0x6B); UART_SendByte(CodeType); if(CodeType == 0x47) { UART_SendByte(pDataLen+2); UART_SendByte(0x41); } else { UART_SendByte(pDataLen); } while(pDataLen) { UART_SendByte(*pData++); pDataLen--; } if(CodeType == 0x47) { UART_SendByte(0x41); } UART_SendByte(0x00); } /* 设置条形码左边间距 a*/ void Set_BarCodeLeftSpace(unsigned char nL, unsigned char nH) { if(!gucCheckPassWord) return; UART_SendByte(0x1D); UART_SendByte(0x4C); UART_SendByte(nL); UART_SendByte(nH); } /* 条形码的宽度 a*/ void Set_BarCodeWidth(unsigned char widthsel) { if(!gucCheckPassWord) return; if(widthsel < 2) { widthsel = 2; } else if(widthsel > 6) { widthsel = 6; } UART_SendByte(0x1D); UART_SendByte(0x77); UART_SendByte(widthsel); } /* 设置汉字字符打印模式 a*/ void SetChinesemode(unsigned char opt) { if(!gucCheckPassWord) return; UART_SendByte(0x1C); UART_SendByte(0x21); UART_SendByte(opt); } /* 选择汉字模式 a*/ void SelChineseChar(void) { if(!gucCheckPassWord) return; UART_SendByte(0x1C); UART_SendByte(0x26); } /*取消打印机汉字打印模式 a*/ void DisChineseChar(void) { if(!gucCheckPassWord) return; UART_SendByte(0x1C); UART_SendByte(0x2E); } /* 选择中文编码格式 a */ void Set_ChineseCode(unsigned char selopt) { if(!gucCheckPassWord) return; if(selopt > 3) selopt = 3; UART_SendByte(0x1B); UART_SendByte(0x23); UART_SendByte(0x23); UART_SendByte(0x43); UART_SendByte(0x44); UART_SendByte(0x54); UART_SendByte(0x59); UART_SendByte(selopt); } /*功能:打印测试页结束时进行切纸 a*/ void TestPrintPage(void) { UART_SendByte(0x1B); UART_SendByte(0x23); UART_SendByte(0x23); UART_SendByte(0x53); UART_SendByte(0x45); UART_SendByte(0x4C); UART_SendByte(0x46); UART_SendByte(0x1D); UART_SendByte(0x53); } /* 打印光栅位图 a */ void PrintGratinmap(unsigned char mode,unsigned int xDot,unsigned int yDot,unsigned char *pData) { unsigned char tmp; unsigned int len; if(!gucCheckPassWord) return; if(mode > 3) { mode = 3; } UART_SendByte(0x1D); UART_SendByte(0x76); UART_SendByte(0x30); UART_SendByte(mode); xDot = xDot / 8; tmp = (unsigned char)(xDot & 0x00ff); UART_SendByte(tmp); tmp = (unsigned char)((xDot>>8) & 0x00ff); UART_SendByte(tmp); tmp = (unsigned char)(yDot & 0x00ff); UART_SendByte(tmp); tmp = (unsigned char)((yDot>>8) & 0x00ff); UART_SendByte(tmp); len = xDot * yDot; while(len) { UART_SendByte(*pData++); len--; } } /* 设置QR Code(二维码)单元大小 a*/ void Set_QRcodeMode(unsigned char mode) { if(!gucCheckPassWord) return; if(mode > 16) mode = 16; UART_SendByte(0x1D); UART_SendByte(0x28); UART_SendByte(0x6B); UART_SendByte(0x03); UART_SendByte(0x00); UART_SendByte(0x31); UART_SendByte(0x43); UART_SendByte(mode); } /* 设置错误纠错等级 a*/ void Set_QRCodeAdjuLevel(unsigned char level) { if(!gucCheckPassWord) return; if(level < 0x30) { level = 0x30; } else if(level > 0x33) { level = 0x33; } UART_SendByte(0x1D); UART_SendByte(0x28); UART_SendByte(0x6B); UART_SendByte(0x03); UART_SendByte(0x00); UART_SendByte(0x31); UART_SendByte(0x45); UART_SendByte(level); } /* QRCode传输数据至编码缓存 a*/ void Set_QRCodeBuffer(unsigned int Len,unsigned char *pData) { unsigned char tmp; if(!gucCheckPassWord) return; if(Len < 3) { return; } Len += 3; UART_SendByte(0x1D); UART_SendByte(0x28); UART_SendByte(0x6B); tmp = (unsigned char)(Len & 0x00ff); UART_SendByte(tmp); tmp = (unsigned char)((Len >> 8)&0x00ff); UART_SendByte(tmp); UART_SendByte(0x31); UART_SendByte(0x50); UART_SendByte(0x30); Len -= 3; while(Len) { UART_SendByte(*pData++); Len--; } UART_SendByte(0x00); } /* QR Code 打印编码缓存的二维条码 a*/ void PrintQRCode(void) { if(!gucCheckPassWord) return; UART_SendByte(0x1D); UART_SendByte(0x28); UART_SendByte(0x6B); UART_SendByte(0x03); UART_SendByte(0x00); UART_SendByte(0x31); UART_SendByte(0x51); UART_SendByte(0x30); UART_SendByte(0x00); } /* ** 函数:void Barcode_sw(unsigned char mode) ** 参数:mode 0禁止,1启用 功能:条形码打印使能 */ void Barcode_sw(unsigned char mode) { UART_SendByte(0x1D); UART_SendByte(0x45); UART_SendByte(0x43); UART_SendByte(mode); }
#include <ctime> #include <cstdlib> #include <typeinfo> #include "Snap.h" int main(int argc, char* argv[]) { const clock_t begin_time = clock(); PUNGraph Graph = TSnap::LoadEdgeList<PUNGraph>("cit-Patents.txt", 0, 1); printf("time for reading cit-Patents.txt:"); printf("%g\n", float(clock() - begin_time) / CLOCKS_PER_SEC); TIntPrV count; printf("number of nodes: %i\n", Graph->GetNodes()); printf("number of edges: %d\n", Graph->GetEdges()); TSnap::DelSelfEdges(Graph); PUNGraph UGraph = TSnap::ConvertGraph<PUNGraph>(Graph); const clock_t begin_time5 = clock(); TKCore<PUNGraph> KCore(UGraph); printf("3-core:"); printf("%g\n", float(clock() - begin_time5) / CLOCKS_PER_SEC); }
#if 1 #include<iostream> using namespace std; enum Color { RED, BLACK }; struct Node { long long int data; bool color; Node *left, *right, *parent; long long int index; // number of noodes on the left side tree of this node. // Constructor Node(long long int data) { this->data = data; left = nullptr; right = nullptr; parent = nullptr; this->color = RED; } Node() { left = nullptr; right = nullptr; parent = nullptr; this->color = RED; } }; // Class to represent Red-Black Tree class RBTree { private: long long int size; Node *root; protected: void rotateLeft(Node *&, Node *&); void rotateRight(Node *&, Node *&); void fixRBTree(Node *&, Node *&); void BSTInsert(Node* data); void updateIndex(); public: // Constructor RBTree() { root = nullptr; } void insert(const long long int &n); long long int getIndex(long long int data); }; /* A utility function to insert a new node with given key in BST */ void RBTree::BSTInsert(Node* data) { size++; if (root == nullptr) { root = data; return; } Node* cur = root; while (1) { // only breaks when the node is allocated in its right place if (data->data <= cur->data) { if (cur->left == nullptr) { // allocates as the left node cur->left = data; cur->left->parent = cur; return; } // go deeper cur = cur->left; } else if (data->data > cur->data) { if (cur->right == nullptr) { // allocate as the right node cur->right = data; cur->right->parent = cur; return; } // go deeper cur = cur->right; } } } void RBTree::rotateLeft(Node *&root, Node *&pt) { Node *pt_right = pt->right; pt->right = pt_right->left; if (pt->right != nullptr) pt->right->parent = pt; pt_right->parent = pt->parent; if (pt->parent == nullptr) root = pt_right; else if (pt == pt->parent->left) pt->parent->left = pt_right; else pt->parent->right = pt_right; pt_right->left = pt; pt->parent = pt_right; } void RBTree::rotateRight(Node *&root, Node *&pt) { Node *pt_left = pt->left; pt->left = pt_left->right; if (pt->left != nullptr) pt->left->parent = pt; pt_left->parent = pt->parent; if (pt->parent == nullptr) root = pt_left; else if (pt == pt->parent->left) pt->parent->left = pt_left; else pt->parent->right = pt_left; pt_left->right = pt; pt->parent = pt_left; } // This function fixes violations caused by BST insertion void RBTree::fixRBTree(Node *&root, Node *&pt) { Node *parent_node = nullptr; Node *grand_parent_noded = nullptr; while ((pt != root) && (pt->color != BLACK) && (pt->parent->color == RED)) { parent_node = pt->parent; grand_parent_noded = pt->parent->parent; /* Case : A Parent of pt is left child of Grand-parent of pt */ if (parent_node == grand_parent_noded->left) { Node *uncle_pt = grand_parent_noded->right; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if (uncle_pt != nullptr && uncle_pt->color == RED) { grand_parent_noded->color = RED; parent_node->color = BLACK; uncle_pt->color = BLACK; pt = grand_parent_noded; } else { /* Case : 2 pt is right child of its parent Left-rotation required */ if (pt == parent_node->right) { rotateLeft(root, parent_node); pt = parent_node; parent_node = pt->parent; } /* Case : 3 pt is left child of its parent Right-rotation required */ rotateRight(root, grand_parent_noded); swap(parent_node->color, grand_parent_noded->color); pt = parent_node; } } /* Case : B Parent of pt is right child of Grand-parent of pt */ else { Node *uncle_pt = grand_parent_noded->left; /* Case : 1 The uncle of pt is also red Only Recoloring required */ if ((uncle_pt != nullptr) && (uncle_pt->color == RED)) { grand_parent_noded->color = RED; parent_node->color = BLACK; uncle_pt->color = BLACK; pt = grand_parent_noded; } else { /* Case : 2 pt is left child of its parent Right-rotation required */ if (pt == parent_node->left) { rotateRight(root, parent_node); pt = parent_node; parent_node = pt->parent; } /* Case : 3 pt is right child of its parent Left-rotation required */ rotateLeft(root, grand_parent_noded); swap(parent_node->color, grand_parent_noded->color); pt = parent_node; } } } root->color = BLACK; } // Function to insert a new node with given data void RBTree::insert(const long long int &data) { Node *pt = new Node(data); // Do a normal BST insert BSTInsert(pt); // fix Red Black Tree violations fixRBTree(root, pt); updateIndex(); } // a function uses the index variable in each node to get the general inde of a node in the full tree long long int RBTree::getIndex(long long int data) { Node* cur = root; long long int index = 0; long long int offset = 0; while (cur != nullptr) { if (data < cur->data) { if (cur->left == nullptr) { return -1; } //index = cur->left->index; cur = cur->left; } else if (data > cur->data) { if (cur->right == nullptr) { return -1; } offset += cur/*->right*/->index; cur = cur->right; } else { return size + 1 - (offset + index + cur->index); } } return -1; } long long int allRightNodes(Node*node) { if (node == nullptr) { return 0; } return node->index + allRightNodes(node->right); } // this function recursively update index of each node correctly. long long int updateIndexHelper(Node* node) { if (node == nullptr) { return 0; } node->index = 1 + updateIndexHelper(node->left); updateIndexHelper(node->right); if (node->right == nullptr) { return node->index; } return node->index + allRightNodes(node->right);//node->right->index; } void RBTree::updateIndex() { updateIndexHelper(root); } int main() { long long int op; long long int elem; RBTree bst; long long int res; long long int n; cin >> n; while (n--) { cin >> op; cin >> elem; switch (op) { case 1: bst.insert(elem); break; case 2: res = bst.getIndex(elem); if (res != -1) { cout << res << endl; } else { cout << "Data tidak ada" << endl; } break; } } return 0; } #endif
// // Created by zhongzhendong on 2018-12-28. // #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <vector> #include <map> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(int x, ListNode* n) : val(x), next(n) {} }; class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { auto result_head = ListNode(0); auto sum = 0, carry = 0; auto head = &result_head; while (l1 || l2) { sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry; head->next = new ListNode(sum % 10); carry = sum / 10; if (l1) l1 = l1->next; if (l2) l2 = l2->next; head = head->next; } if (carry > 0) { head->next = new ListNode(carry); } return result_head.next; } }; TEST_CASE("AddTwoNumbers") { auto num1 = new ListNode(1, new ListNode(4, new ListNode(3))); auto num2 = new ListNode(5, new ListNode(6, new ListNode(4))); auto res = Solution().addTwoNumbers(num1, num2); REQUIRE(res->val == 6); REQUIRE(res->next->val == 0); REQUIRE(res->next->next->val == 8); num1 = new ListNode(1, new ListNode(8)); num2 = new ListNode(0); res = Solution().addTwoNumbers(num1, num2); REQUIRE(res->val == 1); REQUIRE(res->next->val == 8); }
//$Id: SolverVariablesPanel.cpp 9514 2011-04-30 21:44:00Z djcinsb $ //------------------------------------------------------------------------------ // SolverVariablesPanel //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Author: Waka Waktola // Created: 2004/21/01 // Modified: 2004/05/06 by Allison Greene to inherit from GmatPanel /** * This class contains the Solver Variables window. */ //------------------------------------------------------------------------------ #include "gmatwxdefs.hpp" #include "GmatAppData.hpp" #include "SolverVariablesPanel.hpp" // base includes #include "gmatdefs.hpp" #include "GuiInterpreter.hpp" //------------------------------------------------------------------------------ // event tables and other macros for wxWindows //------------------------------------------------------------------------------ BEGIN_EVENT_TABLE(SolverVariablesPanel, GmatPanel) EVT_BUTTON(ID_BUTTON, SolverVariablesPanel::OnButton) EVT_TEXT(ID_TEXTCTRL, SolverVariablesPanel::OnTextUpdate) EVT_COMBOBOX(ID_COMBO, SolverVariablesPanel::OnSolverSelection) EVT_GRID_CELL_CHANGE(SolverVariablesPanel::OnCellValueChanged) END_EVENT_TABLE() //------------------------------------------------------------------------------ // SolverVariablesPanel() //------------------------------------------------------------------------------ /** * A constructor. */ //------------------------------------------------------------------------------ SolverVariablesPanel::SolverVariablesPanel(wxWindow *parent) : GmatPanel(parent) { Create(); Show(); } SolverVariablesPanel::~SolverVariablesPanel() { } //------------------------------- // private methods //------------------------------- void SolverVariablesPanel::Create() { Initialize(); Setup(this); } void SolverVariablesPanel::LoadData() { // explicitly disable apply button // it is turned on in each of the panels EnableUpdate(false); } void SolverVariablesPanel::SaveData() { // explicitly disable apply button // it is turned on in each of the panels EnableUpdate(false); } void SolverVariablesPanel::Initialize() { numOfVars = 20; // TBD nextRow = 0; } void SolverVariablesPanel::Setup( wxWindow *parent) { // wxGrid varsGrid = new wxGrid( parent, ID_GRID, wxDefaultPosition, wxSize(600,160), wxWANTS_CHARS ); varsGrid->CreateGrid( numOfVars, 3, wxGrid::wxGridSelectCells ); varsGrid->SetColSize(0, 150); varsGrid->SetColSize(1, 585); varsGrid->SetColSize(2, 585); varsGrid->SetColLabelValue(0, _T("Solver")); varsGrid->SetColLabelValue(1, _T("Property")); varsGrid->SetColLabelValue(2, _T("Description")); varsGrid->SetRowLabelSize(0); // wxStaticText descStaticText = new wxStaticText( parent, ID_TEXT, wxT("Description"), wxDefaultPosition, wxDefaultSize, 0 ); solverStaticText = new wxStaticText( parent, ID_TEXT, wxT("Solver"), wxDefaultPosition, wxDefaultSize, 0 ); varStaticText = new wxStaticText( parent, ID_TEXT, wxT("Variable"), wxDefaultPosition, wxDefaultSize, 0 ); pertStaticText = new wxStaticText( parent, ID_TEXT, wxT("Perturbation"), wxDefaultPosition, wxDefaultSize, 0 ); maxStaticText = new wxStaticText( parent, ID_TEXT, wxT("Max Step"), wxDefaultPosition, wxDefaultSize, 0 ); lowerStaticText = new wxStaticText( parent, ID_TEXT, wxT("Lower Bound"), wxDefaultPosition, wxDefaultSize, 0 ); upperStaticText = new wxStaticText( parent, ID_TEXT, wxT("Upper Bound"), wxDefaultPosition, wxDefaultSize, 0 ); // wxTextCtrl descTextCtrl = new wxTextCtrl( parent, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(400,-1), 0 ); varTextCtrl = new wxTextCtrl( parent, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(400,-1), 0 ); pertTextCtrl = new wxTextCtrl( parent, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(80,-1), 0 ); maxTextCtrl = new wxTextCtrl( parent, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(80,-1), 0 ); lowerTextCtrl = new wxTextCtrl( parent, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(80,-1), 0 ); upperTextCtrl = new wxTextCtrl( parent, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(80,-1), 0 ); // wxString wxString strArray1[] = { wxT("") }; // wxComboBox solverComboBox = new wxComboBox( parent, ID_COMBO, wxT(strArray1[0]), wxDefaultPosition, wxSize(200,-1), 0, strArray1, wxCB_DROPDOWN|wxCB_READONLY ); // wxButton editButton = new wxButton( parent, ID_BUTTON, wxT("Edit"), wxDefaultPosition, wxDefaultSize, 0 ); updateButton = new wxButton( parent, ID_BUTTON, wxT("Update"), wxDefaultPosition, wxDefaultSize, 0 ); // wx*Sizers wxBoxSizer *item0 = new wxBoxSizer( wxVERTICAL ); wxStaticBox *item2 = new wxStaticBox( parent, -1, wxT("Variable List") ); wxStaticBoxSizer *item1 = new wxStaticBoxSizer( item2, wxVERTICAL ); wxStaticBox *item5 = new wxStaticBox( parent, -1, wxT("Variable Setup") ); wxStaticBoxSizer *item4 = new wxStaticBoxSizer( item5, wxVERTICAL ); wxFlexGridSizer *item6 = new wxFlexGridSizer( 3, 0, 0 ); item6->AddGrowableCol( 1 ); wxStaticBox *item15 = new wxStaticBox( parent, -1, wxT("Settings") ); wxStaticBoxSizer *item14 = new wxStaticBoxSizer( item15, wxHORIZONTAL ); wxGridSizer *item16 = new wxGridSizer( 4, 0, 0 ); // Add to wx*Sizers item1->Add( varsGrid, 0, wxALIGN_CENTER|wxALL, 5 ); item6->Add( descStaticText, 0, wxALIGN_CENTER|wxALL, 5 ); item6->Add( descTextCtrl, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5 ); item6->Add( 20, 20, 0, wxALIGN_CENTER|wxALL, 5 ); item6->Add( solverStaticText, 0, wxALIGN_CENTER|wxALL, 5 ); item6->Add( solverComboBox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); item6->Add( 20, 20, 0, wxALIGN_CENTER|wxALL, 5 ); item6->Add( varStaticText, 0, wxALIGN_CENTER|wxALL, 5 ); item6->Add( varTextCtrl, 0, wxALIGN_CENTER|wxALL, 5 ); item6->Add( editButton, 0, wxALIGN_CENTER|wxALL, 5 ); item16->Add( pertStaticText, 0, wxALIGN_CENTER|wxALL, 5 ); item16->Add( maxStaticText, 0, wxALIGN_CENTER|wxALL, 5 ); item16->Add( lowerStaticText, 0, wxALIGN_CENTER|wxALL, 5 ); item16->Add( upperStaticText, 0, wxALIGN_CENTER|wxALL, 5 ); item16->Add( pertTextCtrl, 0, wxALIGN_CENTER|wxALL, 5 ); item16->Add( maxTextCtrl, 0, wxALIGN_CENTER|wxALL, 5 ); item16->Add( lowerTextCtrl, 0, wxALIGN_CENTER|wxALL, 5 ); item16->Add( upperTextCtrl, 0, wxALIGN_CENTER|wxALL, 5 ); item14->Add( item16, 0, wxGROW|wxALIGN_CENTER_HORIZONTAL|wxALL, 5 ); item4->Add( item6, 0, wxALIGN_CENTER|wxALL, 5 ); item4->Add( item14, 0, wxALIGN_CENTER|wxALL, 5 ); item4->Add( updateButton, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5 ); item0->Add( item1, 0, wxALIGN_CENTER|wxALL, 5 ); item0->Add( item4, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); theMiddleSizer->Add(item0, 0, wxGROW, 5); } void SolverVariablesPanel::OnTextUpdate(wxCommandEvent& event) { if ( event.GetEventObject() == descTextCtrl ) { EnableUpdate(true); } else if ( event.GetEventObject() == varTextCtrl ) { EnableUpdate(true); } else if ( event.GetEventObject() == pertTextCtrl ) { EnableUpdate(true); } else if ( event.GetEventObject() == maxTextCtrl ) { EnableUpdate(true); } else if ( event.GetEventObject() == lowerTextCtrl ) { EnableUpdate(true); } else if ( event.GetEventObject() == upperTextCtrl ) { EnableUpdate(true); } else event.Skip(); } void SolverVariablesPanel::OnSolverSelection(wxCommandEvent &event) { EnableUpdate(true); } void SolverVariablesPanel::OnButton(wxCommandEvent& event) { if ( event.GetEventObject() == editButton ) { // Bring up the VariableCreatePanel EnableUpdate(true); } else if ( event.GetEventObject() == updateButton ) { solverString = solverComboBox->GetStringSelection(); propertyString = varTextCtrl->GetValue(); descriptionString = descTextCtrl->GetValue(); varsGrid->SetCellValue(nextRow, SOL_COL, solverString); varsGrid->SetCellValue(nextRow, PRO_COL, propertyString); varsGrid->SetCellValue(nextRow, DES_COL, descriptionString); nextRow++; EnableUpdate(true); } else event.Skip(); } void SolverVariablesPanel::OnCellValueChanged(wxGridEvent &event) { EnableUpdate(true); }
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QWebEngineView> #include <QLineEdit> #include <QNetworkRequest> #include <QNetworkReply> #include <QNetworkAccessManager> #include <QListWidget> #include <QWebEngineHistory> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); view = new QWebEngineView(this); view->load(QUrl("http://www.qter.org/")); setCentralWidget(view); resize(1024, 680); progress = 0; // 关联信号和槽 connect(view, &QWebEngineView::loadProgress, this, &MainWindow::setProgress); connect(view, &QWebEngineView::titleChanged, this, &MainWindow::adjustTitle); connect(view, &QWebEngineView::loadFinished, this, &MainWindow::finishLoading); locationEdit = new QLineEdit(this); locationEdit->setText("http://www.qter.org/"); connect(locationEdit, &QLineEdit::returnPressed, this, &MainWindow::changeLocation); // 向工具栏添加动作和部件 ui->mainToolBar->addAction(view->pageAction(QWebEnginePage::Back)); ui->mainToolBar->addAction(view->pageAction(QWebEnginePage::Forward)); ui->mainToolBar->addAction(view->pageAction(QWebEnginePage::Reload)); ui->mainToolBar->addAction(view->pageAction(QWebEnginePage::Stop)); ui->mainToolBar->addWidget(locationEdit); connect(view, &QWebEngineView::iconUrlChanged, this, &MainWindow::handleIconUrlChanged); manager = new QNetworkAccessManager(this); QMenu *viewMenu = new QMenu(tr("查看")); QAction *zoomIn = viewMenu->addAction(tr("放大")); zoomIn->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Plus)); connect(zoomIn, &QAction::triggered, [this]() { view->setZoomFactor(view->zoomFactor() + 0.1); ui->statusBar->showMessage(tr("缩放%1%").arg(view->zoomFactor()*100)); }); QAction *zoomOut = viewMenu->addAction(tr("缩小")); zoomOut->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Minus)); connect(zoomOut, &QAction::triggered, [this]() { view->setZoomFactor(view->zoomFactor() - 0.1); ui->statusBar->showMessage(tr("缩放%1%").arg(view->zoomFactor()*100)); }); QAction *resetZoom = viewMenu->addAction(tr("重置")); resetZoom->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_0)); connect(resetZoom, &QAction::triggered, [this]() { view->setZoomFactor(1.0); ui->statusBar->showMessage(tr("缩放%1%").arg(view->zoomFactor()*100)); }); menuBar()->addMenu(viewMenu); ui->mainToolBar->addAction(tr("历史"), this, SLOT(showHistory())); historyList = new QListWidget; historyList->setWindowTitle(tr("历史记录")); historyList->setMinimumWidth(300); connect(historyList, &QListWidget::clicked, this, &MainWindow::gotoHistory); } MainWindow::~MainWindow() { delete ui; } // 地址栏按下回车处理槽 void MainWindow::changeLocation() { QUrl url = QUrl(locationEdit->text()); view->load(url); view->setFocus(); } void MainWindow::setProgress(int p) { progress = p; adjustTitle(); } // 调整标题槽 void MainWindow::adjustTitle() { if ( progress <= 0 || progress >= 100) { setWindowTitle(view->title()); } else { setWindowTitle(QString("%1 (%2%)").arg(view->title()).arg(progress)); } } // 加载完成处理槽 void MainWindow::finishLoading(bool finished) { if (finished) { progress = 100; setWindowTitle(view->title()); } else { setWindowTitle("web page loading error!"); } } // 获取图标文件 void MainWindow::handleIconUrlChanged(const QUrl &url) { QNetworkRequest iconRequest(url); QNetworkReply *iconReply = manager->get(iconRequest); iconReply->setParent(this); connect(iconReply, &QNetworkReply::finished, this, &MainWindow::handleIconLoaded); } // 对获取的图标文件进行处理 void MainWindow::handleIconLoaded() { QIcon icon; QNetworkReply *iconReply = qobject_cast<QNetworkReply*>(sender()); if (iconReply && iconReply->error() == QNetworkReply::NoError) { QByteArray data = iconReply->readAll(); QPixmap pixmap; pixmap.loadFromData(data); icon.addPixmap(pixmap); iconReply->deleteLater(); } else { icon = QIcon(QStringLiteral("../mywebengine/defaulticon.png")); } setWindowIcon(icon); } // 显示历史记录窗口 void MainWindow::showHistory() { historyList->clear(); foreach (QWebEngineHistoryItem item, view->history()->items()) { QListWidgetItem *history = new QListWidgetItem(item.title()); historyList->addItem(history); } historyList->show(); } // 跳转到记录 void MainWindow::gotoHistory(const QModelIndex &index) { QWebEngineHistoryItem item = view->history()->itemAt(index.row()); view->history()->goToItem(item); }
// Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "uritests.h" #include "guiutil.h" #include "walletmodel.h" #include <QUrl> void URITests::uriTests() { SendCoinsRecipient rv; QUrl uri; uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?req-dontexist=")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?dontexist=")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 0); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?label=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString("Some Example Address")); QVERIFY(rv.amount == 0); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=0.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100000); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=1.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100100000); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=100&label=Some Example")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Some Example")); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?message=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString()); QVERIFY(GUIUtil::parseBitcoinURI("zoow://XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?message=Some Example Address", &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString()); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?req-message=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=1,000&label=Some Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=1,000.0&label=Some Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=100&label=Some Example&message=Some Example Message&IS=1")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Some Example")); QVERIFY(rv.message == QString("Some Example Message")); QVERIFY(rv.fUseInstantSend == 1); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=100&label=Some Example&message=Some Example Message&IS=Something Invalid")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Some Example")); QVERIFY(rv.message == QString("Some Example Message")); QVERIFY(rv.fUseInstantSend != 1); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?IS=1")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.fUseInstantSend == 1); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?IS=0")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.fUseInstantSend != 1); uri.setUrl(QString("zoow:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.fUseInstantSend != 1); }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "alert.h" #include "checkpoints.h" #include "db.h" #include "txdb.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include "kernel.h" #include "zerocoin/Zerocoin.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> using namespace std; using namespace boost; // // Global state // CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; CTxMemPool mempool; unsigned int nTransactionsUpdated = 0; map<uint256, CBlockIndex*> mapBlockIndex; set<pair<COutPoint, unsigned int> > setStakeSeen; libzerocoin::Params* ZCParams; CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty CBigNum bnProofOfStakeLimit(~uint256(0) >> 20); CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16); unsigned int nTargetSpacing = 1 * 60; // 1 minute unsigned int nStakeMinAge = 1 * 60 * 60; unsigned int nStakeMaxAge = -1; // unlimited unsigned int nModifierInterval = 10 * 60; // time to elapse before new modifier is computed int nCoinbaseMaturity = 10; CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; uint256 nBestChainTrust = 0; uint256 nBestInvalidTrust = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64_t nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; set<pair<COutPoint, unsigned int> > setStakeSeenOrphan; map<uint256, CTransaction> mapOrphanTransactions; map<uint256, set<uint256> > mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = "LoanOrLease Signed Message:\n"; // Settings int64_t nTransactionFee = MIN_TX_FEE; int64_t nReserveBalance = 0; int64_t nMinimumInputValue = 0; extern enum Checkpoints::CPMode CheckpointsMode; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect) { if (!fConnect) { // ppcoin: wallets need to refund inputs when disconnecting coinstake if (tx.IsCoinStake()) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) pwallet->DisableTransaction(tx); } return; } BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void ResendWalletTransactions(bool fForce) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(fForce); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CTransaction& tx) { uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); if (nSize > 5000) { printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str()); return false; } mapOrphanTransactions[hash] = tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash); printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(), mapOrphanTransactions.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CTransaction& tx = mapOrphanTransactions[hash]; BOOST_FOREACH(const CTxIn& txin, tx.vin) { mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) mapOrphanTransactionsByPrev.erase(txin.prevout.hash); } mapOrphanTransactions.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } ////////////////////////////////////////////////////////////////////////////// // // CTransaction and CTxIndex // bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(prevout.hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool IsStandardTx(const CTransaction& tx) { if (tx.nVersion > CTransaction::CURRENT_VERSION) return false; // Treat non-final transactions as non-standard to prevent a specific type // of double-spend attack, as well as DoS attacks. (if the transaction // can't be mined, the attacker isn't expending resources broadcasting it) // Basically we don't want to propagate transactions that can't included in // the next block. // // However, IsFinalTx() is confusing... Without arguments, it uses // chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height() // is set to the value of nHeight in the block. However, when IsFinalTx() // is called within CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a transaction can // be part of the *next* block, we need to call IsFinalTx() with one more // than chainActive.Height(). // // Timestamps on the other hand don't get any special treatment, because we // can't know what timestamp the next block will have, and there aren't // timestamp applications where it matters. if (!IsFinalTx(tx, nBestHeight + 1)) { return false; } // nTime has different purpose from nLockTime but can be used in similar attacks if (tx.nTime > FutureDrift(GetAdjustedTime())) { return false; } // Extremely large transactions with lots of inputs can cost the network // almost as much to process as they cost the sender in fees, because // computing signature hashes is O(ninputs*txsize). Limiting transactions // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks. unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); if (sz >= MAX_STANDARD_TX_SIZE) return false; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; if (fEnforceCanonical && !txin.scriptSig.HasCanonicalPushes()) { return false; } } unsigned int nDataOut = 0; txnouttype whichType; BOOST_FOREACH(const CTxOut& txout, tx.vout) { if (!::IsStandard(txout.scriptPubKey, whichType)) return false; if (whichType == TX_NULL_DATA) nDataOut++; if (txout.nValue == 0) return false; if (fEnforceCanonical && !txout.scriptPubKey.HasCanonicalPushes()) { return false; } } // only one OP_RETURN txout is permitted if (nDataOut > 1) { return false; } return true; } bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime) { AssertLockHeld(cs_main); // Time based nLockTime implemented in 0.1.6 if (tx.nLockTime == 0) return true; if (nBlockHeight == 0) nBlockHeight = nBestHeight; if (nBlockTime == 0) nBlockTime = GetAdjustedTime(); if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) return true; BOOST_FOREACH(const CTxIn& txin, tx.vin) if (!txin.IsFinal()) return false; return true; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int CTransaction::GetLegacySigOpCount() const { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { AssertLockHeld(cs_main); CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64_t nValueOut = 0; for (unsigned int i = 0; i < vout.size(); i++) { const CTxOut& txout = vout[i]; if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake()) return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction")); if (txout.nValue < 0) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative")); if (txout.nValue > MAX_MONEY) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high")); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } int64_t CTransaction::GetMinFee(unsigned int nBlockSize, enum GetMinFee_mode mode, unsigned int nBytes) const { // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE int64_t nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE; unsigned int nNewBlockSize = nBlockSize + nBytes; int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee; // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01 if (nMinFee < nBaseFee) { BOOST_FOREACH(const CTxOut& txout, vout) if (txout.nValue < CENT) nMinFee = nBaseFee; } // Raise the price as the block approaches full if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2) { if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN) return MAX_MONEY; nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize); } if (!MoneyRange(nMinFee)) nMinFee = MAX_MONEY; return nMinFee; } bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool* pfMissingInputs) { AssertLockHeld(cs_main); if (pfMissingInputs) *pfMissingInputs = false; if (!tx.CheckTransaction()) return error("AcceptToMemoryPool : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return tx.DoS(100, error("AcceptToMemoryPool : coinbase as individual tx")); // ppcoin: coinstake is also only valid in a block, not as a loose transaction if (tx.IsCoinStake()) return tx.DoS(100, error("AcceptToMemoryPool : coinstake as individual tx")); // Rather not work on nonstandard transactions (unless -testnet) if (!fTestNet && !IsStandardTx(tx)) return error("AcceptToMemoryPool : nonstandard transaction type"); // is it already in the memory pool? uint256 hash = tx.GetHash(); if (pool.exists(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; { LOCK(pool.cs); // protect pool.mapNextTx for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (pool.mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = pool.mapNextTx[outpoint].ptx; if (IsFinalTx(*ptxOld)) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!pool.mapNextTx.count(outpoint) || pool.mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } } { CTxDB txdb("r"); // do we already have it? if (txdb.ContainsTx(hash)) return false; MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("AcceptToMemoryPool : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return false; } // Check for non-standard pay-to-script-hash in inputs if (!tx.AreInputsStandard(mapInputs) && !fTestNet) return error("AcceptToMemoryPool : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block int64_t txMinFee = tx.GetMinFee(1000, GMF_RELAY, nSize); if (nFees < txMinFee) return error("AcceptToMemoryPool : not enough fees %s, %"PRId64" < %"PRId64, hash.ToString().c_str(), nFees, txMinFee); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make others' transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEE) { static CCriticalSection cs; static double dFreeCount; static int64_t nLastTime; int64_t nNow = GetTime(); { LOCK(pool.cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) return error("AcceptToMemoryPool : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("AcceptToMemoryPool : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory { LOCK(pool.cs); if (ptxOld) { printf("AcceptToMemoryPool : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); pool.remove(*ptxOld); } pool.addUnchecked(hash, tx); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("AcceptToMemoryPool : accepted %s (poolsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(), pool.mapTx.size()); return true; } bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx) { // Add to memory pool without checking anything. Don't call this directly, // call AcceptToMemoryPool to properly check the transaction first. { mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); nTransactionsUpdated++; } return true; } bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { if (fRecursive) { for (unsigned int i = 0; i < tx.vout.size(); i++) { std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i)); if (it != mapNextTx.end()) remove(*it->second.ptx, true); } } BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); nTransactionsUpdated++; } } return true; } bool CTxMemPool::removeConflicts(const CTransaction &tx) { // Remove transactions which depend on inputs of tx, recursively LOCK(cs); BOOST_FOREACH(const CTxIn &txin, tx.vin) { std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout); if (it != mapNextTx.end()) { const CTransaction &txConflict = *it->second.ptx; if (txConflict != tx) remove(txConflict, true); } } return true; } void CTxMemPool::clear() { LOCK(cs); mapTx.clear(); mapNextTx.clear(); ++nTransactionsUpdated; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; AssertLockHeld(cs_main); // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { AssertLockHeld(cs_main); int nResult = GetDepthInMainChainINTERNAL(pindexRet); if (nResult == 0 && !mempool.exists(GetHash())) return -1; // Not in chain, not in mempool return nResult; } int CMerkleTx::GetBlocksToMaturity() const { if (!(IsCoinBase() || IsCoinStake())) return 0; return max(0, (nCoinbaseMaturity+0) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool() { return ::AcceptToMemoryPool(mempool, *this, NULL); } bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb) { { // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!(tx.IsCoinBase() || tx.IsCoinStake())) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(); } } return AcceptToMemoryPool(); } return false; } bool CWalletTx::AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { if (mempool.lookup(hash, tx)) { return true; } } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // static CBlockIndex* pblockindexFBBHLast; CBlockIndex* FindBlockByHeight(int nHeight) { CBlockIndex *pblockindex; if (nHeight < nBestHeight / 2) pblockindex = pindexGenesisBlock; else pblockindex = pindexBest; if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight)) pblockindex = pblockindexFBBHLast; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; while (pblockindex->nHeight < nHeight) pblockindex = pblockindex->pnext; pblockindexFBBHLast = pblockindex; return pblockindex; } bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } // ppcoin: find block wanted by given orphan block uint256 WantedByOrphan(const CBlock* pblockOrphan) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock)) pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock]; return pblockOrphan->hashPrevBlock; } // miner's coin base reward int64_t GetProofOfWorkReward(int64_t nFees) { int64_t nSubsidy = 3 * COIN; if(nBestHeight == 0) { nSubsidy = 2940000 * COIN; } if (fDebug && GetBoolArg("-printcreation")) printf("GetProofOfWorkReward() : create=%s nSubsidy=%"PRId64"\n", FormatMoney(nSubsidy).c_str(), nSubsidy); return nSubsidy + nFees; } // miner's coin stake reward based on coin age spent (coin-days) int64_t GetProofOfStakeReward(int64_t nCoinAge, int64_t nFees) { int64_t nSubsidy = nCoinAge * COIN_YEAR_REWARD * 33 / (365 * 33 + 8); if (fDebug && GetBoolArg("-printcreation")) printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRId64"\n", FormatMoney(nSubsidy).c_str(), nCoinAge); return nSubsidy + nFees; } static const int64_t nTargetTimespan = 16 * 60; // 16 mins // // maximum nBits value could possible be required nTime after // unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime) { CBigNum bnResult; bnResult.SetCompact(nBase); bnResult *= 2; while (nTime > 0 && bnResult < bnTargetLimit) { // Maximum 200% adjustment per day... bnResult *= 2; nTime -= 24 * 60 * 60; } if (bnResult > bnTargetLimit) bnResult = bnTargetLimit; return bnResult.GetCompact(); } // // minimum amount of work that could possibly be required nTime after // minimum proof-of-work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime) { return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime); } // // minimum amount of stake that could possibly be required nTime after // minimum proof-of-stake required was nBase // unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime) { return ComputeMaxBits(bnProofOfStakeLimit, nBase, nTime); } // ppcoin: find last block index up to pindex const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake) { while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake)) pindex = pindex->pprev; return pindex; } static unsigned int GetNextTargetRequiredV1(const CBlockIndex* pindexLast, bool fProofOfStake) { CBigNum bnTargetLimit = fProofOfStake ? bnProofOfStakeLimit : bnProofOfWorkLimit; if (pindexLast == NULL) return bnTargetLimit.GetCompact(); // genesis block const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake); if (pindexPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // first block const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake); if (pindexPrevPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // second block int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime(); // ppcoin: target change every block // ppcoin: retarget with exponential moving toward target spacing CBigNum bnNew; bnNew.SetCompact(pindexPrev->nBits); int64_t nInterval = nTargetTimespan / nTargetSpacing; bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing); bnNew /= ((nInterval + 1) * nTargetSpacing); if (bnNew > bnTargetLimit) bnNew = bnTargetLimit; return bnNew.GetCompact(); } static unsigned int GetNextTargetRequiredV2(const CBlockIndex* pindexLast, bool fProofOfStake) { CBigNum bnTargetLimit = fProofOfStake ? bnProofOfStakeLimit : bnProofOfWorkLimit; if (pindexLast == NULL) return bnTargetLimit.GetCompact(); // genesis block const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake); if (pindexPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // first block const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake); if (pindexPrevPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // second block int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime(); if (nActualSpacing < 0) nActualSpacing = nTargetSpacing; // ppcoin: target change every block // ppcoin: retarget with exponential moving toward target spacing CBigNum bnNew; bnNew.SetCompact(pindexPrev->nBits); int64_t nInterval = nTargetTimespan / nTargetSpacing; bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing); bnNew /= ((nInterval + 1) * nTargetSpacing); if (bnNew <= 0 || bnNew > bnTargetLimit) bnNew = bnTargetLimit; return bnNew.GetCompact(); } unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake) { if (pindexLast->nHeight < 10000) return GetNextTargetRequiredV1(pindexLast, fProofOfStake); else return GetNextTargetRequiredV2(pindexLast, fProofOfStake); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { LOCK(cs_main); if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64_t nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 15 && pindexBest->GetBlockTime() < GetTime() - 8 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->nChainTrust > nBestInvalidTrust) { nBestInvalidTrust = pindexNew->nChainTrust; CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust)); uiInterface.NotifyBlocksChanged(); } uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust; uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust; printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRId64" date=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(), DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str()); printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRId64" date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(pindexBest->nChainTrust).ToString().c_str(), nBestBlockTrust.Get64(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(GetBlockTime(), GetAdjustedTime()); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anyway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory if (!mempool.lookup(prevout.hash, txPrev)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n indexes are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64_t nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal bitcoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64_t nValueIn = 0; int64_t nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase or coinstake, check that it's matured if (txPrev.IsCoinBase() || txPrev.IsCoinStake()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight); // ppcoin: check transaction timestamp if (txPrev.nTime > nTime) return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction")); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, 0)) { return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (!IsCoinStake()) { if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64_t nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); // enforce transaction fees for every block if (nTxFee < GetMinFee()) return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false; nFees += nTxFee; if (!MoneyRange(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i--) if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } // ppcoin: clean up wallet after disconnecting coinstake BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, false, false); return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck) { // Check it again in case a previous version let a bad block in, but skip BlockSig checking if (!CheckBlock(!fJustCheck, !fJustCheck, false)) return false; //// issue here: it doesn't know the version unsigned int nTxPos; if (fJustCheck) // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator // Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from nTxPos = 1; else nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64_t nFees = 0; int64_t nValueIn = 0; int64_t nValueOut = 0; int64_t nStakeReward = 0; unsigned int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { uint256 hashTx = tx.GetHash(); // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction ids entirely. // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC. // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the // two in the chain that violate it. This prevents exploiting the issue against nodes in their // initial block download. CTxIndex txindexOld; if (txdb.ReadTxIndex(hashTx, txindexOld)) { BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); if (!fJustCheck) nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); MapPrevTx mapInputs; if (tx.IsCoinBase()) nValueOut += tx.GetValueOut(); else { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); int64_t nTxValueIn = tx.GetValueIn(mapInputs); int64_t nTxValueOut = tx.GetValueOut(); nValueIn += nTxValueIn; nValueOut += nTxValueOut; if (!tx.IsCoinStake()) nFees += nTxValueIn - nTxValueOut; if (tx.IsCoinStake()) nStakeReward = nTxValueOut - nTxValueIn; if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false)) return false; } mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size()); } if (IsProofOfWork()) { int64_t nReward = GetProofOfWorkReward(nFees); // Check coinbase reward if (vtx[0].GetValueOut() > nReward) return DoS(50, error("ConnectBlock() : coinbase reward exceeded (actual=%"PRId64" vs calculated=%"PRId64")", vtx[0].GetValueOut(), nReward)); } if (IsProofOfStake()) { // ppcoin: coin stake tx earns reward instead of paying fee uint64_t nCoinAge; if (!vtx[1].GetCoinAge(txdb, nCoinAge)) return error("ConnectBlock() : %s unable to get coin age for coinstake", vtx[1].GetHash().ToString().substr(0,10).c_str()); int64_t nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, nFees); if (nStakeReward > nCalculatedStakeReward) return DoS(100, error("ConnectBlock() : coinstake pays too much(actual=%"PRId64" vs calculated=%"PRId64")", nStakeReward, nCalculatedStakeReward)); } // ppcoin: track money supply and mint amount info pindex->nMint = nValueOut - nValueIn + nFees; pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn; if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex))) return error("Connect() : WriteBlockIndex for pindex failed"); if (fJustCheck) return true; // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); // Disconnect shorter branch list<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); // Queue memory transactions to resurrect. // We only do this for blocks after the last checkpoint (reorganisation before that // point should only happen with -reindex/-loadblock, or a misbehaving peer. BOOST_REVERSE_FOREACH(const CTransaction& tx, block.vtx) if (!(tx.IsCoinBase() || tx.IsCoinStake()) && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate()) vResurrect.push_front(tx); } // Connect longer branch vector<CTransaction> vDelete; for (unsigned int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) AcceptToMemoryPool(mempool, tx, NULL); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) { mempool.remove(tx); mempool.removeConflicts(tx); } printf("REORGANIZE: done\n"); return true; } // Called from inside SetBestChain: attaches a block to the new best chain being built bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew) { uint256 hash = GetHash(); // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return false; } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) mempool.remove(tx); return true; } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); if (!txdb.TxnBegin()) return error("SetBestChain() : TxnBegin failed"); if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { if (!SetBestChainInner(txdb, pindexNew)) return error("SetBestChain() : SetBestChainInner failed"); } else { // the first block in the new chain that will cause it to become the new best chain CBlockIndex *pindexIntermediate = pindexNew; // list of blocks that need to be connected afterwards std::vector<CBlockIndex*> vpindexSecondary; // Reorganize is costly in terms of db load, as it works in a single db transaction. // Try to limit how much needs to be done inside while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust) { vpindexSecondary.push_back(pindexIntermediate); pindexIntermediate = pindexIntermediate->pprev; } if (!vpindexSecondary.empty()) printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size()); // Switch to new best branch if (!Reorganize(txdb, pindexIntermediate)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } // Connect further blocks BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary) { CBlock block; if (!block.ReadFromDisk(pindex)) { printf("SetBestChain() : ReadFromDisk failed\n"); break; } if (!txdb.TxnBegin()) { printf("SetBestChain() : TxnBegin 2 failed\n"); break; } // errors now are not fatal, we still did a reorganisation to a new chain in a valid way if (!block.SetBestChainInner(txdb, pindex)) break; } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; pblockindexFBBHLast = NULL; nBestHeight = pindexBest->nHeight; nBestChainTrust = pindexNew->nChainTrust; nTimeBestReceived = GetTime(); nTransactionsUpdated++; uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust; printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRId64" date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(), nBestBlockTrust.Get64(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); // Check the version of the last 100 blocks to see if we need to upgrade: if (!fIsInitialDownload) { int nUpgraded = 0; const CBlockIndex* pindex = pindexBest; for (int i = 0; i < 100 && pindex != NULL; i++) { if (pindex->nVersion > CBlock::CURRENT_VERSION) ++nUpgraded; pindex = pindex->pprev; } if (nUpgraded > 0) printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION); if (nUpgraded > 100/2) // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: strMiscWarning = _("Warning: This version is obsolete, upgrade required!"); } std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } // ppcoin: total coin age spent in transaction, in the unit of coin-days. // Only those coins meeting minimum age requirement counts. As those // transactions not in main chain are not currently indexed so we // might not find out about their coin age. Older transactions are // guaranteed to be in main chain by sync-checkpoint. This rule is // introduced to help nodes establish a consistent view of the coin // age (trust score) of competing branches. bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const { CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds nCoinAge = 0; if (IsCoinBase()) return true; BOOST_FOREACH(const CTxIn& txin, vin) { // First try finding the previous transaction in database CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) continue; // previous transaction not in main chain if (nTime < txPrev.nTime) return false; // Transaction timestamp violation // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return false; // unable to read block of previous transaction if (block.GetBlockTime() + nStakeMinAge > nTime) continue; // only count coins meeting min age requirement int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue; bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT; if (fDebug && GetBoolArg("-printcoinage")) printf("coin age nValueIn=%"PRId64" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str()); } CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60); if (fDebug && GetBoolArg("-printcoinage")) printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str()); nCoinAge = bnCoinDay.getuint64(); return true; } // ppcoin: total coin age spent in block, in the unit of coin-days. bool CBlock::GetCoinAge(uint64_t& nCoinAge) const { nCoinAge = 0; CTxDB txdb("r"); BOOST_FOREACH(const CTransaction& tx, vtx) { uint64_t nTxCoinAge; if (tx.GetCoinAge(txdb, nTxCoinAge)) nCoinAge += nTxCoinAge; else return false; } if (nCoinAge == 0) // block coin age minimum 1 coin-day nCoinAge = 1; if (fDebug && GetBoolArg("-printcoinage")) printf("block coin age total nCoinDays=%"PRId64"\n", nCoinAge); return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, const uint256& hashProof) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); pindexNew->phashBlock = &hash; map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } // ppcoin: compute chain trust score pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust(); // ppcoin: compute stake entropy bit for stake modifier if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit())) return error("AddToBlockIndex() : SetStakeEntropyBit() failed"); // Record proof hash value pindexNew->hashProof = hashProof; // ppcoin: compute stake modifier uint64_t nStakeModifier = 0; bool fGeneratedStakeModifier = false; if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier)) return error("AddToBlockIndex() : ComputeNextStakeModifier() failed"); pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier); pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew); if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum)) return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRIx64, pindexNew->nHeight, nStakeModifier); // Add to mapBlockIndex map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; if (pindexNew->IsProofOfStake()) setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime)); pindexNew->phashBlock = &((*mi).first); // Write to disk block index CTxDB txdb; if (!txdb.TxnBegin()) return false; txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; LOCK(cs_main); // New best if (pindexNew->nChainTrust > nBestChainTrust) if (!SetBestChain(txdb, pindexNew)) return false; if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = vtx[0].GetHash(); } uiInterface.NotifyBlocksChanged(); return true; } bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetPoWHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > FutureDrift(GetAdjustedTime())) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // Check coinbase timestamp if (GetBlockTime() > FutureDrift((int64_t)vtx[0].nTime)) return DoS(50, error("CheckBlock() : coinbase timestamp is too early")); if (IsProofOfStake()) { // Coinbase output should be empty if proof-of-stake block if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()) return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block")); // Second transaction must be coinstake, the rest must not be if (vtx.empty() || !vtx[1].IsCoinStake()) return DoS(100, error("CheckBlock() : second tx is not coinstake")); for (unsigned int i = 2; i < vtx.size(); i++) if (vtx[i].IsCoinStake()) return DoS(100, error("CheckBlock() : more than one coinstake")); // Check coinstake timestamp if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64_t)vtx[1].nTime)) return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRId64" nTimeTx=%u", GetBlockTime(), vtx[1].nTime)); // NovaCoin: check proof-of-stake block signature if (fCheckSig && !CheckBlockSignature()) return DoS(100, error("CheckBlock() : bad proof-of-stake block signature")); } // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) { if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); // ppcoin: check transaction timestamp if (GetBlockTime() < (int64_t)tx.nTime) return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp")); } // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; BOOST_FOREACH(const CTransaction& tx, vtx) { uniqueTx.insert(tx.GetHash()); } if (uniqueTx.size() != vtx.size()) return DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkle root if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); return true; } bool CBlock::AcceptBlock() { AssertLockHeld(cs_main); if (nVersion > CURRENT_VERSION) return DoS(100, error("AcceptBlock() : reject unknown block version %d", nVersion)); // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; if (IsProofOfWork() && nHeight > LAST_POW_BLOCK) return DoS(100, error("AcceptBlock() : reject proof-of-work at height %d", nHeight)); // Check proof-of-work or proof-of-stake if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake())) return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetPastTimeLimit() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!IsFinalTx(tx, nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckHardened(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight)); uint256 hashProof; // Verify hash target and signature of coinstake tx if (IsProofOfStake()) { uint256 targetProofOfStake; if (!CheckProofOfStake(vtx[1], nBits, hashProof, targetProofOfStake)) { printf("WARNING: AcceptBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str()); return false; // do not error here as we expect this during initial block download } } // PoW is checked in CheckBlock() if (IsProofOfWork()) { hashProof = GetPoWHash(); } bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev); // Check that the block satisfies synchronized checkpoint if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies) return error("AcceptBlock() : rejected by synchronized checkpoint"); if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies) strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!"); // Enforce rule that the coinbase starts with serialized block height CScript expect = CScript() << nHeight; if (vtx[0].vin[0].scriptSig.size() < expect.size() || !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin())) return DoS(100, error("AcceptBlock() : block height mismatch in coinbase")); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos, hashProof)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } // ppcoin: check pending sync-checkpoint Checkpoints::AcceptPendingSyncCheckpoint(); return true; } uint256 CBlockIndex::GetBlockTrust() const { CBigNum bnTarget; bnTarget.SetCompact(nBits); if (bnTarget <= 0) return 0; return ((CBigNum(1)<<256) / (bnTarget+1)).getuint256(); } bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck) { unsigned int nFound = 0; for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++) { if (pstart->nVersion >= minVersion) ++nFound; pstart = pstart->pprev; } return (nFound >= nRequired); } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { AssertLockHeld(cs_main); // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // ppcoin: check proof-of-stake // Limited duplicity on stake: prevents block flood attack // Duplicate stake allowed only when there is orphan child block if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash)) return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str()); // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint(); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash)) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; if (pblock->IsProofOfStake()) bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime)); else bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work"); } } // ppcoin: ask for pending sync-checkpoint if any if (!IsInitialBlockDownload()) Checkpoints::AskForPendingSyncCheckpoint(pfrom); // If don't already have its previous block, shunt it off to holding area until we get it if (!mapBlockIndex.count(pblock->hashPrevBlock)) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); // ppcoin: check proof-of-stake if (pblock->IsProofOfStake()) { // Limited duplicity on stake: prevents block flood attack // Duplicate stake allowed only when there is orphan child block if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash)) return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str()); else setStakeSeenOrphan.insert(pblock->GetProofOfStake()); } CBlock* pblock2 = new CBlock(*pblock); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); // ppcoin: getblocks may not obtain the ancestor block rejected // earlier by duplicate-stake check so we ask for it again directly if (!IsInitialBlockDownload()) pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2))); } return true; } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { CBlock* pblockOrphan = (*mi).second; if (pblockOrphan->AcceptBlock()) vWorkQueue.push_back(pblockOrphan->GetHash()); mapOrphanBlocks.erase(pblockOrphan->GetHash()); setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); // ppcoin: if responsible for sync-checkpoint send it if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty()) Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint()); return true; } // novacoin: attempt to generate suitable proof-of-stake bool CBlock::SignBlock(CWallet& wallet, int64_t nFees) { // if we are trying to sign // something except proof-of-stake block template if (!vtx[0].vout[0].IsEmpty()) return false; // if we are trying to sign // a complete proof-of-stake block if (IsProofOfStake()) return true; static int64_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp CKey key; CTransaction txCoinStake; int64_t nSearchTime = txCoinStake.nTime; // search to current time if (nSearchTime > nLastCoinStakeSearchTime) { if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, nFees, txCoinStake, key)) { if (txCoinStake.nTime >= max(pindexBest->GetPastTimeLimit()+1, PastDrift(pindexBest->GetBlockTime()))) { // make sure coinstake would meet timestamp protocol // as it would be the same as the block timestamp vtx[0].nTime = nTime = txCoinStake.nTime; nTime = max(pindexBest->GetPastTimeLimit()+1, GetMaxTransactionTime()); nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime())); // we have to make sure that we have no future timestamps in // our transactions set for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();) if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; } vtx.insert(vtx.begin() + 1, txCoinStake); hashMerkleRoot = BuildMerkleTree(); // append a signature to our block return key.Sign(GetHash(), vchBlockSig); } } nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime; nLastCoinStakeSearchTime = nSearchTime; } return false; } bool CBlock::CheckBlockSignature() const { if (IsProofOfWork()) return vchBlockSig.empty(); vector<valtype> vSolutions; txnouttype whichType; const CTxOut& txout = vtx[1].vout[1]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { valtype& vchPubKey = vSolutions[0]; CKey key; if (!key.SetPubKey(vchPubKey)) return false; if (vchBlockSig.empty()) return false; return key.Verify(GetHash(), vchBlockSig); } return false; } bool CheckDiskSpace(uint64_t nAdditionalBytes) { uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low!"); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage, "LoanOrLease", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); StartShutdown(); return false; } return true; } static filesystem::path BlockFilePath(unsigned int nFile) { string strBlockFn = strprintf("blk%04u.dat", nFile); return GetDataDir() / strBlockFn; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if ((nFile < 1) || (nFile == (unsigned int) -1)) return NULL; FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; while (true) { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < (long)(0x7F000000 - MAX_SIZE)) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { LOCK(cs_main); CBigNum bnTrustedModulus; if (fTestNet) { pchMessageStart[0] = 0xaa; pchMessageStart[1] = 0x03; pchMessageStart[2] = 0xca; pchMessageStart[3] = 0x14; bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55"); bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet nStakeMinAge = 1 * 60 * 60; // test net min age is 1 hour nCoinbaseMaturity = 10; // test maturity is 10 blocks } else { bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081"); } #if 0 // Set up the Zerocoin Params object ZCParams = new libzerocoin::Params(bnTrustedModulus); #endif // // Load block index // CTxDB txdb("cr+"); if (!txdb.LoadBlockIndex()) return false; // // Init with genesis block // if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis block // MainNet: //CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1510499334, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=) // Coinbase(hash=12630d16a9, nTime=1510499334, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341) // CTxOut(empty) // vMerkleTree: 12630d16a9 // TestNet: //CBlock(hash=0000724595fb3b9609d441cbfb9577615c292abf07d996d3edabc48de843642d, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1510499334, nBits=1f00ffff, nNonce=216178, vtx=1, vchBlockSig=) // Coinbase(hash=12630d16a9, nTime=1510499334, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341) // CTxOut(empty) // vMerkleTree: 12630d16a9 const char* pszTimestamp = "The Times 11 11 17 new lol coin"; CTransaction txNew; txNew.nTime = 1510499334; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].SetEmpty(); CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = 1; block.nTime = 1510499334; block.nBits = bnProofOfWorkLimit.GetCompact(); block.nNonce = !fTestNet ? 501320 : 501320; if (true && (block.GetHash() != hashGenesisBlock)) { // This will figure out a valid hash and Nonce if you're // creating a different genesis block: uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); while (block.GetHash() > hashTarget) { ++block.nNonce; if (block.nNonce == 0) { printf("NONCE WRAPPED, incrementing time"); ++block.nTime; } } } //// debug print block.print(); printf("block.GetHash() == %s\n", block.GetHash().ToString().c_str()); printf("block.hashMerkleRoot == %s\n", block.hashMerkleRoot.ToString().c_str()); printf("block.nTime = %u \n", block.nTime); printf("block.nNonce = %u \n", block.nNonce); assert(block.hashMerkleRoot == uint256("0xf3729cd896c7b8b744cabaa7c03ef4445bd043c88b28e7921cab9a27e4afb7c7")); assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)); assert(block.CheckBlock()); // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos, hashGenesisBlock)) return error("LoadBlockIndex() : genesis block not accepted"); // ppcoin: initialize synchronized checkpoint if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))) return error("LoadBlockIndex() : failed to init sync checkpoint"); } string strPubKey = ""; // if checkpoint master key changed must reset sync-checkpoint if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey) { // write checkpoint master key to db txdb.TxnBegin(); if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey)) return error("LoadBlockIndex() : failed to write new checkpoint master key to db"); if (!txdb.TxnCommit()) return error("LoadBlockIndex() : failed to commit new checkpoint master key to db"); if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint()) return error("LoadBlockIndex() : failed to reset sync-checkpoint"); } return true; } void PrintBlockTree() { AssertLockHeld(cs_main); // pre-compute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().c_str(), block.nBits, DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(), FormatMoney(pindex->nMint).c_str(), block.vtx.size()); PrintWallets(block); // put the main time-chain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } bool LoadExternalBlockFile(FILE* fileIn) { int64_t nStart = GetTimeMillis(); int nLoaded = 0; { LOCK(cs_main); try { CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION); unsigned int nPos = 0; while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown) { unsigned char pchData[65536]; do { fseek(blkdat, nPos, SEEK_SET); int nRead = fread(pchData, 1, sizeof(pchData), blkdat); if (nRead <= 8) { nPos = (unsigned int)-1; break; } void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart)); if (nFind) { if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0) { nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart); break; } nPos += ((unsigned char*)nFind - pchData) + 1; } else nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1; } while(!fRequestShutdown); if (nPos == (unsigned int)-1) break; fseek(blkdat, nPos, SEEK_SET); unsigned int nSize; blkdat >> nSize; if (nSize > 0 && nSize <= MAX_BLOCK_SIZE) { CBlock block; blkdat >> block; if (ProcessBlock(NULL,&block)) { nLoaded++; nPos += 4 + nSize; } } } } catch (std::exception &e) { printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__); } } printf("Loaded %i blocks from external file in %"PRId64"ms\n", nLoaded, GetTimeMillis() - nStart); return nLoaded > 0; } ////////////////////////////////////////////////////////////////////////////// // // CAlert // extern map<uint256, CAlert> mapAlerts; extern CCriticalSection cs_mapAlerts; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // if detected invalid checkpoint enter safe mode if (Checkpoints::hashInvalidCheckpoint != 0) { nPriority = 3000; strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers."); } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; if (nPriority > 1000) strRPC = strStatusBar; } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; txInMap = mempool.exists(inv.hash); return txInMap || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. unsigned char pchMessageStart[4] = { 0x0d, 0xc8, 0x5f, 0x6b }; bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, CPubKey> mapReuseKey; RandAddSeedPerfmon(); if (fDebug) printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size()); if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64_t nTime; CAddress addrMe; CAddress addrFrom; uint64_t nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PEER_PROTO_VERSION) { // disconnect from peers older than this proto version printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; if (pfrom->fInbound && addrMe.IsRoutable()) { pfrom->addrLocal = addrMe; SeenLocal(addrMe); } // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // record my external IP reported by peer if (addrFrom.IsRoutable() && addrMe.IsRoutable()) addrSeenByPeer = addrMe; // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); if (GetBoolArg("-synctime", true)) AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr); if (addr.IsRoutable()) pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && !pfrom->fOneShot && (pfrom->nStartingHeight > (nBestHeight - 144)) && (pfrom->nVersion < NOBLKS_VERSION_START || pfrom->nVersion >= NOBLKS_VERSION_END) && (nAskedForBlocks < 1 || vNodes.size() <= 1)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } // Relay sync-checkpoint { LOCK(Checkpoints::cs_hashSyncCheckpoint); if (!Checkpoints::checkpointMessage.IsNull()) Checkpoints::checkpointMessage.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str()); cPeerBlockCounts.input(pfrom->nStartingHeight); // ppcoin: ask for pending sync-checkpoint if any if (!IsInitialBlockDownload()) Checkpoints::AskForPendingSyncCheckpoint(pfrom); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %"PRIszu"", vAddr.size()); } // Store the new addresses vector<CAddress> vAddrOk; int64_t nNow = GetAdjustedTime(); int64_t nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint64_t hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { pfrom->Misbehaving(20); return error("message inv size() = %"PRIszu"", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } CTxDB txdb("r"); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) pfrom->AskFor(inv); else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0)); if (fDebug) printf("force request: %s\n", inv.ToString().c_str()); } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { pfrom->Misbehaving(20); return error("message getdata size() = %"PRIszu"", vInv.size()); } if (fDebugNet || (vInv.size() != 1)) printf("received getdata (%"PRIszu" invsz)\n", vInv.size()); BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; if (fDebugNet || (vInv.size() == 1)) printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // ppcoin: send latest proof-of-work block to allow the // download node to accept as orphan (proof-of-stake // block might be rejected by stake connection check) vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash())); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory bool pushed = false; { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) { pfrom->PushMessage(inv.GetCommand(), (*mi).second); pushed = true; } } if (!pushed && inv.type == MSG_TX) { CTransaction tx; if (mempool.lookup(inv.hash, tx)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << tx; pfrom->PushMessage("tx", ss); } } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); // ppcoin: tell downloading node about the latest block if it's // without risk being rejected due to stake connection check if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime()) pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain)); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "checkpoint") { CSyncCheckpoint checkpoint; vRecv >> checkpoint; if (checkpoint.ProcessSyncCheckpoint(pfrom)) { // Relay pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint; LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) checkpoint.RelayTo(pnode); } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str()); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); bool fMissingInputs = false; if (AcceptToMemoryPool(mempool, tx, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayTransaction(tx, inv.hash); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); mi != mapOrphanTransactionsByPrev[hashPrev].end(); ++mi) { const uint256& orphanTxHash = *mi; CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash]; bool fMissingInputs2 = false; if (AcceptToMemoryPool(mempool, orphanTx, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayTransaction(orphanTx, orphanTxHash); mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash)); vWorkQueue.push_back(orphanTxHash); vEraseQueue.push_back(orphanTxHash); } else if (!fMissingInputs2) { // invalid orphan vEraseQueue.push_back(orphanTxHash); printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(tx); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; uint256 hashBlock = block.GetHash(); printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str()); CInv inv(MSG_BLOCK, hashBlock); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { // Don't return addresses older than nCutOff timestamp int64_t nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60); pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) if(addr.nTime > nCutOff) pfrom->PushAddress(addr); } else if (strCommand == "mempool") { std::vector<uint256> vtxid; mempool.queryHashes(vtxid); vector<CInv> vInv; for (unsigned int i = 0; i < vtxid.size(); i++) { CInv inv(MSG_TX, vtxid[i]); vInv.push_back(inv); if (i == (MAX_INV_SZ - 1)) break; } if (vInv.size() > 0) pfrom->PushMessage("inv", vInv); } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; /// we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; { LOCK(pfrom->cs_mapRequests); map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64_t nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; uint256 alertHash = alert.GetHash(); if (pfrom->setKnown.count(alertHash) == 0) { if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alertHash); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } else { // Small DoS penalty so peers that send us lots of // duplicate/expired/invalid-signature/whatever alerts // eventually get banned. // This isn't a Misbehaving(100) (immediate ban) because the // peer might be an older or different implementation with // a different signature key, etc. pfrom->Misbehaving(10); } } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } // requires LOCK(cs_vRecvMsg) bool ProcessMessages(CNode* pfrom) { //if (fDebug) // printf("ProcessMessages(%zu messages)\n", pfrom->vRecvMsg.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // bool fOk = true; std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin(); while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; // get next message CNetMessage& msg = *it; //if (fDebug) // printf("ProcessMessages(message %u msgsz, %zu bytes, complete:%s)\n", // msg.hdr.nMessageSize, msg.vRecv.size(), // msg.complete() ? "Y" : "N"); // end, if an incomplete message is found if (!msg.complete()) break; // at this point, any failure means we can delete the current message it++; // Scan for message start if (memcmp(msg.hdr.pchMessageStart, pchMessageStart, sizeof(pchMessageStart)) != 0) { printf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n"); fOk = false; break; } // Read header CMessageHeader& hdr = msg.hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; // Checksum CDataStream& vRecv = msg.vRecv; uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vRecv); } if (fShutdown) break; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from under-length message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from over-long size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } // In case the connection got shut down, its receive buffer was wiped if (!pfrom->fDisconnect) pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it); return fOk; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSendMsg.empty()) { uint64_t nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Resend wallet transactions that haven't gotten in a block yet ResendWalletTransactions(); // Address refresh broadcast static int64_t nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen) { CAddress addr = GetLocalAddress(&pnode->addr); if (addr.IsRoutable()) pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64_t nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { if (fDebugNet) printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } mapAlreadyAskedFor[inv] = nNow; } pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; }
//===-- FunctionErrorPropagator.cpp - Error Propagator ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// Error propagator for fixed point computations in a single function. /// //===----------------------------------------------------------------------===// #include "FunctionErrorPropagator.h" #include "CallSiteVersions.h" #include "llvm/Analysis/CFLSteensAliasAnalysis.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/IR/InstIterator.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Debug.h" #include <llvm/IR/InstrTypes.h> #include "MemSSAUtils.h" #include "Metadata.h" #include "Propagators.h" #include "TypeUtils.h" namespace ErrorProp { using namespace llvm; using namespace mdutils; #define DEBUG_TYPE "errorprop" void FunctionErrorPropagator::computeErrorsWithCopy(RangeErrorMap &GlobRMap, SmallVectorImpl<Value *> *Args, bool GenMetadata) { if (F.empty() || FCopy == nullptr) { LLVM_DEBUG(dbgs() << "[taffo-err] Function " << F.getName() << " could not be processed.\n"); return; } // Increase count of consecutive recursive calls. unsigned OldRecCount = FCMap.incRecursionCount(&F); Function &CF = *FCopy; LLVM_DEBUG(dbgs() << "\n[taffo-err] *** Processing function " << CF.getName() << " (iteration " << OldRecCount + 1 << ")... ***\n"); CmpMap.clear(); RMap = GlobRMap; // Reset the error associated to this function. RMap.erase(FCopy); // CFLSteensAAWrapperPass *CFLSAA = // EPPass.getAnalysisIfAvailable<CFLSteensAAWrapperPass>(); // if (CFLSAA != nullptr) // CFLSAA->getResult().scan(FCopy); MemSSA = &(EPPass.getAnalysis<MemorySSAWrapperPass>(CF).getMSSA()); computeFunctionErrors(Args); if (GenMetadata) { // Put error metadata in original function. attachErrorMetadata(); } applyActualParametersErrors(GlobRMap, Args); // Associate computed errors to global variables. for (const GlobalVariable &GV : F.getParent()->globals()) { const AffineForm<inter_t> *GVErr = RMap.getError(&GV); if (GVErr == nullptr) continue; GlobRMap.setError(&GV, *GVErr); } // Update target errors GlobRMap.updateTargets(RMap); // Associate computed error to the original function. auto FErr = RMap.getError(FCopy); if (FErr != nullptr) GlobRMap.setError(&F, AffineForm<inter_t>(*FErr)); // Restore original recursion count. FCMap.setRecursionCount(&F, OldRecCount); LLVM_DEBUG(dbgs() << "[taffo-err] Finished processing function " << CF.getName() << ".\n\n"); } void FunctionErrorPropagator::computeFunctionErrors(SmallVectorImpl<Value *> *ArgErrs) { assert(FCopy != nullptr); if (ArgErrs) RMap.initArgumentBindings(*FCopy, *ArgErrs); RMap.retrieveRangeErrors(*FCopy); RMap.applyArgumentErrors(*FCopy, ArgErrs); LoopInfo &LInfo = EPPass.getAnalysis<LoopInfoWrapperPass>(*FCopy).getLoopInfo(); // Compute errors for all instructions in the function BBScheduler BBSched(*FCopy, LInfo); // Restore MemSSA assert(FCopy != nullptr); MemSSA = &(EPPass.getAnalysis<MemorySSAWrapperPass>(*FCopy).getMSSA()); for (BasicBlock *BB : BBSched) for (Instruction &I : *BB) computeInstructionErrors(I); } void FunctionErrorPropagator::computeInstructionErrors(Instruction &I) { bool HasInitialError = RMap.retrieveRangeError(I); double InitialError; if (HasInitialError) { auto *IEP = RMap.getError(&I); assert(IEP != nullptr); InitialError = IEP->noiseTermsAbsSum(); } bool ComputedError = dispatchInstruction(I); // if (HasInitialError) { // if (ComputedError) { // LLVM_DEBUG(dbgs() << "WARNING: computed error for instruction " // << I.getName() << " ignored because of metadata error " // << InitialError << ".\n"); // RMap.setError(&I, AffineForm<inter_t>(0.0, InitialError)); // } // else { // LLVM_DEBUG(dbgs() << "Initial error for instruction " // << I.getName() << ": " << InitialError << ".\n"); // } // } if (!ComputedError && HasInitialError) { LLVM_DEBUG(dbgs() << "[taffo-err] WARNING: metadata error " << InitialError << " attached to instruction (" << I << ").\n"); RMap.setError(&I, AffineForm<inter_t>(0.0, InitialError)); } LLVM_DEBUG( if (checkOverflow(I)) dbgs() << "[taffo-err] Possible overflow detected for instruction (" << I << ").\n";); } bool FunctionErrorPropagator::dispatchInstruction(Instruction &I) { assert(MemSSA != nullptr); InstructionPropagator IP(RMap, *MemSSA, SloppyAA); if (I.isBinaryOp()) return IP.propagateBinaryOp(I); switch (I.getOpcode()) { case Instruction::Store: return IP.propagateStore(I); case Instruction::Load: return IP.propagateLoad(I); case Instruction::FPExt: // Fall-through. case Instruction::SExt: // Fall-through. case Instruction::ZExt: return IP.propagateExt(I); case Instruction::FPTrunc: // Fall-through. case Instruction::Trunc: return IP.propagateTrunc(I); case Instruction::FNeg: return IP.propagateFNeg(I); case Instruction::Select: return IP.propagateSelect(I); case Instruction::PHI: return IP.propagatePhi(I); case Instruction::FCmp: // Fall-through. case Instruction::ICmp: return IP.checkCmp(CmpMap, I); case Instruction::Ret: return IP.propagateRet(I); case Instruction::Call: // Fall-through. case Instruction::Invoke: prepareErrorsForCall(I); return IP.propagateCall(I); case Instruction::UIToFP: // Fall-through. case Instruction::SIToFP: return IP.propagateIToFP(I); case Instruction::FPToUI: // Fall-through. case Instruction::FPToSI: return IP.propagateFPToI(I); default: LLVM_DEBUG(InstructionPropagator::logInstruction(I); InstructionPropagator::logInfoln("unhandled.")); return false; } llvm_unreachable("No return statement."); } void FunctionErrorPropagator::prepareErrorsForCall(Instruction &I) { auto CS = dyn_cast<CallBase>(&I); Function *CalledF = CS->getCalledFunction(); SmallVector<Value *, 0U> Args; for (Use &U : CS->args()) { Value *Arg = U.get(); if (Arg->getType()->isPointerTy() && !taffo::fullyUnwrapPointerOrArrayType(Arg->getType())->isStructTy()) { auto RE = RMap.getRangeError(Arg); if (RE != nullptr && RE->second.hasValue()) Args.push_back(Arg); else { Value *OrigPointer = MemSSAUtils::getOriginPointer(*MemSSA, Arg); Args.push_back(OrigPointer); } } else { Args.push_back(Arg); } } if (CalledF == nullptr || InstructionPropagator::isSpecialFunction(*CalledF)) return; LLVM_DEBUG(dbgs() << "[taffo-err] Preparing errors for function call/invoke " << I.getName() << "...\n"); // Stop if we have reached the maximum recursion count. if (FCMap.maxRecursionCountReached(CalledF)) return; // Now propagate the errors for this call. FunctionErrorPropagator CFEP(EPPass, *CalledF, FCMap, RMap.getMetadataManager(), SloppyAA); CFEP.computeErrorsWithCopy(RMap, &Args, false); // Restore MemorySSA assert(FCopy != nullptr); MemSSA = &(EPPass.getAnalysis<MemorySSAWrapperPass>(*FCopy).getMSSA()); } void FunctionErrorPropagator::applyActualParametersErrors(RangeErrorMap &GlobRMap, SmallVectorImpl<Value *> *Args) { assert(FCopy != nullptr); if (Args == nullptr) return; auto FArg = FCopy->arg_begin(); auto FArgEnd = FCopy->arg_end(); for (auto AArg = Args->begin(), AArgEnd = Args->end(); AArg != AArgEnd && FArg != FArgEnd; ++AArg, ++FArg) { if (*AArg == nullptr) continue; if (!FArg->getType()->isPointerTy()) continue; const AffineForm<inter_t> *Err = RMap.getError(&(*FArg)); if (Err == nullptr) { Value *OrigPointer = MemSSAUtils::getOriginPointer(*MemSSA, &*FArg); Err = RMap.getError(OrigPointer); if (Err == nullptr) continue; } LLVM_DEBUG(dbgs() << "[taffo-err] Setting actual parameter (" << **AArg << ") error " << static_cast<double>(Err->noiseTermsAbsSum()) << "\n"); GlobRMap.setError(*AArg, *Err); } // Now update structs: GlobRMap.updateStructErrors(RMap, *Args); } void FunctionErrorPropagator::attachErrorMetadata() { ValueToValueMapTy *VMap = FCMap.getValueToValueMap(&F); assert(VMap != nullptr); for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) { Value *InstCopy = (Cloned) ? (*VMap)[cast<Value>(&*I)] : &*I; if (InstCopy == nullptr) continue; double Error = RMap.getOutputError(InstCopy); if (!std::isnan(Error)) { MetadataManager::setErrorMetadata(*I, Error); } CmpErrorMap::const_iterator CmpErr = CmpMap.find(InstCopy); if (CmpErr != CmpMap.end()) MetadataManager::setCmpErrorMetadata(*I, CmpErr->second); } } bool FunctionErrorPropagator::checkOverflow(Instruction &I) { const FPInterval *Range = RMap.getRange(&I); const TType *Type; if (Range == nullptr || (Type = Range->getTType()) == nullptr) return false; return Range->Min < (Type->getMinValueBound()).convertToDouble() || Range->Max > (Type->getMaxValueBound()).convertToDouble(); } void BBScheduler::enqueueChildren(BasicBlock *BB) { assert(BB != nullptr && "Null basic block."); // Do nothing if already visited. if (Set.count(BB)) return; LLVM_DEBUG(dbgs() << "[taffo-err] Scheduling " << BB->getName() << ".\n"); Set.insert(BB); Instruction *TI = BB->getTerminator(); if (TI != nullptr) { Loop *L = LInfo.getLoopFor(BB); if (L == nullptr) { // Not part of a loop, just visit all unvisited successors. int c = TI->getNumSuccessors(); for (int i = 0; i < c; i++) enqueueChildren(TI->getSuccessor(i)); } else { // Part of a loop: // visit exiting blocks first, so they are scheduled at the end. SmallVector<BasicBlock *, 2U> BodyQueue; int c = TI->getNumSuccessors(); for (int i = 0; i < c; i++) { BasicBlock *DestBB = TI->getSuccessor(i); if (isExiting(DestBB, L)) enqueueChildren(DestBB); else BodyQueue.push_back(DestBB); } // If the header is also the exit, but not a latch, // it is visited also after the loop body if (L->isLoopExiting(BB) && !L->isLoopLatch(BB)) Queue.push_back(BB); for (BasicBlock *BodyBB : BodyQueue) enqueueChildren(BodyBB); } } Queue.push_back(BB); } bool BBScheduler::isExiting(BasicBlock *Dst, Loop *L) const { assert(L != nullptr); if (!L->contains(Dst)) return true; return L->isLoopExiting(Dst); } } // end namespace ErrorProp
/* Copyright 2007 Albert Strasheim <fullung@gmail.com> 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. */ #include <boost/python/class.hpp> #include <boost/python/enum.hpp> #include <cms/Destination.h> #include <cms/Topic.h> #include <cms/Queue.h> #include <cms/TemporaryTopic.h> #include <cms/TemporaryQueue.h> namespace py = boost::python; using cms::Destination; using cms::Topic; using cms::Queue; using cms::TemporaryTopic; using cms::TemporaryQueue; static const char* Destination_docstring = "A C{Destination} object encapsulates a provider-specific address."; static const char* Destination_destinationType_docstring = "Returns the C{Destination} type for this destination."; static const char* DestinationType_docstring = "Available L{Destination} types"; static const char* Topic_docstring = "An interface encapsulating a provider-specific topic name."; static const char* Topic_name_docstring = "The topic name."; static const char* Queue_docstring = "An interface encapsulating a provider-specific queue name."; static const char* Queue_name_docstring = "The queue name."; static const char* TemporaryTopic_docstring = "An interface encapsulating a provider-specific topic name."; static const char* TemporaryTopic_name_docstring = "The topic name."; static const char* TemporaryQueue_docstring = "An interface encapsulating a provider-specific queue name."; static const char* TemporaryQueue_name_docstring = "The queue name."; bool Destination__eq__(const Destination& self, const Destination& other) { if (self.getDestinationType() != other.getDestinationType()) { return false; } switch (self.getDestinationType()) { case Destination::TOPIC: { const Topic& selfTopic = dynamic_cast<const Topic&>(self); const Topic& otherTopic = dynamic_cast<const Topic&>(other); return selfTopic.getTopicName() == otherTopic.getTopicName(); } case Destination::QUEUE: { const Queue& selfQueue = dynamic_cast<const Queue&>(self); const Queue& otherQueue = dynamic_cast<const Queue&>(other); return selfQueue.getQueueName() == otherQueue.getQueueName(); } case Destination::TEMPORARY_TOPIC: { const TemporaryTopic& selfTopic = dynamic_cast<const TemporaryTopic&>(self); const TemporaryTopic& otherTopic = dynamic_cast<const TemporaryTopic&>(other); return selfTopic.getTopicName() == otherTopic.getTopicName(); } case Destination::TEMPORARY_QUEUE: { const TemporaryQueue& selfQueue = dynamic_cast<const TemporaryQueue&>(self); const TemporaryQueue& otherQueue = dynamic_cast<const TemporaryQueue&>(other); return selfQueue.getQueueName() == otherQueue.getQueueName(); } default: Py_FatalError("Failed to compare destinations"); return false; } } void export_Destinations() { py::class_<Destination, boost::noncopyable>("Destination", Destination_docstring, py::no_init) .add_property("destinationType", &Destination::getDestinationType, Destination_destinationType_docstring) .def("__eq__", Destination__eq__) .add_property("CMSProperties", make_function(&Destination::getCMSProperties, py::return_internal_reference<>())) ; py::enum_<Destination::DestinationType>("DestinationType") .value("TOPIC", Destination::TOPIC) .value("QUEUE", Destination::QUEUE) .value("TEMPORARY_TOPIC", Destination::TEMPORARY_TOPIC) .value("TEMPORARY_QUEUE", Destination::TEMPORARY_QUEUE) ; py::class_<Topic, py::bases<Destination>, boost::noncopyable>("Topic", Topic_docstring, py::no_init) .add_property("name", &Topic::getTopicName, Topic_name_docstring) ; py::class_<Queue, py::bases<Destination>, boost::noncopyable>("Queue", Queue_docstring, py::no_init) .add_property("name", &Queue::getQueueName, Queue_name_docstring) ; py::class_<TemporaryTopic, py::bases<Destination>, boost::noncopyable>("TemporaryTopic", TemporaryTopic_docstring, py::no_init) .add_property("name", &TemporaryTopic::getTopicName, TemporaryTopic_name_docstring) ; py::class_<TemporaryQueue, py::bases<Destination>, boost::noncopyable>("TemporaryQueue", TemporaryQueue_docstring, py::no_init) .add_property("name", &TemporaryQueue::getQueueName, TemporaryQueue_name_docstring) ; }
/** * eZmax API Definition (Full) * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.7 * Contact: support-api@ezmax.ca * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QObject> #include "OAIHelpers.h" namespace OpenAPI { OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload(QString json) { this->initializeModel(); this->fromJson(json); } OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload() { this->initializeModel(); } OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::~OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload() {} void OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::initializeModel() { m_a_pki_ezsignformfieldgroup_id_isSet = false; m_a_pki_ezsignformfieldgroup_id_isValid = false; } void OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::fromJson(QString jsonString) { QByteArray array(jsonString.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); } void OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::fromJsonObject(QJsonObject json) { m_a_pki_ezsignformfieldgroup_id_isValid = ::OpenAPI::fromJsonValue(a_pki_ezsignformfieldgroup_id, json[QString("a_pkiEzsignformfieldgroupID")]); m_a_pki_ezsignformfieldgroup_id_isSet = !json[QString("a_pkiEzsignformfieldgroupID")].isNull() && m_a_pki_ezsignformfieldgroup_id_isValid; } QString OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::asJson() const { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::asJsonObject() const { QJsonObject obj; if (a_pki_ezsignformfieldgroup_id.size() > 0) { obj.insert(QString("a_pkiEzsignformfieldgroupID"), ::OpenAPI::toJsonValue(a_pki_ezsignformfieldgroup_id)); } return obj; } QList<qint32> OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::getAPkiEzsignformfieldgroupId() const { return a_pki_ezsignformfieldgroup_id; } void OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::setAPkiEzsignformfieldgroupId(const QList<qint32> &a_pki_ezsignformfieldgroup_id) { this->a_pki_ezsignformfieldgroup_id = a_pki_ezsignformfieldgroup_id; this->m_a_pki_ezsignformfieldgroup_id_isSet = true; } bool OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::is_a_pki_ezsignformfieldgroup_id_Set() const{ return m_a_pki_ezsignformfieldgroup_id_isSet; } bool OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::is_a_pki_ezsignformfieldgroup_id_Valid() const{ return m_a_pki_ezsignformfieldgroup_id_isValid; } bool OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::isSet() const { bool isObjectUpdated = false; do { if (a_pki_ezsignformfieldgroup_id.size() > 0) { isObjectUpdated = true; break; } } while (false); return isObjectUpdated; } bool OAIEzsigndocument_editEzsignformfieldgroups_v1_Response_mPayload::isValid() const { // only required properties are required for the object to be considered valid return m_a_pki_ezsignformfieldgroup_id_isValid && true; } } // namespace OpenAPI
#include <gmock/gmock.h> #include <vector> #include "MaxWeightIndependentSet.hpp" using namespace testing; using namespace DynamicProgramming; TEST(PathGraph, CorrectMaxWeightIndependentSet) { auto path = std::vector<unsigned>{1, 4, 5, 4}; ASSERT_THAT(totalWeightOfMWIS(path), 8); } TEST(PathGraph, CorrectNodesInMaxWeightIndependentSet) { auto path = std::vector<unsigned>{1, 4, 5, 4}; ASSERT_THAT(getIndexOfMWISNodes(path), ElementsAre(1, 3)); } int main(int argc, char *argv[]) { InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); }
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/runtime/runtime-utils.h" #include "src/arguments.h" #include "src/objects-inl.h" namespace v8 { namespace internal { RUNTIME_FUNCTION(Runtime_ForInDone) { SealHandleScope scope(isolate); DCHECK_EQ(2, args.length()); CONVERT_SMI_ARG_CHECKED(index, 0); CONVERT_SMI_ARG_CHECKED(length, 1); DCHECK_LE(0, index); DCHECK_LE(index, length); return isolate->heap()->ToBoolean(index == length); } RUNTIME_FUNCTION(Runtime_ForInFilter) { HandleScope scope(isolate); DCHECK_EQ(2, args.length()); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0); CONVERT_ARG_HANDLE_CHECKED(Object, key, 1); // TODO(turbofan): Fast case for array indices. Handle<Name> name; if (!Object::ToName(isolate, key).ToHandle(&name)) { return isolate->heap()->exception(); } Maybe<bool> result = JSReceiver::HasProperty(receiver, name); if (!result.IsJust()) return isolate->heap()->exception(); if (result.FromJust()) return *name; return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_ForInNext) { HandleScope scope(isolate); DCHECK_EQ(4, args.length()); CONVERT_ARG_HANDLE_CHECKED(JSReceiver, receiver, 0); CONVERT_ARG_HANDLE_CHECKED(FixedArray, cache_array, 1); CONVERT_ARG_HANDLE_CHECKED(Object, cache_type, 2); CONVERT_SMI_ARG_CHECKED(index, 3); Handle<Object> key = handle(cache_array->get(index), isolate); // Don't need filtering if expected map still matches that of the receiver, // and neither for proxies. if (receiver->map() == *cache_type || *cache_type == Smi::FromInt(0)) { return *key; } // TODO(turbofan): Fast case for array indices. Handle<Name> name; if (!Object::ToName(isolate, key).ToHandle(&name)) { return isolate->heap()->exception(); } Maybe<bool> result = JSReceiver::HasProperty(receiver, name); if (!result.IsJust()) return isolate->heap()->exception(); if (result.FromJust()) return *name; return isolate->heap()->undefined_value(); } RUNTIME_FUNCTION(Runtime_ForInStep) { SealHandleScope scope(isolate); DCHECK_EQ(1, args.length()); CONVERT_SMI_ARG_CHECKED(index, 0); DCHECK_LE(0, index); DCHECK_LT(index, Smi::kMaxValue); return Smi::FromInt(index + 1); } } // namespace internal } // namespace v8
/* * Copyright 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "pc/audio_track.h" #include "rtc_base/checks.h" #include "rtc_base/ref_counted_object.h" namespace webrtc { // static rtc::scoped_refptr<AudioTrack> AudioTrack::Create( const std::string& id, const rtc::scoped_refptr<AudioSourceInterface>& source) { return new rtc::RefCountedObject<AudioTrack>(id, source); } AudioTrack::AudioTrack(const std::string& label, const rtc::scoped_refptr<AudioSourceInterface>& source) : MediaStreamTrack<AudioTrackInterface>(label), audio_source_(source) { if (audio_source_) { audio_source_->RegisterObserver(this); OnChanged(); } } AudioTrack::~AudioTrack() { RTC_DCHECK(thread_checker_.IsCurrent()); set_state(MediaStreamTrackInterface::kEnded); if (audio_source_) audio_source_->UnregisterObserver(this); } std::string AudioTrack::kind() const { RTC_DCHECK(thread_checker_.IsCurrent()); return kAudioKind; } AudioSourceInterface* AudioTrack::GetSource() const { RTC_DCHECK(thread_checker_.IsCurrent()); return audio_source_.get(); } void AudioTrack::AddSink(AudioTrackSinkInterface* sink) { RTC_DCHECK(thread_checker_.IsCurrent()); if (audio_source_) audio_source_->AddSink(sink); } void AudioTrack::RemoveSink(AudioTrackSinkInterface* sink) { RTC_DCHECK(thread_checker_.IsCurrent()); if (audio_source_) audio_source_->RemoveSink(sink); } void AudioTrack::OnChanged() { RTC_DCHECK(thread_checker_.IsCurrent()); if (audio_source_->state() == MediaSourceInterface::kEnded) { set_state(kEnded); } else { set_state(kLive); } } } // namespace webrtc
// // Created by william on 4/6/22. // #include "MultiplayerScreen.h" #include "client/wagyourgui/GLFWSession.h" #include "client/wagyourgui/elements/TextInput.h" #include "client/wagyourgui/DrawableHelper.h" #include "ConnectingScreen.h" #include "MainMenuScreen.h" #include <algorithm> #include <string> using namespace DrawableHelper; void MultiplayerScreen::init(Window* window) { std::shared_ptr<TextInput> serverIP; serverIP = addElement( std::make_shared<TextInput>( 5, height / 2 - 55, width - 10, 20, parent->font, 0xFF101010, 0xFF000000, 0xFF4040FF, 0xFFFFFFFF, "127.0.0.1", [](Button* btn) {}, [](std::string& str) {} )); serverIP->regex = "\\d*\\.?\\d*\\.?\\d*\\.?\\d*"; addElement( std::make_shared<Button>( 5, height / 2 + 10, width / 2 - 10, 20, parent->font, "Host", 0, 0xFF4f4f4f, 0xFFFFFFFF, 0xFF000000, [=](Button* b) { if (regex_match(serverIP->content, std::regex("^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\\.|$)){4}"))) { parent->setScreen(new ConnectingScreen(parent, serverIP->content)); } } )); std::shared_ptr<TextInput> joinCode; joinCode = addElement( std::make_shared<TextInput>( width / 2 + 5, height / 2 - 15, width / 2 - 10, 20, parent->font, 0xFF101010, 0xFF000000, 0xFF4040FF, 0xFFFFFFFF, "", [](Button* btn) {}, [=](std::string& str) { https://stackoverflow.com/questions/735204/convert-a-string-in-c-to-upper-case std::transform(str.begin(), str.end(), str.begin(), ::toupper); } )); joinCode->regex = std::regex("[a-zA-Z0-9]{0,5}"); addElement( std::make_shared<Button>( width / 2 + 5, height / 2 + 10, width / 2 - 10, 20, parent->font, "Join", 0, 0xFF4f4f4f, 0xFFFFFFFF, 0xFF000000, [=](Button* b) { if (joinCode->content.length() == 5) { if (regex_match(serverIP->content, std::regex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){4}$"))) { parent->setScreen(new ConnectingScreen(parent, serverIP->content, joinCode->content)); } } } )); addElement( std::make_shared<Button>( 5, height - 35, width / 2 - 10, 20, parent->font, "Back", 0, 0xFF4f4f4f, 0xFFFFFFFF, 0xFF000000, [=](Button* b) { parent->setScreen(new MainMenuScreen(parent)); } )); } void MultiplayerScreen::onRender(float mouseX, float mouseY) { drawCenteredString(parent->font, "Multiplayer", width / 2, 15, 0xFFFFFFFF); glPushMatrix(); glTranslatef(width / 2, height / 2 - 70, 0); glScalef(0.5, 0.5, 1); drawCenteredString(parent->font, "Server IP", 0, 0, 0xFFFFFFFF); glPopMatrix(); glPushMatrix(); glTranslatef(3 * width / 4, height / 2 - 30, 0); glScalef(0.5, 0.5, 1); drawCenteredString(parent->font, "Join Code", 0, 0, 0xFFFFFFFF); glPopMatrix(); Screen::onRender(mouseX, mouseY); }
#include "utils.h" #include "crypto/sha2.h" #include "flaggedarrayset.h" #include "relayprocess.h" #include <stdio.h> #include <sys/time.h> #include <algorithm> #include <random> #include <string.h> #include <unistd.h> void do_nothing(...) {} #ifdef BENCH #define PRINT_TIME do_nothing #else #define PRINT_TIME printf #endif std::linear_congruential_engine<std::uint_fast32_t, 48271, 0, 2147483647> engine(42); void fill_txv(std::vector<unsigned char>& block, std::vector<std::shared_ptr<std::vector<unsigned char> > >& txVectors, float includeP) { std::vector<unsigned char>::const_iterator readit = block.begin(); move_forward(readit, sizeof(struct bitcoin_msg_header), block.end()); move_forward(readit, 80, block.end()); uint32_t txcount = read_varint(readit, block.end()); std::uniform_real_distribution<double> distribution(0.0, 1.0); for (uint32_t i = 0; i < txcount; i++) { std::vector<unsigned char>::const_iterator txstart = readit; move_forward(readit, 4, block.end()); uint32_t txins = read_varint(readit, block.end()); for (uint32_t j = 0; j < txins; j++) { move_forward(readit, 36, block.end()); uint32_t scriptlen = read_varint(readit, block.end()); move_forward(readit, scriptlen + 4, block.end()); } uint32_t txouts = read_varint(readit, block.end()); for (uint32_t j = 0; j < txouts; j++) { move_forward(readit, 8, block.end()); uint32_t scriptlen = read_varint(readit, block.end()); move_forward(readit, scriptlen, block.end()); } move_forward(readit, 4, block.end()); if (distribution(engine) < includeP) txVectors.push_back(std::make_shared<std::vector<unsigned char> >(txstart, readit)); } std::shuffle(txVectors.begin(), txVectors.end(), engine); } int pipefd[2]; uint32_t block_tx_count; RelayNodeCompressor global_sender(false), global_receiver(false); std::set<std::vector<unsigned char> > globalSeenSet; static unsigned int compress_runs = 0, decompress_runs = 0; static std::chrono::nanoseconds total_compress_time, total_decompress_time; static std::chrono::nanoseconds max_compress_time, max_decompress_time; static std::chrono::nanoseconds min_compress_time = std::chrono::hours(1), min_decompress_time = std::chrono::hours(1); std::shared_ptr<std::vector<unsigned char> > __attribute__((noinline)) recv_block(std::shared_ptr<std::vector<unsigned char> >& data, RelayNodeCompressor* receiver, bool time) { size_t readpos = sizeof(struct relay_msg_header); auto start = std::chrono::steady_clock::now(); std::function<ssize_t(char*, size_t)> do_read = [&](char* buf, size_t count) { memcpy(buf, &(*data)[readpos], count); readpos += count; assert(readpos <= data->size()); return count; }; auto res = receiver->decompress_relay_block(do_read, block_tx_count, true); auto decompressed = std::chrono::steady_clock::now(); if (time) { total_decompress_time += decompressed - start; decompress_runs++; if ((decompressed - start) > max_decompress_time) max_decompress_time = decompressed - start; if ((decompressed - start) < min_decompress_time) min_decompress_time = decompressed - start; } if (std::get<2>(res)) { printf("ERROR Decompressing block %s\n", std::get<2>(res)); exit(2); } else if (time) PRINT_TIME("Decompressed block in %lf ms\n", to_millis_double(decompressed - start)); return std::get<1>(res); } std::tuple<std::shared_ptr<std::vector<unsigned char> >, const char*> __attribute__((noinline)) do_compress_test(RelayNodeCompressor& sender, const std::vector<unsigned char>& fullhash, const std::vector<unsigned char>& data, uint32_t tx_count) { auto start = std::chrono::steady_clock::now(); auto res = sender.maybe_compress_block(fullhash, data, true); auto compressed = std::chrono::steady_clock::now(); total_compress_time += compressed - start; compress_runs++; if ((compressed - start) > max_compress_time) max_compress_time = compressed - start; if ((compressed - start) < min_compress_time) min_compress_time = compressed - start; if(std::get<0>(res)) PRINT_TIME("Compressed from %lu to %lu in %lf ms with %u txn pre-relayed\n", data.size(), std::get<0>(res)->size(), to_millis_double(compressed - start), tx_count); return res; } void test_compress_block(std::vector<unsigned char>& data, std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors) { std::vector<unsigned char> fullhash(32); getblockhash(fullhash, data, sizeof(struct bitcoin_msg_header)); RelayNodeCompressor sender(false), tester(false), tester2(false), receiver(false); for (auto v : txVectors) { unsigned int made = sender.get_relay_transaction(v).use_count(); #ifndef PRECISE_BENCH v = std::make_shared<std::vector<unsigned char> >(*v); // Copy the vector to give the deduper something to do #endif if (made) receiver.recv_tx(v); #ifndef PRECISE_BENCH v = std::make_shared<std::vector<unsigned char> >(*v); #endif if (made != tester.get_relay_transaction(v).use_count() || made != tester2.get_relay_transaction(v).use_count()) { printf("get_relay_transaction behavior not consistent???\n"); exit(5); } #ifndef PRECISE_BENCH v = std::make_shared<std::vector<unsigned char> >(*v); #endif made = global_sender.get_relay_transaction(v).use_count(); #ifndef PRECISE_BENCH v = std::make_shared<std::vector<unsigned char> >(*v); #endif if (made) global_receiver.recv_tx(v); } unsigned int i = 0; sender.for_each_sent_tx([&](std::shared_ptr<std::vector<unsigned char> > tx) { if (*tx != *txVectors[i]) { printf("for_each_sent_tx was not in order!\n"); exit(6); } std::vector<unsigned char> tx_data, tx_hash(32); if (!tester.send_tx_cache.remove(0, tx_data, &tx_hash[0]) || tx_data != *txVectors[i++]) { printf("for_each_sent_tx output did not match remove(0)\n"); exit(7); } }); auto res = do_compress_test(sender, fullhash, data, txVectors.size()); if (std::get<1>(res)) { printf("Failed to compress block %s\n", std::get<1>(res)); exit(8); } std::this_thread::sleep_for(std::chrono::milliseconds(10)); // Let the deduper thread run... if (*std::get<0>(tester2.maybe_compress_block(fullhash, data, true)) != *std::get<0>(res)) { printf("maybe_compress_block not consistent???\n"); exit(9); } struct relay_msg_header header; memcpy(&header, &(*std::get<0>(res))[0], sizeof(header)); block_tx_count = ntohl(header.length); auto decompressed_block = recv_block(std::get<0>(res), &receiver, true); if (*decompressed_block != data) { printf("Re-constructed block did not match!\n"); exit(4); } if (globalSeenSet.insert(fullhash).second) { res = global_sender.maybe_compress_block(fullhash, data, true); if (std::get<1>(res)) { printf("Failed to compress block globally %s\n", std::get<1>(res)); exit(8); } decompressed_block = recv_block(std::get<0>(res), &global_receiver, false); if (*decompressed_block != data) { printf("Global re-constructed block did not match!\n"); exit(4); } } } void run_test(std::vector<unsigned char>& data) { std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors; test_compress_block(data, txVectors); fill_txv(data, txVectors, 1.0); test_compress_block(data, txVectors); txVectors.clear(); fill_txv(data, txVectors, 0.5); test_compress_block(data, txVectors); txVectors.clear(); fill_txv(data, txVectors, 0.9); test_compress_block(data, txVectors); } int main() { std::vector<unsigned char> data(sizeof(struct bitcoin_msg_header)); std::vector<unsigned char> lastBlock; std::vector<std::shared_ptr<std::vector<unsigned char> > > allTxn; FILE* f = fopen("block.txt", "r"); while (true) { char hex[2]; if (fread(hex, 1, 1, f) != 1) break; else if (hex[0] == '\n') { if (data.size()) { #ifdef BENCH for (int i = 0; i < 100; i++) #endif run_test(data); fill_txv(data, allTxn, 0.9); lastBlock = data; } data = std::vector<unsigned char>(sizeof(struct bitcoin_msg_header)); } else if (fread(hex + 1, 1, 1, f) != 1) break; else { if (hex[0] >= 'a') hex[0] -= 'a' - '9' - 1; if (hex[1] >= 'a') hex[1] -= 'a' - '9' - 1; data.push_back((hex[0] - '0') << 4 | (hex[1] - '0')); } } #ifdef BENCH for (int i = 0; i < 100; i++) #endif test_compress_block(lastBlock, allTxn); printf("Total time spent compressing %u blocks: %lf ms (avg %lf, min %lf, max %lf)\n", compress_runs, to_millis_double(total_compress_time), to_millis_double(total_compress_time / compress_runs), to_millis_double(min_compress_time), to_millis_double(max_compress_time)); printf("Total time spent decompressing %u blocks: %lf ms (avg %lf, min %lf, max %lf)\n", decompress_runs, to_millis_double(total_decompress_time), to_millis_double(total_decompress_time / decompress_runs), to_millis_double(min_decompress_time), to_millis_double(max_decompress_time)); return 0; }
#include <functional> #include <string> #include <iostream> #include "src/trie.hpp" /* quick example class for handling extra data */ class metadata { public: int somethingA; int somethingB; }; void example() { std::cout << "hello world!" << std::endl; } int main() { /* Create our Trie * The template parameters are the following: * > Key Datatype for lookup * > Datatype for the value * > an extra datatype for user defined datatypes. */ Trie::Trie<std::string, std::function<void(void)>, metadata> exampleTrie; std::cout << "Adding two children to the root." << std::endl; exampleTrie.add("test", example); exampleTrie.add("lol", example); exampleTrie.del("test"); std::cout << "List the keys we added to the root:" << std::endl; for(auto const& l: exampleTrie.list()) std::cout << "> " << l << std::endl; std::cout << "Changing the childrens meta objects:" << std::endl; for(auto const& l: exampleTrie.list()) { /* access the object. */ auto child = *exampleTrie[l]; /* Change it */ child.meta.somethingA = 1337; std::cout << "somethingA: " << child.meta.somethingA << std::endl; /* run it */ std::cout << "Running this childs function:" << std::endl; child.value(); } }
// // Created by egordm on 19-3-18. // #include "segmentation_helper.h" #include "../cvision/segmentation.h" #include "../cvision/visualization.h" using namespace cvision::algorithms; using namespace cvision::evaluation; Mat ComplexSegmentationHelper::draw(const cv::Mat &src, const cv::Mat &original) { frame = src; float threshold_a = ((float) threshold) / 100; auto mweight = (float) (0.5 + ((positive_marginal_prob - 0.5) * (((float) marginal_weight) / 100))); return segmentation::complex_segmentation(src, positive_hst, negative_hst, threshold_a, mweight); } std::vector<Statistic> ComplexSegmentationHelper::get_statistics() { return { std::bind(&ComplexSegmentationHelper::get_probability, this), std::bind(&ComplexSegmentationHelper::get_probability2, this) }; } std::vector<Trackbar> ComplexSegmentationHelper::get_trackbars() { return { Trackbar("Threshold", &threshold, 100)}; } bool ComplexSegmentationHelper::on_click(int x, int y, bool rb) { if(rb) return false; colour = frame.at<Vec3b>(Point(x, y)); HistColor color_array = {(double) colour[0], (double) colour[1], (double) colour[2]}; pskin = positive_hst->probability(color_array); penv = negative_hst->probability(color_array); pbayes = bayes_probability(pskin, penv, positive_marginal_prob); return true; } std::string ComplexSegmentationHelper::get_probability() { std::stringstream ss; ss << "C " << (int) colour[2] << "," << (int) colour[1] << "," << (int) colour[0] << "| Pt: " << pskin << "| Pn: " << penv; return ss.str(); } std::string ComplexSegmentationHelper::get_probability2() { std::stringstream ss; ss << "Pm: " << positive_marginal_prob << "| Pb: " << pbayes; return ss.str(); } std::vector<Trackbar> SimpleSegmentationHelper::get_trackbars() { return { Trackbar("Alpha", &alpha, 40), Trackbar("Beta", &beta, 60), Trackbar("Gamma", &gamma, 60), }; } Mat SimpleSegmentationHelper::draw(const cv::Mat &src, const cv::Mat &original) { Mat prefx; cvtColor(src, prefx, COLOR_BGR2HSV); auto color = skin_histogram->dominat_val(); Scalar low(std::fmin(0, color[0] - ((double) alpha / 2)), std::fmax(0, ((double) beta / 2)), std::fmax(0, ((double) gamma / 2))); Scalar high(std::fmin(180, color[0] + ((double) alpha / 2)), std::fmin(256, 256 - ((double) beta / 2)), std::fmin(256, 256 - ((double) gamma / 2))); return segmentation::simple_segmentation(prefx, low, high); } std::vector<Trackbar> SegmentationPatcher::get_trackbars() { return { Trackbar("Erode Dilate Size", &ed_size, 30), Trackbar("Close Size", &close_size, 30), Trackbar("Post Blur", &postblur, 30) }; } Mat SegmentationPatcher::draw(const cv::Mat &src, const cv::Mat &original) { mask = segmentation::clean_segmentation(src, ed_size, close_size, (postblur % 2 == 0) ? postblur + 1 : postblur); if(mask.channels() > 1) cvtColor(mask, mask, COLOR_BGR2GRAY); Mat ret; original.convertTo(ret, -1, 1, -100); original.copyTo(ret, mask); return ret; } std::vector<Statistic> CFMatrixHelper::get_statistics() { return { std::bind(&CFMatrixHelper::get_recall, this), std::bind(&CFMatrixHelper::get_precision, this), std::bind(&CFMatrixHelper::get_score, this), std::bind(&CFMatrixHelper::get_error, this) }; } std::string CFMatrixHelper::get_recall() { std::stringstream ss; ss << "Recall: " << cf_results.recall; return ss.str(); } std::string CFMatrixHelper::get_precision() { std::stringstream ss; ss << "Precision: " << cf_results.precision; return ss.str(); } std::string CFMatrixHelper::get_score() { std::stringstream ss; ss << "F1 score: " << cf_results.f1; return ss.str(); } std::string CFMatrixHelper::get_error() { std::stringstream ss; ss << "Relative error: " << cf_results.relative_error; return ss.str(); } cv::Mat CFMatrixHelper::draw(const cv::Mat &src, const cv::Mat &original) { cv::Mat prediction, ground_truth; original.copyTo(prediction, input_mask); label_mask.copyTo(ground_truth); if(ground_truth.channels() > 1) cvtColor(ground_truth, ground_truth, COLOR_BGR2GRAY); auto matrix = cvision::evaluation::make_confsion_matrix(original, ground_truth, prediction); cf_results = matrix.evaluate(); return src; }
#include "envoy/extensions/filters/network/direct_response/v3/config.pb.h" #include "envoy/extensions/filters/network/direct_response/v3/config.pb.validate.h" #include "envoy/registry/registry.h" #include "envoy/server/filter_config.h" #include "common/config/datasource.h" #include "extensions/filters/network/common/factory_base.h" #include "extensions/filters/network/direct_response/filter.h" #include "extensions/filters/network/well_known_names.h" namespace Envoy { namespace Extensions { namespace NetworkFilters { namespace DirectResponse { /** * Config registration for the direct response filter. @see NamedNetworkFilterConfigFactory. */ class DirectResponseConfigFactory : public Common::FactoryBase<envoy::extensions::filters::network::direct_response::v3::Config> { public: DirectResponseConfigFactory() : FactoryBase(NetworkFilterNames::get().DirectResponse) {} private: Network::FilterFactoryCb createFilterFactoryFromProtoTyped( const envoy::extensions::filters::network::direct_response::v3::Config& config, Server::Configuration::FactoryContext& context) override { return [config, &context](Network::FilterManager& filter_manager) -> void { auto content = Config::DataSource::read(config.response(), true, context.api()); filter_manager.addReadFilter(std::make_shared<DirectResponseFilter>(content)); }; } bool isTerminalFilterByProtoTyped( const envoy::extensions::filters::network::direct_response::v3::Config&, Server::Configuration::FactoryContext&) override { return true; } }; /** * Static registration for the direct response filter. @see RegisterFactory. */ REGISTER_FACTORY(DirectResponseConfigFactory, Server::Configuration::NamedNetworkFilterConfigFactory); } // namespace DirectResponse } // namespace NetworkFilters } // namespace Extensions } // namespace Envoy
//1462 #include <iostream> #include <fstream> #include <cmath> #include <cctype> #include <stdlib.h> #include <string.h> #define zero 1e-8 #define MAXN 110 using namespace std; double t[MAXN]; char code[MAXN][MAXN][MAXN], name[100][100], del[300], *tok; int m[MAXN], N, n; double state[MAXN][MAXN], A[MAXN][MAXN + 1], r; void Gauss() { int i, j, k; for (j = 1; j <= n; j++) { for (i = j; i <= n; i++) if (!(fabs(A[i][j]) < zero)) break; if (i != j) for (k = 1; k <= n + 1; k++) swap(A[i][k], A[j][k]); r = A[j][j]; for (k = j; k <= n + 1; k++) A[j][k] /= r; for (i = j + 1; i <= n; i++) { r = A[i][j]; for (k = j; k <= n + 1; k++) A[i][k] -= r * A[j][k]; } } for (j = n; j >= 1; j--) { for (i = j - 1; i >= 1; i--) { r = A[i][j]; for (k = 1; k <= n + 1; k++) A[i][k] -= A[j][k] * r; } } } void IntoA(int x) { int i; for (i = 1; i <= n; i++) A[x][i] = state[x][i]; A[x][n + 1] = - state[x][0]; A[x][x]--; } bool calc(int x) { double case1, case2; int i, j, k; char s[100]; n = m[x]; for (i = 0; i <= n; i++) state[n][i] = 0; IntoA(n); for (k = n - 1; k >= 1; k--) { for (i = 0; i <= n; i++) state[k][i] = state[k + 1][i]; if (strstr(code[x][k], "NOP;") != 0) state[k][0]++; else { strcpy(s, code[x][k]); tok = strtok(s, del); tok = strtok(NULL, del); tok = strtok(NULL, del); case1 = atof(tok); case2 = 1 - case1; if (strstr(code[x][k], ">") != 0) swap(case1, case2); tok = strtok(NULL, del); tok = strtok(NULL, del); if (strstr(code[x][k], "PROC") != 0) { for (i = 1; i <= N; i++) if (strcmp(name[i], tok) == 0) break; if (fabs(t[i]) < zero) return false; state[k][0] += case1 * t[i]; state[k][0]++; } else { j = atoi(tok); for (i = 0; i <= n; i++) state[k][i] *= case2; if (j > k) for (i = 0; i <= n; i++) state[k][i] += case1 * state[j][i]; else state[k][j] += case1; state[k][0]++; } } IntoA(k); } return true; } int main() { int i, j, ndel; char s[100]; ndel = 0; for (i = 255; i >= 0; i--) if (! (isalpha(char(i)) || isdigit(char(i)) || char(i) == '.')) del[++ndel - 1] = char(i); del[ndel] = '\0'; ifstream cin("random.dat", ios::in); cin.getline(s, 200, '\n'); N = 0; while (1) { cin.getline(s, 100, '\n'); if (strcmp(s, "PROG_END") == 0) break; N++; m[N] = 0; tok = strtok(s, del); tok = strtok(NULL, del); strcpy(name[N], tok); while (1) { cin.getline(s, 100, '\n'); ++m[N]; strcpy(code[N][m[N]], s); if (strcmp(s, "END;") == 0) break; } } for (i = 1; i <= N; i++) t[i] = 0; i = N; while (i > 0) { for (j = 1; j <= N; j++) if (fabs(t[j]) < zero) if (calc(j)) { i--; Gauss(); t[j] = A[1][n + 1]; } } while (1) { cin.getline(s, 100, '\n'); if (strcmp(s, "REQUEST_END") == 0) break; for (i = 1; i <= N; i++) if (strcmp(s, name[i]) == 0) { printf("%.3Lf\n", t[i]); break; } } cin.close(); //system("pause"); return 0; }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/greengrassv2/model/DeploymentComponentUpdatePolicyAction.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace GreengrassV2 { namespace Model { namespace DeploymentComponentUpdatePolicyActionMapper { static const int NOTIFY_COMPONENTS_HASH = HashingUtils::HashString("NOTIFY_COMPONENTS"); static const int SKIP_NOTIFY_COMPONENTS_HASH = HashingUtils::HashString("SKIP_NOTIFY_COMPONENTS"); DeploymentComponentUpdatePolicyAction GetDeploymentComponentUpdatePolicyActionForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == NOTIFY_COMPONENTS_HASH) { return DeploymentComponentUpdatePolicyAction::NOTIFY_COMPONENTS; } else if (hashCode == SKIP_NOTIFY_COMPONENTS_HASH) { return DeploymentComponentUpdatePolicyAction::SKIP_NOTIFY_COMPONENTS; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<DeploymentComponentUpdatePolicyAction>(hashCode); } return DeploymentComponentUpdatePolicyAction::NOT_SET; } Aws::String GetNameForDeploymentComponentUpdatePolicyAction(DeploymentComponentUpdatePolicyAction enumValue) { switch(enumValue) { case DeploymentComponentUpdatePolicyAction::NOTIFY_COMPONENTS: return "NOTIFY_COMPONENTS"; case DeploymentComponentUpdatePolicyAction::SKIP_NOTIFY_COMPONENTS: return "SKIP_NOTIFY_COMPONENTS"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace DeploymentComponentUpdatePolicyActionMapper } // namespace Model } // namespace GreengrassV2 } // namespace Aws
/* Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* HIT_START * BUILD: %t %s test_common.cpp * HIT_END */ #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <iostream> #include <string> #include "hip/hip_runtime.h" using namespace std; void usage() { printf("hipEnvVar [otpions]\n\ -c,\t\ttotal number of available GPUs and their pciBusID\n\ -d,\t\tselect one GPU and return its pciBusID\n\ -v,\t\tsend the list to HIP_VISIBLE_DEVICES env var\n\ -h,\t\tshow this help message\n\ "); } int main(int argc, char **argv) { //string str = getenv("HIP_VISIBLE_DEVICES"); //std::cout << "The current env HIP_VISIBLE_DEVICES is"<<str << std::endl; extern char *optarg; extern int optind; int c = 0; int retDevCnt=0, retDevInfo=0, setEnvVar=0; int device=0; string env; while ((c = getopt(argc, argv, "cd:v:h")) != -1) switch (c) { case 'c': retDevCnt = true; break; case 'd': retDevInfo = true; device = atoi(optarg); break; case 'v': setEnvVar = true; env = optarg; break; case 'h': usage(); return 0; default : //usage(); return -1; } if (setEnvVar ) { //env = "export HIP_VISIBLE_DEVICES=" + env; //cout<<"The received env var is: "<<env<<endl; setenv("HIP_VISIBLE_DEVICES",env.c_str(),1); setenv("CUDA_VISIBLE_DEVICES",env.c_str(),1); cout<<"set env HIP_VISIBLE_DEVICES = "<< env.c_str()<<endl; //verify if the environment variable is set char* pPath; pPath = getenv ("HIP_VISIBLE_DEVICES"); if(pPath!=NULL) printf("HIP_VISIBLE_DEVICES is %s\n", pPath); else printf("HIP_VISIBLE_DEVICES is not set\n"); } // device init int devCount=0; hipGetDeviceCount(&devCount); //printf("\nTotal number of GPU devices in the system is %d\n",devCount); if (devCount == 0) { printf("No HIP enabled device\n"); return -1; } if (device < 0 || device > devCount -1) { printf("Selected device %d is out of bound. Devices on your system are in range %d - %d\n", device, 0, devCount -1); return -1; } if (retDevCnt) { //std::cout << "Total number of devices visible in system is "<< devCount << std::endl; std::cout << devCount << std::endl; } if (retDevInfo) { hipDevice_t deviceT; hipDeviceGet(&deviceT, device); char pciBusId[100]; memset(pciBusId,0,100); hipDeviceGetPCIBusId(pciBusId,100,deviceT); cout<<pciBusId<<endl; } exit(0); }
#include "ActionManagerTest.h" #include "../testResource.h" #include "cocos2d.h" enum { kTagNode, kTagGrossini, kTagSequence, }; Layer* nextActionManagerAction(); Layer* backActionManagerAction(); Layer* restartActionManagerAction(); static int sceneIdx = -1; #define MAX_LAYER 5 Layer* createActionManagerLayer(int nIndex) { switch(nIndex) { case 0: return new CrashTest(); case 1: return new LogicTest(); case 2: return new PauseTest(); case 3: return new RemoveTest(); case 4: return new ResumeTest(); } return NULL; } Layer* nextActionManagerAction() { sceneIdx++; sceneIdx = sceneIdx % MAX_LAYER; auto layer = createActionManagerLayer(sceneIdx); layer->autorelease(); return layer; } Layer* backActionManagerAction() { sceneIdx--; int total = MAX_LAYER; if( sceneIdx < 0 ) sceneIdx += total; auto layer = createActionManagerLayer(sceneIdx); layer->autorelease(); return layer; } Layer* restartActionManagerAction() { auto layer = createActionManagerLayer(sceneIdx); layer->autorelease(); return layer; } //------------------------------------------------------------------ // // ActionManagerTest // //------------------------------------------------------------------ ActionManagerTest::ActionManagerTest(void) { } ActionManagerTest::~ActionManagerTest(void) { } std::string ActionManagerTest::title() { return "No title"; } void ActionManagerTest::restartCallback(Object* sender) { auto s = new ActionManagerTestScene(); s->addChild(restartActionManagerAction()); Director::getInstance()->replaceScene(s); s->release(); } void ActionManagerTest::nextCallback(Object* sender) { auto s = new ActionManagerTestScene(); s->addChild( nextActionManagerAction() ); Director::getInstance()->replaceScene(s); s->release(); } void ActionManagerTest::backCallback(Object* sender) { auto s = new ActionManagerTestScene(); s->addChild( backActionManagerAction() ); Director::getInstance()->replaceScene(s); s->release(); } //------------------------------------------------------------------ // // Test1 // //------------------------------------------------------------------ void CrashTest::onEnter() { ActionManagerTest::onEnter(); auto child = Sprite::create(s_pathGrossini); child->setPosition( VisibleRect::center() ); addChild(child, 1); //Sum of all action's duration is 1.5 second. child->runAction(RotateBy::create(1.5f, 90)); child->runAction(Sequence::create( DelayTime::create(1.4f), FadeOut::create(1.1f), NULL) ); //After 1.5 second, self will be removed. runAction( Sequence::create( DelayTime::create(1.4f), CallFunc::create( CC_CALLBACK_0(CrashTest::removeThis,this)), NULL) ); } void CrashTest::removeThis() { m_pParent->removeChild(this, true); nextCallback(this); } std::string CrashTest::title() { return "Test 1. Should not crash"; } //------------------------------------------------------------------ // // Test2 // //------------------------------------------------------------------ void LogicTest::onEnter() { ActionManagerTest::onEnter(); auto grossini = Sprite::create(s_pathGrossini); addChild(grossini, 0, 2); grossini->setPosition(VisibleRect::center()); grossini->runAction( Sequence::create( MoveBy::create(1, Point(150,0)), CallFuncN::create(CC_CALLBACK_1(LogicTest::bugMe,this)), NULL) ); } void LogicTest::bugMe(Node* node) { node->stopAllActions(); //After this stop next action not working, if remove this stop everything is working node->runAction(ScaleTo::create(2, 2)); } std::string LogicTest::title() { return "Logic test"; } //------------------------------------------------------------------ // // PauseTest // //------------------------------------------------------------------ void PauseTest::onEnter() { // // This test MUST be done in 'onEnter' and not on 'init' // otherwise the paused action will be resumed at 'onEnter' time // ActionManagerTest::onEnter(); auto l = LabelTTF::create("After 5 seconds grossini should move", "Thonburi", 16); addChild(l); l->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y-75) ); // // Also, this test MUST be done, after [super onEnter] // auto grossini = Sprite::create(s_pathGrossini); addChild(grossini, 0, kTagGrossini); grossini->setPosition(VisibleRect::center() ); auto action = MoveBy::create(1, Point(150,0)); auto director = Director::getInstance(); director->getActionManager()->addAction(action, grossini, true); schedule( schedule_selector(PauseTest::unpause), 3); } void PauseTest::unpause(float dt) { unschedule( schedule_selector(PauseTest::unpause) ); auto node = getChildByTag( kTagGrossini ); auto director = Director::getInstance(); director->getActionManager()->resumeTarget(node); } std::string PauseTest::title() { return "Pause Test"; } //------------------------------------------------------------------ // // RemoveTest // //------------------------------------------------------------------ void RemoveTest::onEnter() { ActionManagerTest::onEnter(); auto l = LabelTTF::create("Should not crash", "Thonburi", 16); addChild(l); l->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y - 75) ); auto pMove = MoveBy::create(2, Point(200, 0)); auto pCallback = CallFunc::create(CC_CALLBACK_0(RemoveTest::stopAction,this)); auto pSequence = Sequence::create(pMove, pCallback, NULL); pSequence->setTag(kTagSequence); auto pChild = Sprite::create(s_pathGrossini); pChild->setPosition( VisibleRect::center() ); addChild(pChild, 1, kTagGrossini); pChild->runAction(pSequence); } void RemoveTest::stopAction() { auto sprite = getChildByTag(kTagGrossini); sprite->stopActionByTag(kTagSequence); } std::string RemoveTest::title() { return "Remove Test"; } //------------------------------------------------------------------ // // ResumeTest // //------------------------------------------------------------------ std::string ResumeTest::title() { return "Resume Test"; } void ResumeTest::onEnter() { ActionManagerTest::onEnter(); auto l = LabelTTF::create("Grossini only rotate/scale in 3 seconds", "Thonburi", 16); addChild(l); l->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y - 75)); auto pGrossini = Sprite::create(s_pathGrossini); addChild(pGrossini, 0, kTagGrossini); pGrossini->setPosition(VisibleRect::center()); pGrossini->runAction(ScaleBy::create(2, 2)); auto director = Director::getInstance(); director->getActionManager()->pauseTarget(pGrossini); pGrossini->runAction(RotateBy::create(2, 360)); this->schedule(schedule_selector(ResumeTest::resumeGrossini), 3.0f); } void ResumeTest::resumeGrossini(float time) { this->unschedule(schedule_selector(ResumeTest::resumeGrossini)); auto pGrossini = getChildByTag(kTagGrossini); auto director = Director::getInstance(); director->getActionManager()->resumeTarget(pGrossini); } //------------------------------------------------------------------ // // ActionManagerTestScene // //------------------------------------------------------------------ void ActionManagerTestScene::runThisTest() { auto layer = nextActionManagerAction(); addChild(layer); Director::getInstance()->replaceScene(this); }
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2018 The FASTNODE developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "core_io.h" #include "base58.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/standard.h" #include "serialize.h" #include "streams.h" #include <univalue.h> #include "util.h" #include "utilmoneystr.h" #include "utilstrencodings.h" #include <boost/foreach.hpp> using namespace std; string FormatScript(const CScript& script) { string ret; CScript::const_iterator it = script.begin(); opcodetype op; while (it != script.end()) { CScript::const_iterator it2 = it; vector<unsigned char> vch; if (script.GetOp2(it, op, &vch)) { if (op == OP_0) { ret += "0 "; continue; } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) { ret += strprintf("%i ", op - OP_1NEGATE - 1); continue; } else if (op >= OP_NOP && op <= OP_CHECKMULTISIGVERIFY) { string str(GetOpName(op)); if (str.substr(0, 3) == string("OP_")) { ret += str.substr(3, string::npos) + " "; continue; } } if (vch.size() > 0) { ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it)); } else { ret += strprintf("0x%x", HexStr(it2, it)); } continue; } ret += strprintf("0x%x ", HexStr(it2, script.end())); break; } return ret.substr(0, ret.size() - 1); } string EncodeHexTx(const CTransaction& tx) { CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; return HexStr(ssTx.begin(), ssTx.end()); } void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.pushKV("asm", scriptPubKey.ToString()); if (fIncludeHex) out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.pushKV("type", GetTxnOutputType(type)); return; } out.pushKV("reqSigs", nRequired); out.pushKV("type", GetTxnOutputType(type)); UniValue a(UniValue::VARR); BOOST_FOREACH (const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.pushKV("addresses", a); } void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry) { entry.pushKV("txid", tx.GetHash().GetHex()); entry.pushKV("version", tx.nVersion); entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin(UniValue::VARR); BOOST_FOREACH (const CTxIn& txin, tx.vin) { UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); else { in.pushKV("txid", txin.prevout.hash.GetHex()); in.pushKV("vout", (int64_t)txin.prevout.n); UniValue o(UniValue::VOBJ); o.pushKV("asm", txin.scriptSig.ToString()); o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); in.pushKV("scriptSig", o); } in.pushKV("sequence", (int64_t)txin.nSequence); vin.push_back(in); } entry.pushKV("vin", vin); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); UniValue outValue(UniValue::VNUM, FormatMoney(txout.nValue)); out.pushKV("value", outValue); out.pushKV("n", (int64_t)i); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(txout.scriptPubKey, o, true); out.pushKV("scriptPubKey", o); vout.push_back(out); } entry.pushKV("vout", vout); if (hashBlock != 0) entry.pushKV("blockhash", hashBlock.GetHex()); entry.pushKV("hex", EncodeHexTx(tx)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction". }
//===-- Instructions.cpp - Implement the LLVM instructions ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements all of the non-inline methods for the LLVM instruction // classes. // //===----------------------------------------------------------------------===// #include "llvm/IR/Instructions.h" #include "LLVMContextImpl.h" #include "llvm/IR/CallSite.h" #include "llvm/IR/ConstantRange.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" #include "llvm/IR/Operator.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" using namespace llvm; //===----------------------------------------------------------------------===// // CallSite Class //===----------------------------------------------------------------------===// User::op_iterator CallSite::getCallee() const { Instruction *II(getInstruction()); return isCall() ? cast<CallInst>(II)->op_end() - 1 // Skip Callee : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee } //===----------------------------------------------------------------------===// // TerminatorInst Class //===----------------------------------------------------------------------===// // Out of line virtual method, so the vtable, etc has a home. TerminatorInst::~TerminatorInst() { } //===----------------------------------------------------------------------===// // UnaryInstruction Class //===----------------------------------------------------------------------===// // Out of line virtual method, so the vtable, etc has a home. UnaryInstruction::~UnaryInstruction() { } //===----------------------------------------------------------------------===// // SelectInst Class //===----------------------------------------------------------------------===// /// areInvalidOperands - Return a string if the specified operands are invalid /// for a select operation, otherwise return null. const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { if (Op1->getType() != Op2->getType()) return "both values to select must have same type"; if (Op1->getType()->isTokenTy()) return "select values cannot have token type"; if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) { // Vector select. if (VT->getElementType() != Type::getInt1Ty(Op0->getContext())) return "vector select condition element type must be i1"; VectorType *ET = dyn_cast<VectorType>(Op1->getType()); if (!ET) return "selected values for vector select must be vectors"; if (ET->getNumElements() != VT->getNumElements()) return "vector select requires selected vectors to have " "the same vector length as select condition"; } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) { return "select condition must be i1 or <n x i1>"; } return nullptr; } //===----------------------------------------------------------------------===// // PHINode Class //===----------------------------------------------------------------------===// PHINode::PHINode(const PHINode &PN) : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()), ReservedSpace(PN.getNumOperands()) { allocHungoffUses(PN.getNumOperands()); std::copy(PN.op_begin(), PN.op_end(), op_begin()); std::copy(PN.block_begin(), PN.block_end(), block_begin()); SubclassOptionalData = PN.SubclassOptionalData; } // removeIncomingValue - Remove an incoming value. This is useful if a // predecessor basic block is deleted. Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) { Value *Removed = getIncomingValue(Idx); // Move everything after this operand down. // // FIXME: we could just swap with the end of the list, then erase. However, // clients might not expect this to happen. The code as it is thrashes the // use/def lists, which is kinda lame. std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx); std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx); // Nuke the last value. Op<-1>().set(nullptr); setNumHungOffUseOperands(getNumOperands() - 1); // If the PHI node is dead, because it has zero entries, nuke it now. if (getNumOperands() == 0 && DeletePHIIfEmpty) { // If anyone is using this PHI, make them use a dummy value instead... replaceAllUsesWith(UndefValue::get(getType())); eraseFromParent(); } return Removed; } /// growOperands - grow operands - This grows the operand list in response /// to a push_back style of operation. This grows the number of ops by 1.5 /// times. /// void PHINode::growOperands() { unsigned e = getNumOperands(); unsigned NumOps = e + e / 2; if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common. ReservedSpace = NumOps; growHungoffUses(ReservedSpace, /* IsPhi */ true); } /// hasConstantValue - If the specified PHI node always merges together the same /// value, return the value, otherwise return null. Value *PHINode::hasConstantValue() const { // Exploit the fact that phi nodes always have at least one entry. Value *ConstantValue = getIncomingValue(0); for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i) if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) { if (ConstantValue != this) return nullptr; // Incoming values not all the same. // The case where the first value is this PHI. ConstantValue = getIncomingValue(i); } if (ConstantValue == this) return UndefValue::get(getType()); return ConstantValue; } //===----------------------------------------------------------------------===// // LandingPadInst Implementation //===----------------------------------------------------------------------===// LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, const Twine &NameStr, Instruction *InsertBefore) : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) { init(NumReservedValues, NameStr); } LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, const Twine &NameStr, BasicBlock *InsertAtEnd) : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) { init(NumReservedValues, NameStr); } LandingPadInst::LandingPadInst(const LandingPadInst &LP) : Instruction(LP.getType(), Instruction::LandingPad, nullptr, LP.getNumOperands()), ReservedSpace(LP.getNumOperands()) { allocHungoffUses(LP.getNumOperands()); Use *OL = getOperandList(); const Use *InOL = LP.getOperandList(); for (unsigned I = 0, E = ReservedSpace; I != E; ++I) OL[I] = InOL[I]; setCleanup(LP.isCleanup()); } LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr, Instruction *InsertBefore) { return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore); } LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr, BasicBlock *InsertAtEnd) { return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd); } void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) { ReservedSpace = NumReservedValues; setNumHungOffUseOperands(0); allocHungoffUses(ReservedSpace); setName(NameStr); setCleanup(false); } /// growOperands - grow operands - This grows the operand list in response to a /// push_back style of operation. This grows the number of ops by 2 times. void LandingPadInst::growOperands(unsigned Size) { unsigned e = getNumOperands(); if (ReservedSpace >= e + Size) return; ReservedSpace = (std::max(e, 1U) + Size / 2) * 2; growHungoffUses(ReservedSpace); } void LandingPadInst::addClause(Constant *Val) { unsigned OpNo = getNumOperands(); growOperands(1); assert(OpNo < ReservedSpace && "Growing didn't work!"); setNumHungOffUseOperands(getNumOperands() + 1); getOperandList()[OpNo] = Val; } //===----------------------------------------------------------------------===// // CallInst Implementation //===----------------------------------------------------------------------===// CallInst::~CallInst() { } void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) { this->FTy = FTy; assert(getNumOperands() == Args.size() + 1 && "NumOperands not set up?"); Op<-1>() = Func; #ifndef NDEBUG assert((Args.size() == FTy->getNumParams() || (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && "Calling a function with bad signature!"); for (unsigned i = 0; i != Args.size(); ++i) assert((i >= FTy->getNumParams() || FTy->getParamType(i) == Args[i]->getType()) && "Calling a function with a bad signature!"); #endif std::copy(Args.begin(), Args.end(), op_begin()); setName(NameStr); } void CallInst::init(Value *Func, const Twine &NameStr) { FTy = cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); assert(getNumOperands() == 1 && "NumOperands not set up?"); Op<-1>() = Func; assert(FTy->getNumParams() == 0 && "Calling a function with bad signature"); setName(NameStr); } CallInst::CallInst(Value *Func, const Twine &Name, Instruction *InsertBefore) : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) ->getElementType())->getReturnType(), Instruction::Call, OperandTraits<CallInst>::op_end(this) - 1, 1, InsertBefore) { init(Func, Name); } CallInst::CallInst(Value *Func, const Twine &Name, BasicBlock *InsertAtEnd) : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) ->getElementType())->getReturnType(), Instruction::Call, OperandTraits<CallInst>::op_end(this) - 1, 1, InsertAtEnd) { init(Func, Name); } CallInst::CallInst(const CallInst &CI) : Instruction(CI.getType(), Instruction::Call, OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(), CI.getNumOperands()), AttributeList(CI.AttributeList), FTy(CI.FTy) { setTailCallKind(CI.getTailCallKind()); setCallingConv(CI.getCallingConv()); std::copy(CI.op_begin(), CI.op_end(), op_begin()); SubclassOptionalData = CI.SubclassOptionalData; } void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) { AttributeSet PAL = getAttributes(); PAL = PAL.addAttribute(getContext(), i, attr); setAttributes(PAL); } void CallInst::addAttribute(unsigned i, StringRef Kind, StringRef Value) { AttributeSet PAL = getAttributes(); PAL = PAL.addAttribute(getContext(), i, Kind, Value); setAttributes(PAL); } void CallInst::removeAttribute(unsigned i, Attribute attr) { AttributeSet PAL = getAttributes(); AttrBuilder B(attr); LLVMContext &Context = getContext(); PAL = PAL.removeAttributes(Context, i, AttributeSet::get(Context, i, B)); setAttributes(PAL); } void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) { AttributeSet PAL = getAttributes(); PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); setAttributes(PAL); } void CallInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { AttributeSet PAL = getAttributes(); PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); setAttributes(PAL); } bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const { if (AttributeList.hasAttribute(i, A)) return true; if (const Function *F = getCalledFunction()) return F->getAttributes().hasAttribute(i, A); return false; } /// IsConstantOne - Return true only if val is constant int 1 static bool IsConstantOne(Value *val) { assert(val && "IsConstantOne does not work with nullptr val"); const ConstantInt *CVal = dyn_cast<ConstantInt>(val); return CVal && CVal->isOne(); } static Instruction *createMalloc(Instruction *InsertBefore, BasicBlock *InsertAtEnd, Type *IntPtrTy, Type *AllocTy, Value *AllocSize, Value *ArraySize, Function *MallocF, const Twine &Name) { assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && "createMalloc needs either InsertBefore or InsertAtEnd"); // malloc(type) becomes: // bitcast (i8* malloc(typeSize)) to type* // malloc(type, arraySize) becomes: // bitcast (i8 *malloc(typeSize*arraySize)) to type* if (!ArraySize) ArraySize = ConstantInt::get(IntPtrTy, 1); else if (ArraySize->getType() != IntPtrTy) { if (InsertBefore) ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, "", InsertBefore); else ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, "", InsertAtEnd); } if (!IsConstantOne(ArraySize)) { if (IsConstantOne(AllocSize)) { AllocSize = ArraySize; // Operand * 1 = Operand } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) { Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy, false /*ZExt*/); // Malloc arg is constant product of type size and array size AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize)); } else { // Multiply type size by the array size... if (InsertBefore) AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, "mallocsize", InsertBefore); else AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, "mallocsize", InsertAtEnd); } } assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size"); // Create the call to Malloc. BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; Module* M = BB->getParent()->getParent(); Type *BPTy = Type::getInt8PtrTy(BB->getContext()); Value *MallocFunc = MallocF; if (!MallocFunc) // prototype malloc as "void *malloc(size_t)" MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, nullptr); PointerType *AllocPtrType = PointerType::getUnqual(AllocTy); CallInst *MCall = nullptr; Instruction *Result = nullptr; if (InsertBefore) { MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore); Result = MCall; if (Result->getType() != AllocPtrType) // Create a cast instruction to convert to the right type... Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore); } else { MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall"); Result = MCall; if (Result->getType() != AllocPtrType) { InsertAtEnd->getInstList().push_back(MCall); // Create a cast instruction to convert to the right type... Result = new BitCastInst(MCall, AllocPtrType, Name); } } MCall->setTailCall(); if (Function *F = dyn_cast<Function>(MallocFunc)) { MCall->setCallingConv(F->getCallingConv()); if (!F->doesNotAlias(0)) F->setDoesNotAlias(0); } assert(!MCall->getType()->isVoidTy() && "Malloc has void return type"); return Result; } /// CreateMalloc - Generate the IR for a call to malloc: /// 1. Compute the malloc call's argument as the specified type's size, /// possibly multiplied by the array size if the array size is not /// constant 1. /// 2. Call malloc with that argument. /// 3. Bitcast the result of the malloc call to the specified type. Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy, Type *AllocTy, Value *AllocSize, Value *ArraySize, Function * MallocF, const Twine &Name) { return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, ArraySize, MallocF, Name); } /// CreateMalloc - Generate the IR for a call to malloc: /// 1. Compute the malloc call's argument as the specified type's size, /// possibly multiplied by the array size if the array size is not /// constant 1. /// 2. Call malloc with that argument. /// 3. Bitcast the result of the malloc call to the specified type. /// Note: This function does not add the bitcast to the basic block, that is the /// responsibility of the caller. Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy, Type *AllocTy, Value *AllocSize, Value *ArraySize, Function *MallocF, const Twine &Name) { return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, ArraySize, MallocF, Name); } static Instruction* createFree(Value* Source, Instruction *InsertBefore, BasicBlock *InsertAtEnd) { assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && "createFree needs either InsertBefore or InsertAtEnd"); assert(Source->getType()->isPointerTy() && "Can not free something of nonpointer type!"); BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; Module* M = BB->getParent()->getParent(); Type *VoidTy = Type::getVoidTy(M->getContext()); Type *IntPtrTy = Type::getInt8PtrTy(M->getContext()); // prototype free as "void free(void*)" Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, nullptr); CallInst* Result = nullptr; Value *PtrCast = Source; if (InsertBefore) { if (Source->getType() != IntPtrTy) PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore); Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore); } else { if (Source->getType() != IntPtrTy) PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd); Result = CallInst::Create(FreeFunc, PtrCast, ""); } Result->setTailCall(); if (Function *F = dyn_cast<Function>(FreeFunc)) Result->setCallingConv(F->getCallingConv()); return Result; } /// CreateFree - Generate the IR for a call to the builtin free function. Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) { return createFree(Source, InsertBefore, nullptr); } /// CreateFree - Generate the IR for a call to the builtin free function. /// Note: This function does not add the call to the basic block, that is the /// responsibility of the caller. Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) { Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd); assert(FreeCall && "CreateFree did not create a CallInst"); return FreeCall; } //===----------------------------------------------------------------------===// // InvokeInst Implementation //===----------------------------------------------------------------------===// void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef<Value *> Args, const Twine &NameStr) { this->FTy = FTy; assert(getNumOperands() == 3 + Args.size() && "NumOperands not set up?"); Op<-3>() = Fn; Op<-2>() = IfNormal; Op<-1>() = IfException; #ifndef NDEBUG assert(((Args.size() == FTy->getNumParams()) || (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && "Invoking a function with bad signature"); for (unsigned i = 0, e = Args.size(); i != e; i++) assert((i >= FTy->getNumParams() || FTy->getParamType(i) == Args[i]->getType()) && "Invoking a function with a bad signature!"); #endif std::copy(Args.begin(), Args.end(), op_begin()); setName(NameStr); } InvokeInst::InvokeInst(const InvokeInst &II) : TerminatorInst(II.getType(), Instruction::Invoke, OperandTraits<InvokeInst>::op_end(this) - II.getNumOperands(), II.getNumOperands()), AttributeList(II.AttributeList), FTy(II.FTy) { setCallingConv(II.getCallingConv()); std::copy(II.op_begin(), II.op_end(), op_begin()); SubclassOptionalData = II.SubclassOptionalData; } BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const { return getSuccessor(idx); } unsigned InvokeInst::getNumSuccessorsV() const { return getNumSuccessors(); } void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) { return setSuccessor(idx, B); } bool InvokeInst::hasFnAttrImpl(Attribute::AttrKind A) const { if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A)) return true; if (const Function *F = getCalledFunction()) return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A); return false; } bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const { if (AttributeList.hasAttribute(i, A)) return true; if (const Function *F = getCalledFunction()) return F->getAttributes().hasAttribute(i, A); return false; } void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) { AttributeSet PAL = getAttributes(); PAL = PAL.addAttribute(getContext(), i, attr); setAttributes(PAL); } void InvokeInst::removeAttribute(unsigned i, Attribute attr) { AttributeSet PAL = getAttributes(); AttrBuilder B(attr); PAL = PAL.removeAttributes(getContext(), i, AttributeSet::get(getContext(), i, B)); setAttributes(PAL); } void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) { AttributeSet PAL = getAttributes(); PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); setAttributes(PAL); } void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { AttributeSet PAL = getAttributes(); PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); setAttributes(PAL); } LandingPadInst *InvokeInst::getLandingPadInst() const { return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI()); } //===----------------------------------------------------------------------===// // ReturnInst Implementation //===----------------------------------------------------------------------===// ReturnInst::ReturnInst(const ReturnInst &RI) : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret, OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(), RI.getNumOperands()) { if (RI.getNumOperands()) Op<0>() = RI.Op<0>(); SubclassOptionalData = RI.SubclassOptionalData; } ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(C), Instruction::Ret, OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, InsertBefore) { if (retVal) Op<0>() = retVal; } ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(C), Instruction::Ret, OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, InsertAtEnd) { if (retVal) Op<0>() = retVal; } ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret, OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) { } unsigned ReturnInst::getNumSuccessorsV() const { return getNumSuccessors(); } /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to /// emit the vtable for the class in this translation unit. void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { llvm_unreachable("ReturnInst has no successors!"); } BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const { llvm_unreachable("ReturnInst has no successors!"); } ReturnInst::~ReturnInst() { } //===----------------------------------------------------------------------===// // ResumeInst Implementation //===----------------------------------------------------------------------===// ResumeInst::ResumeInst(const ResumeInst &RI) : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume, OperandTraits<ResumeInst>::op_begin(this), 1) { Op<0>() = RI.Op<0>(); } ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume, OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) { Op<0>() = Exn; } ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume, OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) { Op<0>() = Exn; } unsigned ResumeInst::getNumSuccessorsV() const { return getNumSuccessors(); } void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { llvm_unreachable("ResumeInst has no successors!"); } BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const { llvm_unreachable("ResumeInst has no successors!"); } //===----------------------------------------------------------------------===// // CleanupEndPadInst Implementation //===----------------------------------------------------------------------===// CleanupEndPadInst::CleanupEndPadInst(const CleanupEndPadInst &CEPI) : TerminatorInst(CEPI.getType(), Instruction::CleanupEndPad, OperandTraits<CleanupEndPadInst>::op_end(this) - CEPI.getNumOperands(), CEPI.getNumOperands()) { setInstructionSubclassData(CEPI.getSubclassDataFromInstruction()); setCleanupPad(CEPI.getCleanupPad()); if (BasicBlock *UnwindDest = CEPI.getUnwindDest()) setUnwindDest(UnwindDest); } void CleanupEndPadInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) { setCleanupPad(CleanupPad); if (UnwindBB) { setInstructionSubclassData(getSubclassDataFromInstruction() | 1); setUnwindDest(UnwindBB); } } CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB, unsigned Values, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()), Instruction::CleanupEndPad, OperandTraits<CleanupEndPadInst>::op_end(this) - Values, Values, InsertBefore) { init(CleanupPad, UnwindBB); } CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB, unsigned Values, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()), Instruction::CleanupEndPad, OperandTraits<CleanupEndPadInst>::op_end(this) - Values, Values, InsertAtEnd) { init(CleanupPad, UnwindBB); } BasicBlock *CleanupEndPadInst::getSuccessorV(unsigned Idx) const { assert(Idx == 0); return getUnwindDest(); } unsigned CleanupEndPadInst::getNumSuccessorsV() const { return getNumSuccessors(); } void CleanupEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) { assert(Idx == 0); setUnwindDest(B); } //===----------------------------------------------------------------------===// // CleanupReturnInst Implementation //===----------------------------------------------------------------------===// CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI) : TerminatorInst(CRI.getType(), Instruction::CleanupRet, OperandTraits<CleanupReturnInst>::op_end(this) - CRI.getNumOperands(), CRI.getNumOperands()) { setInstructionSubclassData(CRI.getSubclassDataFromInstruction()); Op<-1>() = CRI.Op<-1>(); if (CRI.hasUnwindDest()) Op<-2>() = CRI.Op<-2>(); } void CleanupReturnInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) { if (UnwindBB) setInstructionSubclassData(getSubclassDataFromInstruction() | 1); Op<-1>() = CleanupPad; if (UnwindBB) Op<-2>() = UnwindBB; } CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB, unsigned Values, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()), Instruction::CleanupRet, OperandTraits<CleanupReturnInst>::op_end(this) - Values, Values, InsertBefore) { init(CleanupPad, UnwindBB); } CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB, unsigned Values, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()), Instruction::CleanupRet, OperandTraits<CleanupReturnInst>::op_end(this) - Values, Values, InsertAtEnd) { init(CleanupPad, UnwindBB); } BasicBlock *CleanupReturnInst::getSuccessorV(unsigned Idx) const { assert(Idx == 0); return getUnwindDest(); } unsigned CleanupReturnInst::getNumSuccessorsV() const { return getNumSuccessors(); } void CleanupReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) { assert(Idx == 0); setUnwindDest(B); } //===----------------------------------------------------------------------===// // CatchEndPadInst Implementation //===----------------------------------------------------------------------===// CatchEndPadInst::CatchEndPadInst(const CatchEndPadInst &CRI) : TerminatorInst(CRI.getType(), Instruction::CatchEndPad, OperandTraits<CatchEndPadInst>::op_end(this) - CRI.getNumOperands(), CRI.getNumOperands()) { setInstructionSubclassData(CRI.getSubclassDataFromInstruction()); if (BasicBlock *UnwindDest = CRI.getUnwindDest()) setUnwindDest(UnwindDest); } void CatchEndPadInst::init(BasicBlock *UnwindBB) { if (UnwindBB) { setInstructionSubclassData(getSubclassDataFromInstruction() | 1); setUnwindDest(UnwindBB); } } CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB, unsigned Values, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad, OperandTraits<CatchEndPadInst>::op_end(this) - Values, Values, InsertBefore) { init(UnwindBB); } CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB, unsigned Values, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad, OperandTraits<CatchEndPadInst>::op_end(this) - Values, Values, InsertAtEnd) { init(UnwindBB); } BasicBlock *CatchEndPadInst::getSuccessorV(unsigned Idx) const { assert(Idx == 0); return getUnwindDest(); } unsigned CatchEndPadInst::getNumSuccessorsV() const { return getNumSuccessors(); } void CatchEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) { assert(Idx == 0); setUnwindDest(B); } //===----------------------------------------------------------------------===// // CatchReturnInst Implementation //===----------------------------------------------------------------------===// void CatchReturnInst::init(CatchPadInst *CatchPad, BasicBlock *BB) { Op<0>() = CatchPad; Op<1>() = BB; } CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI) : TerminatorInst(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet, OperandTraits<CatchReturnInst>::op_begin(this), 2) { Op<0>() = CRI.Op<0>(); Op<1>() = CRI.Op<1>(); } CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, OperandTraits<CatchReturnInst>::op_begin(this), 2, InsertBefore) { init(CatchPad, BB); } CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, OperandTraits<CatchReturnInst>::op_begin(this), 2, InsertAtEnd) { init(CatchPad, BB); } BasicBlock *CatchReturnInst::getSuccessorV(unsigned Idx) const { assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!"); return getSuccessor(); } unsigned CatchReturnInst::getNumSuccessorsV() const { return getNumSuccessors(); } void CatchReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) { assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!"); setSuccessor(B); } //===----------------------------------------------------------------------===// // CatchPadInst Implementation //===----------------------------------------------------------------------===// void CatchPadInst::init(BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef<Value *> Args, const Twine &NameStr) { assert(getNumOperands() == 2 + Args.size() && "NumOperands not set up?"); Op<-2>() = IfNormal; Op<-1>() = IfException; std::copy(Args.begin(), Args.end(), op_begin()); setName(NameStr); } CatchPadInst::CatchPadInst(const CatchPadInst &CPI) : TerminatorInst(CPI.getType(), Instruction::CatchPad, OperandTraits<CatchPadInst>::op_end(this) - CPI.getNumOperands(), CPI.getNumOperands()) { std::copy(CPI.op_begin(), CPI.op_end(), op_begin()); } CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef<Value *> Args, unsigned Values, const Twine &NameStr, Instruction *InsertBefore) : TerminatorInst(Type::getTokenTy(IfNormal->getContext()), Instruction::CatchPad, OperandTraits<CatchPadInst>::op_end(this) - Values, Values, InsertBefore) { init(IfNormal, IfException, Args, NameStr); } CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef<Value *> Args, unsigned Values, const Twine &NameStr, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getTokenTy(IfNormal->getContext()), Instruction::CatchPad, OperandTraits<CatchPadInst>::op_end(this) - Values, Values, InsertAtEnd) { init(IfNormal, IfException, Args, NameStr); } BasicBlock *CatchPadInst::getSuccessorV(unsigned Idx) const { return getSuccessor(Idx); } unsigned CatchPadInst::getNumSuccessorsV() const { return getNumSuccessors(); } void CatchPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) { return setSuccessor(Idx, B); } //===----------------------------------------------------------------------===// // TerminatePadInst Implementation //===----------------------------------------------------------------------===// void TerminatePadInst::init(BasicBlock *BB, ArrayRef<Value *> Args) { if (BB) setInstructionSubclassData(getSubclassDataFromInstruction() | 1); if (BB) Op<-1>() = BB; std::copy(Args.begin(), Args.end(), op_begin()); } TerminatePadInst::TerminatePadInst(const TerminatePadInst &TPI) : TerminatorInst(TPI.getType(), Instruction::TerminatePad, OperandTraits<TerminatePadInst>::op_end(this) - TPI.getNumOperands(), TPI.getNumOperands()) { setInstructionSubclassData(TPI.getSubclassDataFromInstruction()); std::copy(TPI.op_begin(), TPI.op_end(), op_begin()); } TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB, ArrayRef<Value *> Args, unsigned Values, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad, OperandTraits<TerminatePadInst>::op_end(this) - Values, Values, InsertBefore) { init(BB, Args); } TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB, ArrayRef<Value *> Args, unsigned Values, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad, OperandTraits<TerminatePadInst>::op_end(this) - Values, Values, InsertAtEnd) { init(BB, Args); } BasicBlock *TerminatePadInst::getSuccessorV(unsigned Idx) const { assert(Idx == 0); return getUnwindDest(); } unsigned TerminatePadInst::getNumSuccessorsV() const { return getNumSuccessors(); } void TerminatePadInst::setSuccessorV(unsigned Idx, BasicBlock *B) { assert(Idx == 0); return setUnwindDest(B); } //===----------------------------------------------------------------------===// // CleanupPadInst Implementation //===----------------------------------------------------------------------===// void CleanupPadInst::init(ArrayRef<Value *> Args, const Twine &NameStr) { assert(getNumOperands() == Args.size() && "NumOperands not set up?"); std::copy(Args.begin(), Args.end(), op_begin()); setName(NameStr); } CleanupPadInst::CleanupPadInst(const CleanupPadInst &CPI) : Instruction(CPI.getType(), Instruction::CleanupPad, OperandTraits<CleanupPadInst>::op_end(this) - CPI.getNumOperands(), CPI.getNumOperands()) { std::copy(CPI.op_begin(), CPI.op_end(), op_begin()); } CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args, const Twine &NameStr, Instruction *InsertBefore) : Instruction(Type::getTokenTy(C), Instruction::CleanupPad, OperandTraits<CleanupPadInst>::op_end(this) - Args.size(), Args.size(), InsertBefore) { init(Args, NameStr); } CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args, const Twine &NameStr, BasicBlock *InsertAtEnd) : Instruction(Type::getTokenTy(C), Instruction::CleanupPad, OperandTraits<CleanupPadInst>::op_end(this) - Args.size(), Args.size(), InsertAtEnd) { init(Args, NameStr); } //===----------------------------------------------------------------------===// // UnreachableInst Implementation //===----------------------------------------------------------------------===// UnreachableInst::UnreachableInst(LLVMContext &Context, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable, nullptr, 0, InsertBefore) { } UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable, nullptr, 0, InsertAtEnd) { } unsigned UnreachableInst::getNumSuccessorsV() const { return getNumSuccessors(); } void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { llvm_unreachable("UnreachableInst has no successors!"); } BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const { llvm_unreachable("UnreachableInst has no successors!"); } //===----------------------------------------------------------------------===// // BranchInst Implementation //===----------------------------------------------------------------------===// void BranchInst::AssertOK() { if (isConditional()) assert(getCondition()->getType()->isIntegerTy(1) && "May only branch on boolean predicates!"); } BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertBefore) { assert(IfTrue && "Branch destination may not be null!"); Op<-1>() = IfTrue; } BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertBefore) { Op<-1>() = IfTrue; Op<-2>() = IfFalse; Op<-3>() = Cond; #ifndef NDEBUG AssertOK(); #endif } BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) { assert(IfTrue && "Branch destination may not be null!"); Op<-1>() = IfTrue; } BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) { Op<-1>() = IfTrue; Op<-2>() = IfFalse; Op<-3>() = Cond; #ifndef NDEBUG AssertOK(); #endif } BranchInst::BranchInst(const BranchInst &BI) : TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br, OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(), BI.getNumOperands()) { Op<-1>() = BI.Op<-1>(); if (BI.getNumOperands() != 1) { assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!"); Op<-3>() = BI.Op<-3>(); Op<-2>() = BI.Op<-2>(); } SubclassOptionalData = BI.SubclassOptionalData; } void BranchInst::swapSuccessors() { assert(isConditional() && "Cannot swap successors of an unconditional branch"); Op<-1>().swap(Op<-2>()); // Update profile metadata if present and it matches our structural // expectations. MDNode *ProfileData = getMetadata(LLVMContext::MD_prof); if (!ProfileData || ProfileData->getNumOperands() != 3) return; // The first operand is the name. Fetch them backwards and build a new one. Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2), ProfileData->getOperand(1)}; setMetadata(LLVMContext::MD_prof, MDNode::get(ProfileData->getContext(), Ops)); } BasicBlock *BranchInst::getSuccessorV(unsigned idx) const { return getSuccessor(idx); } unsigned BranchInst::getNumSuccessorsV() const { return getNumSuccessors(); } void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) { setSuccessor(idx, B); } //===----------------------------------------------------------------------===// // AllocaInst Implementation //===----------------------------------------------------------------------===// static Value *getAISize(LLVMContext &Context, Value *Amt) { if (!Amt) Amt = ConstantInt::get(Type::getInt32Ty(Context), 1); else { assert(!isa<BasicBlock>(Amt) && "Passed basic block into allocation size parameter! Use other ctor"); assert(Amt->getType()->isIntegerTy() && "Allocation array size is not an integer!"); } return Amt; } AllocaInst::AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore) : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertBefore) {} AllocaInst::AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd) : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertAtEnd) {} AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name, Instruction *InsertBefore) : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertBefore) {} AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name, BasicBlock *InsertAtEnd) : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertAtEnd) {} AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align, const Twine &Name, Instruction *InsertBefore) : UnaryInstruction(PointerType::getUnqual(Ty), Alloca, getAISize(Ty->getContext(), ArraySize), InsertBefore), AllocatedType(Ty) { setAlignment(Align); assert(!Ty->isVoidTy() && "Cannot allocate void!"); setName(Name); } AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align, const Twine &Name, BasicBlock *InsertAtEnd) : UnaryInstruction(PointerType::getUnqual(Ty), Alloca, getAISize(Ty->getContext(), ArraySize), InsertAtEnd), AllocatedType(Ty) { setAlignment(Align); assert(!Ty->isVoidTy() && "Cannot allocate void!"); setName(Name); } // Out of line virtual method, so the vtable, etc has a home. AllocaInst::~AllocaInst() { } void AllocaInst::setAlignment(unsigned Align) { assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); assert(Align <= MaximumAlignment && "Alignment is greater than MaximumAlignment!"); setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) | (Log2_32(Align) + 1)); assert(getAlignment() == Align && "Alignment representation error!"); } bool AllocaInst::isArrayAllocation() const { if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0))) return !CI->isOne(); return true; } /// isStaticAlloca - Return true if this alloca is in the entry block of the /// function and is a constant size. If so, the code generator will fold it /// into the prolog/epilog code, so it is basically free. bool AllocaInst::isStaticAlloca() const { // Must be constant size. if (!isa<ConstantInt>(getArraySize())) return false; // Must be in the entry block. const BasicBlock *Parent = getParent(); return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca(); } //===----------------------------------------------------------------------===// // LoadInst Implementation //===----------------------------------------------------------------------===// void LoadInst::AssertOK() { assert(getOperand(0)->getType()->isPointerTy() && "Ptr must have pointer type."); assert(!(isAtomic() && getAlignment() == 0) && "Alignment required for atomic load"); } LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef) : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {} LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE) : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {} LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, Instruction *InsertBef) : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {} LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, BasicBlock *InsertAE) : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {} LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, unsigned Align, Instruction *InsertBef) : LoadInst(Ty, Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, InsertBef) {} LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, unsigned Align, BasicBlock *InsertAE) : LoadInst(Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, InsertAE) { } LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope, Instruction *InsertBef) : UnaryInstruction(Ty, Load, Ptr, InsertBef) { assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); setVolatile(isVolatile); setAlignment(Align); setAtomic(Order, SynchScope); AssertOK(); setName(Name); } LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope, BasicBlock *InsertAE) : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), Load, Ptr, InsertAE) { setVolatile(isVolatile); setAlignment(Align); setAtomic(Order, SynchScope); AssertOK(); setName(Name); } LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef) : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), Load, Ptr, InsertBef) { setVolatile(false); setAlignment(0); setAtomic(NotAtomic); AssertOK(); if (Name && Name[0]) setName(Name); } LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE) : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), Load, Ptr, InsertAE) { setVolatile(false); setAlignment(0); setAtomic(NotAtomic); AssertOK(); if (Name && Name[0]) setName(Name); } LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile, Instruction *InsertBef) : UnaryInstruction(Ty, Load, Ptr, InsertBef) { assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); setVolatile(isVolatile); setAlignment(0); setAtomic(NotAtomic); AssertOK(); if (Name && Name[0]) setName(Name); } LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile, BasicBlock *InsertAE) : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), Load, Ptr, InsertAE) { setVolatile(isVolatile); setAlignment(0); setAtomic(NotAtomic); AssertOK(); if (Name && Name[0]) setName(Name); } void LoadInst::setAlignment(unsigned Align) { assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); assert(Align <= MaximumAlignment && "Alignment is greater than MaximumAlignment!"); setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | ((Log2_32(Align)+1)<<1)); assert(getAlignment() == Align && "Alignment representation error!"); } //===----------------------------------------------------------------------===// // StoreInst Implementation //===----------------------------------------------------------------------===// void StoreInst::AssertOK() { assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!"); assert(getOperand(1)->getType()->isPointerTy() && "Ptr must have pointer type!"); assert(getOperand(0)->getType() == cast<PointerType>(getOperand(1)->getType())->getElementType() && "Ptr must be a pointer to Val type!"); assert(!(isAtomic() && getAlignment() == 0) && "Alignment required for atomic store"); } StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore) : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {} StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd) : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {} StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Instruction *InsertBefore) : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {} StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, BasicBlock *InsertAtEnd) : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {} StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align, Instruction *InsertBefore) : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread, InsertBefore) {} StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align, BasicBlock *InsertAtEnd) : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread, InsertAtEnd) {} StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope, Instruction *InsertBefore) : Instruction(Type::getVoidTy(val->getContext()), Store, OperandTraits<StoreInst>::op_begin(this), OperandTraits<StoreInst>::operands(this), InsertBefore) { Op<0>() = val; Op<1>() = addr; setVolatile(isVolatile); setAlignment(Align); setAtomic(Order, SynchScope); AssertOK(); } StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align, AtomicOrdering Order, SynchronizationScope SynchScope, BasicBlock *InsertAtEnd) : Instruction(Type::getVoidTy(val->getContext()), Store, OperandTraits<StoreInst>::op_begin(this), OperandTraits<StoreInst>::operands(this), InsertAtEnd) { Op<0>() = val; Op<1>() = addr; setVolatile(isVolatile); setAlignment(Align); setAtomic(Order, SynchScope); AssertOK(); } void StoreInst::setAlignment(unsigned Align) { assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); assert(Align <= MaximumAlignment && "Alignment is greater than MaximumAlignment!"); setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | ((Log2_32(Align)+1) << 1)); assert(getAlignment() == Align && "Alignment representation error!"); } //===----------------------------------------------------------------------===// // AtomicCmpXchgInst Implementation //===----------------------------------------------------------------------===// void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal, AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) { Op<0>() = Ptr; Op<1>() = Cmp; Op<2>() = NewVal; setSuccessOrdering(SuccessOrdering); setFailureOrdering(FailureOrdering); setSynchScope(SynchScope); assert(getOperand(0) && getOperand(1) && getOperand(2) && "All operands must be non-null!"); assert(getOperand(0)->getType()->isPointerTy() && "Ptr must have pointer type!"); assert(getOperand(1)->getType() == cast<PointerType>(getOperand(0)->getType())->getElementType() && "Ptr must be a pointer to Cmp type!"); assert(getOperand(2)->getType() == cast<PointerType>(getOperand(0)->getType())->getElementType() && "Ptr must be a pointer to NewVal type!"); assert(SuccessOrdering != NotAtomic && "AtomicCmpXchg instructions must be atomic!"); assert(FailureOrdering != NotAtomic && "AtomicCmpXchg instructions must be atomic!"); assert(SuccessOrdering >= FailureOrdering && "AtomicCmpXchg success ordering must be at least as strong as fail"); assert(FailureOrdering != Release && FailureOrdering != AcquireRelease && "AtomicCmpXchg failure ordering cannot include release semantics"); } AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, SynchronizationScope SynchScope, Instruction *InsertBefore) : Instruction( StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()), nullptr), AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) { Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope); } AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering, SynchronizationScope SynchScope, BasicBlock *InsertAtEnd) : Instruction( StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()), nullptr), AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) { Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope); } //===----------------------------------------------------------------------===// // AtomicRMWInst Implementation //===----------------------------------------------------------------------===// void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val, AtomicOrdering Ordering, SynchronizationScope SynchScope) { Op<0>() = Ptr; Op<1>() = Val; setOperation(Operation); setOrdering(Ordering); setSynchScope(SynchScope); assert(getOperand(0) && getOperand(1) && "All operands must be non-null!"); assert(getOperand(0)->getType()->isPointerTy() && "Ptr must have pointer type!"); assert(getOperand(1)->getType() == cast<PointerType>(getOperand(0)->getType())->getElementType() && "Ptr must be a pointer to Val type!"); assert(Ordering != NotAtomic && "AtomicRMW instructions must be atomic!"); } AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, AtomicOrdering Ordering, SynchronizationScope SynchScope, Instruction *InsertBefore) : Instruction(Val->getType(), AtomicRMW, OperandTraits<AtomicRMWInst>::op_begin(this), OperandTraits<AtomicRMWInst>::operands(this), InsertBefore) { Init(Operation, Ptr, Val, Ordering, SynchScope); } AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, AtomicOrdering Ordering, SynchronizationScope SynchScope, BasicBlock *InsertAtEnd) : Instruction(Val->getType(), AtomicRMW, OperandTraits<AtomicRMWInst>::op_begin(this), OperandTraits<AtomicRMWInst>::operands(this), InsertAtEnd) { Init(Operation, Ptr, Val, Ordering, SynchScope); } //===----------------------------------------------------------------------===// // FenceInst Implementation //===----------------------------------------------------------------------===// FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, SynchronizationScope SynchScope, Instruction *InsertBefore) : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) { setOrdering(Ordering); setSynchScope(SynchScope); } FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, SynchronizationScope SynchScope, BasicBlock *InsertAtEnd) : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) { setOrdering(Ordering); setSynchScope(SynchScope); } //===----------------------------------------------------------------------===// // GetElementPtrInst Implementation //===----------------------------------------------------------------------===// void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &Name) { assert(getNumOperands() == 1 + IdxList.size() && "NumOperands not initialized?"); Op<0>() = Ptr; std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1); setName(Name); } GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI) : Instruction(GEPI.getType(), GetElementPtr, OperandTraits<GetElementPtrInst>::op_end(this) - GEPI.getNumOperands(), GEPI.getNumOperands()), SourceElementType(GEPI.SourceElementType), ResultElementType(GEPI.ResultElementType) { std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin()); SubclassOptionalData = GEPI.SubclassOptionalData; } /// getIndexedType - Returns the type of the element that would be accessed with /// a gep instruction with the specified parameters. /// /// The Idxs pointer should point to a continuous piece of memory containing the /// indices, either as Value* or uint64_t. /// /// A null type is returned if the indices are invalid for the specified /// pointer type. /// template <typename IndexTy> static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) { // Handle the special case of the empty set index set, which is always valid. if (IdxList.empty()) return Agg; // If there is at least one index, the top level type must be sized, otherwise // it cannot be 'stepped over'. if (!Agg->isSized()) return nullptr; unsigned CurIdx = 1; for (; CurIdx != IdxList.size(); ++CurIdx) { CompositeType *CT = dyn_cast<CompositeType>(Agg); if (!CT || CT->isPointerTy()) return nullptr; IndexTy Index = IdxList[CurIdx]; if (!CT->indexValid(Index)) return nullptr; Agg = CT->getTypeAtIndex(Index); } return CurIdx == IdxList.size() ? Agg : nullptr; } Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) { return getIndexedTypeInternal(Ty, IdxList); } Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList) { return getIndexedTypeInternal(Ty, IdxList); } Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) { return getIndexedTypeInternal(Ty, IdxList); } /// hasAllZeroIndices - Return true if all of the indices of this GEP are /// zeros. If so, the result pointer and the first operand have the same /// value, just potentially different types. bool GetElementPtrInst::hasAllZeroIndices() const { for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) { if (!CI->isZero()) return false; } else { return false; } } return true; } /// hasAllConstantIndices - Return true if all of the indices of this GEP are /// constant integers. If so, the result pointer and the first operand have /// a constant offset between them. bool GetElementPtrInst::hasAllConstantIndices() const { for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { if (!isa<ConstantInt>(getOperand(i))) return false; } return true; } void GetElementPtrInst::setIsInBounds(bool B) { cast<GEPOperator>(this)->setIsInBounds(B); } bool GetElementPtrInst::isInBounds() const { return cast<GEPOperator>(this)->isInBounds(); } bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const { // Delegate to the generic GEPOperator implementation. return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset); } //===----------------------------------------------------------------------===// // ExtractElementInst Implementation //===----------------------------------------------------------------------===// ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, const Twine &Name, Instruction *InsertBef) : Instruction(cast<VectorType>(Val->getType())->getElementType(), ExtractElement, OperandTraits<ExtractElementInst>::op_begin(this), 2, InsertBef) { assert(isValidOperands(Val, Index) && "Invalid extractelement instruction operands!"); Op<0>() = Val; Op<1>() = Index; setName(Name); } ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, const Twine &Name, BasicBlock *InsertAE) : Instruction(cast<VectorType>(Val->getType())->getElementType(), ExtractElement, OperandTraits<ExtractElementInst>::op_begin(this), 2, InsertAE) { assert(isValidOperands(Val, Index) && "Invalid extractelement instruction operands!"); Op<0>() = Val; Op<1>() = Index; setName(Name); } bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy()) return false; return true; } //===----------------------------------------------------------------------===// // InsertElementInst Implementation //===----------------------------------------------------------------------===// InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, const Twine &Name, Instruction *InsertBef) : Instruction(Vec->getType(), InsertElement, OperandTraits<InsertElementInst>::op_begin(this), 3, InsertBef) { assert(isValidOperands(Vec, Elt, Index) && "Invalid insertelement instruction operands!"); Op<0>() = Vec; Op<1>() = Elt; Op<2>() = Index; setName(Name); } InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, const Twine &Name, BasicBlock *InsertAE) : Instruction(Vec->getType(), InsertElement, OperandTraits<InsertElementInst>::op_begin(this), 3, InsertAE) { assert(isValidOperands(Vec, Elt, Index) && "Invalid insertelement instruction operands!"); Op<0>() = Vec; Op<1>() = Elt; Op<2>() = Index; setName(Name); } bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, const Value *Index) { if (!Vec->getType()->isVectorTy()) return false; // First operand of insertelement must be vector type. if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType()) return false;// Second operand of insertelement must be vector element type. if (!Index->getType()->isIntegerTy()) return false; // Third operand of insertelement must be i32. return true; } //===----------------------------------------------------------------------===// // ShuffleVectorInst Implementation //===----------------------------------------------------------------------===// ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, const Twine &Name, Instruction *InsertBefore) : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), cast<VectorType>(Mask->getType())->getNumElements()), ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) { assert(isValidOperands(V1, V2, Mask) && "Invalid shuffle vector instruction operands!"); Op<0>() = V1; Op<1>() = V2; Op<2>() = Mask; setName(Name); } ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, const Twine &Name, BasicBlock *InsertAtEnd) : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), cast<VectorType>(Mask->getType())->getNumElements()), ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this), OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) { assert(isValidOperands(V1, V2, Mask) && "Invalid shuffle vector instruction operands!"); Op<0>() = V1; Op<1>() = V2; Op<2>() = Mask; setName(Name); } bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, const Value *Mask) { // V1 and V2 must be vectors of the same type. if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType()) return false; // Mask must be vector of i32. VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType()); if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32)) return false; // Check to see if Mask is valid. if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask)) return true; if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) { unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); for (Value *Op : MV->operands()) { if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) { if (CI->uge(V1Size*2)) return false; } else if (!isa<UndefValue>(Op)) { return false; } } return true; } if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(Mask)) { unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i) if (CDS->getElementAsInteger(i) >= V1Size*2) return false; return true; } // The bitcode reader can create a place holder for a forward reference // used as the shuffle mask. When this occurs, the shuffle mask will // fall into this case and fail. To avoid this error, do this bit of // ugliness to allow such a mask pass. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask)) if (CE->getOpcode() == Instruction::UserOp1) return true; return false; } /// getMaskValue - Return the index from the shuffle mask for the specified /// output result. This is either -1 if the element is undef or a number less /// than 2*numelements. int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) { assert(i < Mask->getType()->getVectorNumElements() && "Index out of range"); if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask)) return CDS->getElementAsInteger(i); Constant *C = Mask->getAggregateElement(i); if (isa<UndefValue>(C)) return -1; return cast<ConstantInt>(C)->getZExtValue(); } /// getShuffleMask - Return the full mask for this instruction, where each /// element is the element number and undef's are returned as -1. void ShuffleVectorInst::getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result) { unsigned NumElts = Mask->getType()->getVectorNumElements(); if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) { for (unsigned i = 0; i != NumElts; ++i) Result.push_back(CDS->getElementAsInteger(i)); return; } for (unsigned i = 0; i != NumElts; ++i) { Constant *C = Mask->getAggregateElement(i); Result.push_back(isa<UndefValue>(C) ? -1 : cast<ConstantInt>(C)->getZExtValue()); } } //===----------------------------------------------------------------------===// // InsertValueInst Class //===----------------------------------------------------------------------===// void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const Twine &Name) { assert(getNumOperands() == 2 && "NumOperands not initialized?"); // There's no fundamental reason why we require at least one index // (other than weirdness with &*IdxBegin being invalid; see // getelementptr's init routine for example). But there's no // present need to support it. assert(Idxs.size() > 0 && "InsertValueInst must have at least one index"); assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) == Val->getType() && "Inserted value must match indexed type!"); Op<0>() = Agg; Op<1>() = Val; Indices.append(Idxs.begin(), Idxs.end()); setName(Name); } InsertValueInst::InsertValueInst(const InsertValueInst &IVI) : Instruction(IVI.getType(), InsertValue, OperandTraits<InsertValueInst>::op_begin(this), 2), Indices(IVI.Indices) { Op<0>() = IVI.getOperand(0); Op<1>() = IVI.getOperand(1); SubclassOptionalData = IVI.SubclassOptionalData; } //===----------------------------------------------------------------------===// // ExtractValueInst Class //===----------------------------------------------------------------------===// void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) { assert(getNumOperands() == 1 && "NumOperands not initialized?"); // There's no fundamental reason why we require at least one index. // But there's no present need to support it. assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index"); Indices.append(Idxs.begin(), Idxs.end()); setName(Name); } ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI) : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)), Indices(EVI.Indices) { SubclassOptionalData = EVI.SubclassOptionalData; } // getIndexedType - Returns the type of the element that would be extracted // with an extractvalue instruction with the specified parameters. // // A null type is returned if the indices are invalid for the specified // pointer type. // Type *ExtractValueInst::getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs) { for (unsigned Index : Idxs) { // We can't use CompositeType::indexValid(Index) here. // indexValid() always returns true for arrays because getelementptr allows // out-of-bounds indices. Since we don't allow those for extractvalue and // insertvalue we need to check array indexing manually. // Since the only other types we can index into are struct types it's just // as easy to check those manually as well. if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) { if (Index >= AT->getNumElements()) return nullptr; } else if (StructType *ST = dyn_cast<StructType>(Agg)) { if (Index >= ST->getNumElements()) return nullptr; } else { // Not a valid type to index into. return nullptr; } Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index); } return const_cast<Type*>(Agg); } //===----------------------------------------------------------------------===// // BinaryOperator Class //===----------------------------------------------------------------------===// BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty, const Twine &Name, Instruction *InsertBefore) : Instruction(Ty, iType, OperandTraits<BinaryOperator>::op_begin(this), OperandTraits<BinaryOperator>::operands(this), InsertBefore) { Op<0>() = S1; Op<1>() = S2; init(iType); setName(Name); } BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd) : Instruction(Ty, iType, OperandTraits<BinaryOperator>::op_begin(this), OperandTraits<BinaryOperator>::operands(this), InsertAtEnd) { Op<0>() = S1; Op<1>() = S2; init(iType); setName(Name); } void BinaryOperator::init(BinaryOps iType) { Value *LHS = getOperand(0), *RHS = getOperand(1); (void)LHS; (void)RHS; // Silence warnings. assert(LHS->getType() == RHS->getType() && "Binary operator operand types must match!"); #ifndef NDEBUG switch (iType) { case Add: case Sub: case Mul: assert(getType() == LHS->getType() && "Arithmetic operation should return same type as operands!"); assert(getType()->isIntOrIntVectorTy() && "Tried to create an integer operation on a non-integer type!"); break; case FAdd: case FSub: case FMul: assert(getType() == LHS->getType() && "Arithmetic operation should return same type as operands!"); assert(getType()->isFPOrFPVectorTy() && "Tried to create a floating-point operation on a " "non-floating-point type!"); break; case UDiv: case SDiv: assert(getType() == LHS->getType() && "Arithmetic operation should return same type as operands!"); assert((getType()->isIntegerTy() || (getType()->isVectorTy() && cast<VectorType>(getType())->getElementType()->isIntegerTy())) && "Incorrect operand type (not integer) for S/UDIV"); break; case FDiv: assert(getType() == LHS->getType() && "Arithmetic operation should return same type as operands!"); assert(getType()->isFPOrFPVectorTy() && "Incorrect operand type (not floating point) for FDIV"); break; case URem: case SRem: assert(getType() == LHS->getType() && "Arithmetic operation should return same type as operands!"); assert((getType()->isIntegerTy() || (getType()->isVectorTy() && cast<VectorType>(getType())->getElementType()->isIntegerTy())) && "Incorrect operand type (not integer) for S/UREM"); break; case FRem: assert(getType() == LHS->getType() && "Arithmetic operation should return same type as operands!"); assert(getType()->isFPOrFPVectorTy() && "Incorrect operand type (not floating point) for FREM"); break; case Shl: case LShr: case AShr: assert(getType() == LHS->getType() && "Shift operation should return same type as operands!"); assert((getType()->isIntegerTy() || (getType()->isVectorTy() && cast<VectorType>(getType())->getElementType()->isIntegerTy())) && "Tried to create a shift operation on a non-integral type!"); break; case And: case Or: case Xor: assert(getType() == LHS->getType() && "Logical operation should return same type as operands!"); assert((getType()->isIntegerTy() || (getType()->isVectorTy() && cast<VectorType>(getType())->getElementType()->isIntegerTy())) && "Tried to create a logical operation on a non-integral type!"); break; default: break; } #endif } BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore) { assert(S1->getType() == S2->getType() && "Cannot create binary operator with two operands of differing type!"); return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore); } BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name, BasicBlock *InsertAtEnd) { BinaryOperator *Res = Create(Op, S1, S2, Name); InsertAtEnd->getInstList().push_back(Res); return Res; } BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, Instruction *InsertBefore) { Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); return new BinaryOperator(Instruction::Sub, zero, Op, Op->getType(), Name, InsertBefore); } BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, BasicBlock *InsertAtEnd) { Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); return new BinaryOperator(Instruction::Sub, zero, Op, Op->getType(), Name, InsertAtEnd); } BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, Instruction *InsertBefore) { Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore); } BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, BasicBlock *InsertAtEnd) { Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd); } BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, Instruction *InsertBefore) { Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore); } BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, BasicBlock *InsertAtEnd) { Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd); } BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name, Instruction *InsertBefore) { Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); return new BinaryOperator(Instruction::FSub, zero, Op, Op->getType(), Name, InsertBefore); } BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name, BasicBlock *InsertAtEnd) { Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); return new BinaryOperator(Instruction::FSub, zero, Op, Op->getType(), Name, InsertAtEnd); } BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, Instruction *InsertBefore) { Constant *C = Constant::getAllOnesValue(Op->getType()); return new BinaryOperator(Instruction::Xor, Op, C, Op->getType(), Name, InsertBefore); } BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, BasicBlock *InsertAtEnd) { Constant *AllOnes = Constant::getAllOnesValue(Op->getType()); return new BinaryOperator(Instruction::Xor, Op, AllOnes, Op->getType(), Name, InsertAtEnd); } // isConstantAllOnes - Helper function for several functions below static inline bool isConstantAllOnes(const Value *V) { if (const Constant *C = dyn_cast<Constant>(V)) return C->isAllOnesValue(); return false; } bool BinaryOperator::isNeg(const Value *V) { if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) if (Bop->getOpcode() == Instruction::Sub) if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) return C->isNegativeZeroValue(); return false; } bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) { if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) if (Bop->getOpcode() == Instruction::FSub) if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) { if (!IgnoreZeroSign) IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros(); return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue(); } return false; } bool BinaryOperator::isNot(const Value *V) { if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) return (Bop->getOpcode() == Instruction::Xor && (isConstantAllOnes(Bop->getOperand(1)) || isConstantAllOnes(Bop->getOperand(0)))); return false; } Value *BinaryOperator::getNegArgument(Value *BinOp) { return cast<BinaryOperator>(BinOp)->getOperand(1); } const Value *BinaryOperator::getNegArgument(const Value *BinOp) { return getNegArgument(const_cast<Value*>(BinOp)); } Value *BinaryOperator::getFNegArgument(Value *BinOp) { return cast<BinaryOperator>(BinOp)->getOperand(1); } const Value *BinaryOperator::getFNegArgument(const Value *BinOp) { return getFNegArgument(const_cast<Value*>(BinOp)); } Value *BinaryOperator::getNotArgument(Value *BinOp) { assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!"); BinaryOperator *BO = cast<BinaryOperator>(BinOp); Value *Op0 = BO->getOperand(0); Value *Op1 = BO->getOperand(1); if (isConstantAllOnes(Op0)) return Op1; assert(isConstantAllOnes(Op1)); return Op0; } const Value *BinaryOperator::getNotArgument(const Value *BinOp) { return getNotArgument(const_cast<Value*>(BinOp)); } // swapOperands - Exchange the two operands to this instruction. This // instruction is safe to use on any binary instruction and does not // modify the semantics of the instruction. If the instruction is // order dependent (SetLT f.e.) the opcode is changed. // bool BinaryOperator::swapOperands() { if (!isCommutative()) return true; // Can't commute operands Op<0>().swap(Op<1>()); return false; } void BinaryOperator::setHasNoUnsignedWrap(bool b) { cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b); } void BinaryOperator::setHasNoSignedWrap(bool b) { cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b); } void BinaryOperator::setIsExact(bool b) { cast<PossiblyExactOperator>(this)->setIsExact(b); } bool BinaryOperator::hasNoUnsignedWrap() const { return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap(); } bool BinaryOperator::hasNoSignedWrap() const { return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap(); } bool BinaryOperator::isExact() const { return cast<PossiblyExactOperator>(this)->isExact(); } void BinaryOperator::copyIRFlags(const Value *V) { // Copy the wrapping flags. if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) { setHasNoSignedWrap(OB->hasNoSignedWrap()); setHasNoUnsignedWrap(OB->hasNoUnsignedWrap()); } // Copy the exact flag. if (auto *PE = dyn_cast<PossiblyExactOperator>(V)) setIsExact(PE->isExact()); // Copy the fast-math flags. if (auto *FP = dyn_cast<FPMathOperator>(V)) copyFastMathFlags(FP->getFastMathFlags()); } void BinaryOperator::andIRFlags(const Value *V) { if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) { setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap()); setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap()); } if (auto *PE = dyn_cast<PossiblyExactOperator>(V)) setIsExact(isExact() & PE->isExact()); if (auto *FP = dyn_cast<FPMathOperator>(V)) { FastMathFlags FM = getFastMathFlags(); FM &= FP->getFastMathFlags(); copyFastMathFlags(FM); } } //===----------------------------------------------------------------------===// // FPMathOperator Class //===----------------------------------------------------------------------===// /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs. /// An accuracy of 0.0 means that the operation should be performed with the /// default precision. float FPMathOperator::getFPAccuracy() const { const MDNode *MD = cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath); if (!MD) return 0.0; ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0)); return Accuracy->getValueAPF().convertToFloat(); } //===----------------------------------------------------------------------===// // CastInst Class //===----------------------------------------------------------------------===// void CastInst::anchor() {} // Just determine if this cast only deals with integral->integral conversion. bool CastInst::isIntegerCast() const { switch (getOpcode()) { default: return false; case Instruction::ZExt: case Instruction::SExt: case Instruction::Trunc: return true; case Instruction::BitCast: return getOperand(0)->getType()->isIntegerTy() && getType()->isIntegerTy(); } } bool CastInst::isLosslessCast() const { // Only BitCast can be lossless, exit fast if we're not BitCast if (getOpcode() != Instruction::BitCast) return false; // Identity cast is always lossless Type* SrcTy = getOperand(0)->getType(); Type* DstTy = getType(); if (SrcTy == DstTy) return true; // Pointer to pointer is always lossless. if (SrcTy->isPointerTy()) return DstTy->isPointerTy(); return false; // Other types have no identity values } /// This function determines if the CastInst does not require any bits to be /// changed in order to effect the cast. Essentially, it identifies cases where /// no code gen is necessary for the cast, hence the name no-op cast. For /// example, the following are all no-op casts: /// # bitcast i32* %x to i8* /// # bitcast <2 x i32> %x to <4 x i16> /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only /// @brief Determine if the described cast is a no-op. bool CastInst::isNoopCast(Instruction::CastOps Opcode, Type *SrcTy, Type *DestTy, Type *IntPtrTy) { switch (Opcode) { default: llvm_unreachable("Invalid CastOp"); case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: case Instruction::FPTrunc: case Instruction::FPExt: case Instruction::UIToFP: case Instruction::SIToFP: case Instruction::FPToUI: case Instruction::FPToSI: case Instruction::AddrSpaceCast: // TODO: Target informations may give a more accurate answer here. return false; case Instruction::BitCast: return true; // BitCast never modifies bits. case Instruction::PtrToInt: return IntPtrTy->getScalarSizeInBits() == DestTy->getScalarSizeInBits(); case Instruction::IntToPtr: return IntPtrTy->getScalarSizeInBits() == SrcTy->getScalarSizeInBits(); } } /// @brief Determine if a cast is a no-op. bool CastInst::isNoopCast(Type *IntPtrTy) const { return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy); } bool CastInst::isNoopCast(const DataLayout &DL) const { Type *PtrOpTy = nullptr; if (getOpcode() == Instruction::PtrToInt) PtrOpTy = getOperand(0)->getType(); else if (getOpcode() == Instruction::IntToPtr) PtrOpTy = getType(); Type *IntPtrTy = PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0); return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy); } /// This function determines if a pair of casts can be eliminated and what /// opcode should be used in the elimination. This assumes that there are two /// instructions like this: /// * %F = firstOpcode SrcTy %x to MidTy /// * %S = secondOpcode MidTy %F to DstTy /// The function returns a resultOpcode so these two casts can be replaced with: /// * %Replacement = resultOpcode %SrcTy %x to DstTy /// If no such cast is permited, the function returns 0. unsigned CastInst::isEliminableCastPair( Instruction::CastOps firstOp, Instruction::CastOps secondOp, Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, Type *DstIntPtrTy) { // Define the 144 possibilities for these two cast instructions. The values // in this matrix determine what to do in a given situation and select the // case in the switch below. The rows correspond to firstOp, the columns // correspond to secondOp. In looking at the table below, keep in mind // the following cast properties: // // Size Compare Source Destination // Operator Src ? Size Type Sign Type Sign // -------- ------------ ------------------- --------------------- // TRUNC > Integer Any Integral Any // ZEXT < Integral Unsigned Integer Any // SEXT < Integral Signed Integer Any // FPTOUI n/a FloatPt n/a Integral Unsigned // FPTOSI n/a FloatPt n/a Integral Signed // UITOFP n/a Integral Unsigned FloatPt n/a // SITOFP n/a Integral Signed FloatPt n/a // FPTRUNC > FloatPt n/a FloatPt n/a // FPEXT < FloatPt n/a FloatPt n/a // PTRTOINT n/a Pointer n/a Integral Unsigned // INTTOPTR n/a Integral Unsigned Pointer n/a // BITCAST = FirstClass n/a FirstClass n/a // ADDRSPCST n/a Pointer n/a Pointer n/a // // NOTE: some transforms are safe, but we consider them to be non-profitable. // For example, we could merge "fptoui double to i32" + "zext i32 to i64", // into "fptoui double to i64", but this loses information about the range // of the produced value (we no longer know the top-part is all zeros). // Further this conversion is often much more expensive for typical hardware, // and causes issues when building libgcc. We disallow fptosi+sext for the // same reason. const unsigned numCastOps = Instruction::CastOpsEnd - Instruction::CastOpsBegin; static const uint8_t CastResults[numCastOps][numCastOps] = { // T F F U S F F P I B A -+ // R Z S P P I I T P 2 N T S | // U E E 2 2 2 2 R E I T C C +- secondOp // N X X U S F F N X N 2 V V | // C T T I I P P C T T P T T -+ { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+ { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt | { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt | { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI | { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI | { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP | { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc | { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt | { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt | { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr | { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast | { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+ }; // If either of the casts are a bitcast from scalar to vector, disallow the // merging. However, bitcast of A->B->A are allowed. bool isFirstBitcast = (firstOp == Instruction::BitCast); bool isSecondBitcast = (secondOp == Instruction::BitCast); bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast); // Check if any of the bitcasts convert scalars<->vectors. if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) || (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy))) // Unless we are bitcasing to the original type, disallow optimizations. if (!chainedBitcast) return 0; int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin] [secondOp-Instruction::CastOpsBegin]; switch (ElimCase) { case 0: // Categorically disallowed. return 0; case 1: // Allowed, use first cast's opcode. return firstOp; case 2: // Allowed, use second cast's opcode. return secondOp; case 3: // No-op cast in second op implies firstOp as long as the DestTy // is integer and we are not converting between a vector and a // non-vector type. if (!SrcTy->isVectorTy() && DstTy->isIntegerTy()) return firstOp; return 0; case 4: // No-op cast in second op implies firstOp as long as the DestTy // is floating point. if (DstTy->isFloatingPointTy()) return firstOp; return 0; case 5: // No-op cast in first op implies secondOp as long as the SrcTy // is an integer. if (SrcTy->isIntegerTy()) return secondOp; return 0; case 6: // No-op cast in first op implies secondOp as long as the SrcTy // is a floating point. if (SrcTy->isFloatingPointTy()) return secondOp; return 0; case 7: { // Cannot simplify if address spaces are different! if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) return 0; unsigned MidSize = MidTy->getScalarSizeInBits(); // We can still fold this without knowing the actual sizes as long we // know that the intermediate pointer is the largest possible // pointer size. // FIXME: Is this always true? if (MidSize == 64) return Instruction::BitCast; // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size. if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy) return 0; unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits(); if (MidSize >= PtrSize) return Instruction::BitCast; return 0; } case 8: { // ext, trunc -> bitcast, if the SrcTy and DstTy are same size // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy) // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy) unsigned SrcSize = SrcTy->getScalarSizeInBits(); unsigned DstSize = DstTy->getScalarSizeInBits(); if (SrcSize == DstSize) return Instruction::BitCast; else if (SrcSize < DstSize) return firstOp; return secondOp; } case 9: // zext, sext -> zext, because sext can't sign extend after zext return Instruction::ZExt; case 10: // fpext followed by ftrunc is allowed if the bit size returned to is // the same as the original, in which case its just a bitcast if (SrcTy == DstTy) return Instruction::BitCast; return 0; // If the types are not the same we can't eliminate it. case 11: { // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize if (!MidIntPtrTy) return 0; unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits(); unsigned SrcSize = SrcTy->getScalarSizeInBits(); unsigned DstSize = DstTy->getScalarSizeInBits(); if (SrcSize <= PtrSize && SrcSize == DstSize) return Instruction::BitCast; return 0; } case 12: { // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) return Instruction::AddrSpaceCast; return Instruction::BitCast; } case 13: // FIXME: this state can be merged with (1), but the following assert // is useful to check the correcteness of the sequence due to semantic // change of bitcast. assert( SrcTy->isPtrOrPtrVectorTy() && MidTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() && SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() && MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && "Illegal addrspacecast, bitcast sequence!"); // Allowed, use first cast's opcode return firstOp; case 14: // bitcast, addrspacecast -> addrspacecast if the element type of // bitcast's source is the same as that of addrspacecast's destination. if (SrcTy->getPointerElementType() == DstTy->getPointerElementType()) return Instruction::AddrSpaceCast; return 0; case 15: // FIXME: this state can be merged with (1), but the following assert // is useful to check the correcteness of the sequence due to semantic // change of bitcast. assert( SrcTy->isIntOrIntVectorTy() && MidTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() && MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && "Illegal inttoptr, bitcast sequence!"); // Allowed, use first cast's opcode return firstOp; case 16: // FIXME: this state can be merged with (2), but the following assert // is useful to check the correcteness of the sequence due to semantic // change of bitcast. assert( SrcTy->isPtrOrPtrVectorTy() && MidTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy() && SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() && "Illegal bitcast, ptrtoint sequence!"); // Allowed, use second cast's opcode return secondOp; case 17: // (sitofp (zext x)) -> (uitofp x) return Instruction::UIToFP; case 99: // Cast combination can't happen (error in input). This is for all cases // where the MidTy is not the same for the two cast instructions. llvm_unreachable("Invalid Cast Combination"); default: llvm_unreachable("Error in CastResults table!!!"); } } CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore) { assert(castIsValid(op, S, Ty) && "Invalid cast!"); // Construct and return the appropriate CastInst subclass switch (op) { case Trunc: return new TruncInst (S, Ty, Name, InsertBefore); case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore); case SExt: return new SExtInst (S, Ty, Name, InsertBefore); case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore); case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore); case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore); case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore); case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore); case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore); case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore); case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore); case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore); case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore); default: llvm_unreachable("Invalid opcode provided"); } } CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd) { assert(castIsValid(op, S, Ty) && "Invalid cast!"); // Construct and return the appropriate CastInst subclass switch (op) { case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd); case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd); case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd); case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd); case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd); case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd); case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd); case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd); case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd); case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd); case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd); case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd); case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd); default: llvm_unreachable("Invalid opcode provided"); } } CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore) { if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); return Create(Instruction::ZExt, S, Ty, Name, InsertBefore); } CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd) { if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd); } CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore) { if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); return Create(Instruction::SExt, S, Ty, Name, InsertBefore); } CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd) { if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd); } CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore) { if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); return Create(Instruction::Trunc, S, Ty, Name, InsertBefore); } CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd) { if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd); } CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd) { assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && "Invalid cast"); assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); assert((!Ty->isVectorTy() || Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) && "Invalid cast"); if (Ty->isIntOrIntVectorTy()) return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd); return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd); } /// @brief Create a BitCast or a PtrToInt cast instruction CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore) { assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && "Invalid cast"); assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); assert((!Ty->isVectorTy() || Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) && "Invalid cast"); if (Ty->isIntOrIntVectorTy()) return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore); } CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd) { assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd); return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); } CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore) { assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore); return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); } CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore) { if (S->getType()->isPointerTy() && Ty->isIntegerTy()) return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); if (S->getType()->isIntegerTy() && Ty->isPointerTy()) return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore); return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); } CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, bool isSigned, const Twine &Name, Instruction *InsertBefore) { assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && "Invalid integer cast"); unsigned SrcBits = C->getType()->getScalarSizeInBits(); unsigned DstBits = Ty->getScalarSizeInBits(); Instruction::CastOps opcode = (SrcBits == DstBits ? Instruction::BitCast : (SrcBits > DstBits ? Instruction::Trunc : (isSigned ? Instruction::SExt : Instruction::ZExt))); return Create(opcode, C, Ty, Name, InsertBefore); } CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, bool isSigned, const Twine &Name, BasicBlock *InsertAtEnd) { assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && "Invalid cast"); unsigned SrcBits = C->getType()->getScalarSizeInBits(); unsigned DstBits = Ty->getScalarSizeInBits(); Instruction::CastOps opcode = (SrcBits == DstBits ? Instruction::BitCast : (SrcBits > DstBits ? Instruction::Trunc : (isSigned ? Instruction::SExt : Instruction::ZExt))); return Create(opcode, C, Ty, Name, InsertAtEnd); } CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, const Twine &Name, Instruction *InsertBefore) { assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && "Invalid cast"); unsigned SrcBits = C->getType()->getScalarSizeInBits(); unsigned DstBits = Ty->getScalarSizeInBits(); Instruction::CastOps opcode = (SrcBits == DstBits ? Instruction::BitCast : (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); return Create(opcode, C, Ty, Name, InsertBefore); } CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd) { assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && "Invalid cast"); unsigned SrcBits = C->getType()->getScalarSizeInBits(); unsigned DstBits = Ty->getScalarSizeInBits(); Instruction::CastOps opcode = (SrcBits == DstBits ? Instruction::BitCast : (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); return Create(opcode, C, Ty, Name, InsertAtEnd); } // Check whether it is valid to call getCastOpcode for these types. // This routine must be kept in sync with getCastOpcode. bool CastInst::isCastable(Type *SrcTy, Type *DestTy) { if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) return false; if (SrcTy == DestTy) return true; if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { // An element by element cast. Valid if casting the elements is valid. SrcTy = SrcVecTy->getElementType(); DestTy = DestVecTy->getElementType(); } // Get the bit sizes, we'll need these unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr // Run through the possibilities ... if (DestTy->isIntegerTy()) { // Casting to integral if (SrcTy->isIntegerTy()) // Casting from integral return true; if (SrcTy->isFloatingPointTy()) // Casting from floating pt return true; if (SrcTy->isVectorTy()) // Casting from vector return DestBits == SrcBits; // Casting from something else return SrcTy->isPointerTy(); } if (DestTy->isFloatingPointTy()) { // Casting to floating pt if (SrcTy->isIntegerTy()) // Casting from integral return true; if (SrcTy->isFloatingPointTy()) // Casting from floating pt return true; if (SrcTy->isVectorTy()) // Casting from vector return DestBits == SrcBits; // Casting from something else return false; } if (DestTy->isVectorTy()) // Casting to vector return DestBits == SrcBits; if (DestTy->isPointerTy()) { // Casting to pointer if (SrcTy->isPointerTy()) // Casting from pointer return true; return SrcTy->isIntegerTy(); // Casting from integral } if (DestTy->isX86_MMXTy()) { if (SrcTy->isVectorTy()) return DestBits == SrcBits; // 64-bit vector to MMX return false; } // Casting to something else return false; } bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) { if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) return false; if (SrcTy == DestTy) return true; if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) { if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { // An element by element cast. Valid if casting the elements is valid. SrcTy = SrcVecTy->getElementType(); DestTy = DestVecTy->getElementType(); } } } if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) { if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) { return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace(); } } unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr // Could still have vectors of pointers if the number of elements doesn't // match if (SrcBits == 0 || DestBits == 0) return false; if (SrcBits != DestBits) return false; if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy()) return false; return true; } bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL) { if (auto *PtrTy = dyn_cast<PointerType>(SrcTy)) if (auto *IntTy = dyn_cast<IntegerType>(DestTy)) return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy); if (auto *PtrTy = dyn_cast<PointerType>(DestTy)) if (auto *IntTy = dyn_cast<IntegerType>(SrcTy)) return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy); return isBitCastable(SrcTy, DestTy); } // Provide a way to get a "cast" where the cast opcode is inferred from the // types and size of the operand. This, basically, is a parallel of the // logic in the castIsValid function below. This axiom should hold: // castIsValid( getCastOpcode(Val, Ty), Val, Ty) // should not assert in castIsValid. In other words, this produces a "correct" // casting opcode for the arguments passed to it. // This routine must be kept in sync with isCastable. Instruction::CastOps CastInst::getCastOpcode( const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) { Type *SrcTy = Src->getType(); assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() && "Only first class types are castable!"); if (SrcTy == DestTy) return BitCast; // FIXME: Check address space sizes here if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { // An element by element cast. Find the appropriate opcode based on the // element types. SrcTy = SrcVecTy->getElementType(); DestTy = DestVecTy->getElementType(); } // Get the bit sizes, we'll need these unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr // Run through the possibilities ... if (DestTy->isIntegerTy()) { // Casting to integral if (SrcTy->isIntegerTy()) { // Casting from integral if (DestBits < SrcBits) return Trunc; // int -> smaller int else if (DestBits > SrcBits) { // its an extension if (SrcIsSigned) return SExt; // signed -> SEXT else return ZExt; // unsigned -> ZEXT } else { return BitCast; // Same size, No-op cast } } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt if (DestIsSigned) return FPToSI; // FP -> sint else return FPToUI; // FP -> uint } else if (SrcTy->isVectorTy()) { assert(DestBits == SrcBits && "Casting vector to integer of different width"); return BitCast; // Same size, no-op cast } else { assert(SrcTy->isPointerTy() && "Casting from a value that is not first-class type"); return PtrToInt; // ptr -> int } } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt if (SrcTy->isIntegerTy()) { // Casting from integral if (SrcIsSigned) return SIToFP; // sint -> FP else return UIToFP; // uint -> FP } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt if (DestBits < SrcBits) { return FPTrunc; // FP -> smaller FP } else if (DestBits > SrcBits) { return FPExt; // FP -> larger FP } else { return BitCast; // same size, no-op cast } } else if (SrcTy->isVectorTy()) { assert(DestBits == SrcBits && "Casting vector to floating point of different width"); return BitCast; // same size, no-op cast } llvm_unreachable("Casting pointer or non-first class to float"); } else if (DestTy->isVectorTy()) { assert(DestBits == SrcBits && "Illegal cast to vector (wrong type or size)"); return BitCast; } else if (DestTy->isPointerTy()) { if (SrcTy->isPointerTy()) { if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace()) return AddrSpaceCast; return BitCast; // ptr -> ptr } else if (SrcTy->isIntegerTy()) { return IntToPtr; // int -> ptr } llvm_unreachable("Casting pointer to other than pointer or int"); } else if (DestTy->isX86_MMXTy()) { if (SrcTy->isVectorTy()) { assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX"); return BitCast; // 64-bit vector to MMX } llvm_unreachable("Illegal cast to X86_MMX"); } llvm_unreachable("Casting to type that is not first-class"); } //===----------------------------------------------------------------------===// // CastInst SubClass Constructors //===----------------------------------------------------------------------===// /// Check that the construction parameters for a CastInst are correct. This /// could be broken out into the separate constructors but it is useful to have /// it in one place and to eliminate the redundant code for getting the sizes /// of the types involved. bool CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) { // Check for type sanity on the arguments Type *SrcTy = S->getType(); if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() || SrcTy->isAggregateType() || DstTy->isAggregateType()) return false; // Get the size of the types in bits, we'll need this later unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); unsigned DstBitSize = DstTy->getScalarSizeInBits(); // If these are vector types, get the lengths of the vectors (using zero for // scalar types means that checking that vector lengths match also checks that // scalars are not being converted to vectors or vectors to scalars). unsigned SrcLength = SrcTy->isVectorTy() ? cast<VectorType>(SrcTy)->getNumElements() : 0; unsigned DstLength = DstTy->isVectorTy() ? cast<VectorType>(DstTy)->getNumElements() : 0; // Switch on the opcode provided switch (op) { default: return false; // This is an input error case Instruction::Trunc: return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && SrcLength == DstLength && SrcBitSize > DstBitSize; case Instruction::ZExt: return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && SrcLength == DstLength && SrcBitSize < DstBitSize; case Instruction::SExt: return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && SrcLength == DstLength && SrcBitSize < DstBitSize; case Instruction::FPTrunc: return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && SrcLength == DstLength && SrcBitSize > DstBitSize; case Instruction::FPExt: return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && SrcLength == DstLength && SrcBitSize < DstBitSize; case Instruction::UIToFP: case Instruction::SIToFP: return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() && SrcLength == DstLength; case Instruction::FPToUI: case Instruction::FPToSI: return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() && SrcLength == DstLength; case Instruction::PtrToInt: if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy)) return false; if (VectorType *VT = dyn_cast<VectorType>(SrcTy)) if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements()) return false; return SrcTy->getScalarType()->isPointerTy() && DstTy->getScalarType()->isIntegerTy(); case Instruction::IntToPtr: if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy)) return false; if (VectorType *VT = dyn_cast<VectorType>(SrcTy)) if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements()) return false; return SrcTy->getScalarType()->isIntegerTy() && DstTy->getScalarType()->isPointerTy(); case Instruction::BitCast: { PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); // BitCast implies a no-op cast of type only. No bits change. // However, you can't cast pointers to anything but pointers. if (!SrcPtrTy != !DstPtrTy) return false; // For non-pointer cases, the cast is okay if the source and destination bit // widths are identical. if (!SrcPtrTy) return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits(); // If both are pointers then the address spaces must match. if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) return false; // A vector of pointers must have the same number of elements. if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy)) return (SrcVecTy->getNumElements() == DstVecTy->getNumElements()); return false; } return true; } case Instruction::AddrSpaceCast: { PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); if (!SrcPtrTy) return false; PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); if (!DstPtrTy) return false; if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) return false; if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy)) return (SrcVecTy->getNumElements() == DstVecTy->getNumElements()); return false; } return true; } } } TruncInst::TruncInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, Trunc, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); } TruncInst::TruncInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); } ZExtInst::ZExtInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, ZExt, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); } ZExtInst::ZExtInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); } SExtInst::SExtInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, SExt, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); } SExtInst::SExtInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); } FPTruncInst::FPTruncInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); } FPTruncInst::FPTruncInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); } FPExtInst::FPExtInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); } FPExtInst::FPExtInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); } UIToFPInst::UIToFPInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); } UIToFPInst::UIToFPInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); } SIToFPInst::SIToFPInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); } SIToFPInst::SIToFPInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); } FPToUIInst::FPToUIInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); } FPToUIInst::FPToUIInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); } FPToSIInst::FPToSIInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); } FPToSIInst::FPToSIInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); } PtrToIntInst::PtrToIntInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); } PtrToIntInst::PtrToIntInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); } IntToPtrInst::IntToPtrInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); } IntToPtrInst::IntToPtrInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); } BitCastInst::BitCastInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); } BitCastInst::BitCastInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); } AddrSpaceCastInst::AddrSpaceCastInst( Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); } AddrSpaceCastInst::AddrSpaceCastInst( Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) { assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); } //===----------------------------------------------------------------------===// // CmpInst Classes //===----------------------------------------------------------------------===// void CmpInst::anchor() {} CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate, Value *LHS, Value *RHS, const Twine &Name, Instruction *InsertBefore) : Instruction(ty, op, OperandTraits<CmpInst>::op_begin(this), OperandTraits<CmpInst>::operands(this), InsertBefore) { Op<0>() = LHS; Op<1>() = RHS; setPredicate((Predicate)predicate); setName(Name); } CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate, Value *LHS, Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd) : Instruction(ty, op, OperandTraits<CmpInst>::op_begin(this), OperandTraits<CmpInst>::operands(this), InsertAtEnd) { Op<0>() = LHS; Op<1>() = RHS; setPredicate((Predicate)predicate); setName(Name); } CmpInst * CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore) { if (Op == Instruction::ICmp) { if (InsertBefore) return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate), S1, S2, Name); else return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name); } if (InsertBefore) return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate), S1, S2, Name); else return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name); } CmpInst * CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, const Twine &Name, BasicBlock *InsertAtEnd) { if (Op == Instruction::ICmp) { return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), S1, S2, Name); } return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), S1, S2, Name); } void CmpInst::swapOperands() { if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) IC->swapOperands(); else cast<FCmpInst>(this)->swapOperands(); } bool CmpInst::isCommutative() const { if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) return IC->isCommutative(); return cast<FCmpInst>(this)->isCommutative(); } bool CmpInst::isEquality() const { if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) return IC->isEquality(); return cast<FCmpInst>(this)->isEquality(); } CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { switch (pred) { default: llvm_unreachable("Unknown cmp predicate!"); case ICMP_EQ: return ICMP_NE; case ICMP_NE: return ICMP_EQ; case ICMP_UGT: return ICMP_ULE; case ICMP_ULT: return ICMP_UGE; case ICMP_UGE: return ICMP_ULT; case ICMP_ULE: return ICMP_UGT; case ICMP_SGT: return ICMP_SLE; case ICMP_SLT: return ICMP_SGE; case ICMP_SGE: return ICMP_SLT; case ICMP_SLE: return ICMP_SGT; case FCMP_OEQ: return FCMP_UNE; case FCMP_ONE: return FCMP_UEQ; case FCMP_OGT: return FCMP_ULE; case FCMP_OLT: return FCMP_UGE; case FCMP_OGE: return FCMP_ULT; case FCMP_OLE: return FCMP_UGT; case FCMP_UEQ: return FCMP_ONE; case FCMP_UNE: return FCMP_OEQ; case FCMP_UGT: return FCMP_OLE; case FCMP_ULT: return FCMP_OGE; case FCMP_UGE: return FCMP_OLT; case FCMP_ULE: return FCMP_OGT; case FCMP_ORD: return FCMP_UNO; case FCMP_UNO: return FCMP_ORD; case FCMP_TRUE: return FCMP_FALSE; case FCMP_FALSE: return FCMP_TRUE; } } ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) { switch (pred) { default: llvm_unreachable("Unknown icmp predicate!"); case ICMP_EQ: case ICMP_NE: case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: return pred; case ICMP_UGT: return ICMP_SGT; case ICMP_ULT: return ICMP_SLT; case ICMP_UGE: return ICMP_SGE; case ICMP_ULE: return ICMP_SLE; } } ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) { switch (pred) { default: llvm_unreachable("Unknown icmp predicate!"); case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: return pred; case ICMP_SGT: return ICMP_UGT; case ICMP_SLT: return ICMP_ULT; case ICMP_SGE: return ICMP_UGE; case ICMP_SLE: return ICMP_ULE; } } /// Initialize a set of values that all satisfy the condition with C. /// ConstantRange ICmpInst::makeConstantRange(Predicate pred, const APInt &C) { APInt Lower(C); APInt Upper(C); uint32_t BitWidth = C.getBitWidth(); switch (pred) { default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!"); case ICmpInst::ICMP_EQ: ++Upper; break; case ICmpInst::ICMP_NE: ++Lower; break; case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); // Check for an empty-set condition. if (Lower == Upper) return ConstantRange(BitWidth, /*isFullSet=*/false); break; case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); // Check for an empty-set condition. if (Lower == Upper) return ConstantRange(BitWidth, /*isFullSet=*/false); break; case ICmpInst::ICMP_UGT: ++Lower; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max) // Check for an empty-set condition. if (Lower == Upper) return ConstantRange(BitWidth, /*isFullSet=*/false); break; case ICmpInst::ICMP_SGT: ++Lower; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max) // Check for an empty-set condition. if (Lower == Upper) return ConstantRange(BitWidth, /*isFullSet=*/false); break; case ICmpInst::ICMP_ULE: Lower = APInt::getMinValue(BitWidth); ++Upper; // Check for a full-set condition. if (Lower == Upper) return ConstantRange(BitWidth, /*isFullSet=*/true); break; case ICmpInst::ICMP_SLE: Lower = APInt::getSignedMinValue(BitWidth); ++Upper; // Check for a full-set condition. if (Lower == Upper) return ConstantRange(BitWidth, /*isFullSet=*/true); break; case ICmpInst::ICMP_UGE: Upper = APInt::getMinValue(BitWidth); // Min = Next(Max) // Check for a full-set condition. if (Lower == Upper) return ConstantRange(BitWidth, /*isFullSet=*/true); break; case ICmpInst::ICMP_SGE: Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max) // Check for a full-set condition. if (Lower == Upper) return ConstantRange(BitWidth, /*isFullSet=*/true); break; } return ConstantRange(Lower, Upper); } CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { switch (pred) { default: llvm_unreachable("Unknown cmp predicate!"); case ICMP_EQ: case ICMP_NE: return pred; case ICMP_SGT: return ICMP_SLT; case ICMP_SLT: return ICMP_SGT; case ICMP_SGE: return ICMP_SLE; case ICMP_SLE: return ICMP_SGE; case ICMP_UGT: return ICMP_ULT; case ICMP_ULT: return ICMP_UGT; case ICMP_UGE: return ICMP_ULE; case ICMP_ULE: return ICMP_UGE; case FCMP_FALSE: case FCMP_TRUE: case FCMP_OEQ: case FCMP_ONE: case FCMP_UEQ: case FCMP_UNE: case FCMP_ORD: case FCMP_UNO: return pred; case FCMP_OGT: return FCMP_OLT; case FCMP_OLT: return FCMP_OGT; case FCMP_OGE: return FCMP_OLE; case FCMP_OLE: return FCMP_OGE; case FCMP_UGT: return FCMP_ULT; case FCMP_ULT: return FCMP_UGT; case FCMP_UGE: return FCMP_ULE; case FCMP_ULE: return FCMP_UGE; } } bool CmpInst::isUnsigned(unsigned short predicate) { switch (predicate) { default: return false; case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_UGE: return true; } } bool CmpInst::isSigned(unsigned short predicate) { switch (predicate) { default: return false; case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: return true; } } bool CmpInst::isOrdered(unsigned short predicate) { switch (predicate) { default: return false; case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ORD: return true; } } bool CmpInst::isUnordered(unsigned short predicate) { switch (predicate) { default: return false; case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNO: return true; } } bool CmpInst::isTrueWhenEqual(unsigned short predicate) { switch(predicate) { default: return false; case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE: case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true; } } bool CmpInst::isFalseWhenEqual(unsigned short predicate) { switch(predicate) { case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT: case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true; default: return false; } } //===----------------------------------------------------------------------===// // SwitchInst Implementation //===----------------------------------------------------------------------===// void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) { assert(Value && Default && NumReserved); ReservedSpace = NumReserved; setNumHungOffUseOperands(2); allocHungoffUses(ReservedSpace); Op<0>() = Value; Op<1>() = Default; } /// SwitchInst ctor - Create a new switch instruction, specifying a value to /// switch on and a default destination. The number of additional cases can /// be specified here to make memory allocation more efficient. This /// constructor can also autoinsert before another instruction. SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch, nullptr, 0, InsertBefore) { init(Value, Default, 2+NumCases*2); } /// SwitchInst ctor - Create a new switch instruction, specifying a value to /// switch on and a default destination. The number of additional cases can /// be specified here to make memory allocation more efficient. This /// constructor also autoinserts at the end of the specified BasicBlock. SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch, nullptr, 0, InsertAtEnd) { init(Value, Default, 2+NumCases*2); } SwitchInst::SwitchInst(const SwitchInst &SI) : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) { init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands()); setNumHungOffUseOperands(SI.getNumOperands()); Use *OL = getOperandList(); const Use *InOL = SI.getOperandList(); for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) { OL[i] = InOL[i]; OL[i+1] = InOL[i+1]; } SubclassOptionalData = SI.SubclassOptionalData; } /// addCase - Add an entry to the switch instruction... /// void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) { unsigned NewCaseIdx = getNumCases(); unsigned OpNo = getNumOperands(); if (OpNo+2 > ReservedSpace) growOperands(); // Get more space! // Initialize some new operands. assert(OpNo+1 < ReservedSpace && "Growing didn't work!"); setNumHungOffUseOperands(OpNo+2); CaseIt Case(this, NewCaseIdx); Case.setValue(OnVal); Case.setSuccessor(Dest); } /// removeCase - This method removes the specified case and its successor /// from the switch instruction. void SwitchInst::removeCase(CaseIt i) { unsigned idx = i.getCaseIndex(); assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!"); unsigned NumOps = getNumOperands(); Use *OL = getOperandList(); // Overwrite this case with the end of the list. if (2 + (idx + 1) * 2 != NumOps) { OL[2 + idx * 2] = OL[NumOps - 2]; OL[2 + idx * 2 + 1] = OL[NumOps - 1]; } // Nuke the last value. OL[NumOps-2].set(nullptr); OL[NumOps-2+1].set(nullptr); setNumHungOffUseOperands(NumOps-2); } /// growOperands - grow operands - This grows the operand list in response /// to a push_back style of operation. This grows the number of ops by 3 times. /// void SwitchInst::growOperands() { unsigned e = getNumOperands(); unsigned NumOps = e*3; ReservedSpace = NumOps; growHungoffUses(ReservedSpace); } BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const { return getSuccessor(idx); } unsigned SwitchInst::getNumSuccessorsV() const { return getNumSuccessors(); } void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) { setSuccessor(idx, B); } //===----------------------------------------------------------------------===// // IndirectBrInst Implementation //===----------------------------------------------------------------------===// void IndirectBrInst::init(Value *Address, unsigned NumDests) { assert(Address && Address->getType()->isPointerTy() && "Address of indirectbr must be a pointer"); ReservedSpace = 1+NumDests; setNumHungOffUseOperands(1); allocHungoffUses(ReservedSpace); Op<0>() = Address; } /// growOperands - grow operands - This grows the operand list in response /// to a push_back style of operation. This grows the number of ops by 2 times. /// void IndirectBrInst::growOperands() { unsigned e = getNumOperands(); unsigned NumOps = e*2; ReservedSpace = NumOps; growHungoffUses(ReservedSpace); } IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, Instruction *InsertBefore) : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr, nullptr, 0, InsertBefore) { init(Address, NumCases); } IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, BasicBlock *InsertAtEnd) : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr, nullptr, 0, InsertAtEnd) { init(Address, NumCases); } IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI) : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr, nullptr, IBI.getNumOperands()) { allocHungoffUses(IBI.getNumOperands()); Use *OL = getOperandList(); const Use *InOL = IBI.getOperandList(); for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i) OL[i] = InOL[i]; SubclassOptionalData = IBI.SubclassOptionalData; } /// addDestination - Add a destination. /// void IndirectBrInst::addDestination(BasicBlock *DestBB) { unsigned OpNo = getNumOperands(); if (OpNo+1 > ReservedSpace) growOperands(); // Get more space! // Initialize some new operands. assert(OpNo < ReservedSpace && "Growing didn't work!"); setNumHungOffUseOperands(OpNo+1); getOperandList()[OpNo] = DestBB; } /// removeDestination - This method removes the specified successor from the /// indirectbr instruction. void IndirectBrInst::removeDestination(unsigned idx) { assert(idx < getNumOperands()-1 && "Successor index out of range!"); unsigned NumOps = getNumOperands(); Use *OL = getOperandList(); // Replace this value with the last one. OL[idx+1] = OL[NumOps-1]; // Nuke the last value. OL[NumOps-1].set(nullptr); setNumHungOffUseOperands(NumOps-1); } BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const { return getSuccessor(idx); } unsigned IndirectBrInst::getNumSuccessorsV() const { return getNumSuccessors(); } void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) { setSuccessor(idx, B); } //===----------------------------------------------------------------------===// // cloneImpl() implementations //===----------------------------------------------------------------------===// // Define these methods here so vtables don't get emitted into every translation // unit that uses these classes. GetElementPtrInst *GetElementPtrInst::cloneImpl() const { return new (getNumOperands()) GetElementPtrInst(*this); } BinaryOperator *BinaryOperator::cloneImpl() const { return Create(getOpcode(), Op<0>(), Op<1>()); } FCmpInst *FCmpInst::cloneImpl() const { return new FCmpInst(getPredicate(), Op<0>(), Op<1>()); } ICmpInst *ICmpInst::cloneImpl() const { return new ICmpInst(getPredicate(), Op<0>(), Op<1>()); } ExtractValueInst *ExtractValueInst::cloneImpl() const { return new ExtractValueInst(*this); } InsertValueInst *InsertValueInst::cloneImpl() const { return new InsertValueInst(*this); } AllocaInst *AllocaInst::cloneImpl() const { AllocaInst *Result = new AllocaInst(getAllocatedType(), (Value *)getOperand(0), getAlignment()); Result->setUsedWithInAlloca(isUsedWithInAlloca()); return Result; } LoadInst *LoadInst::cloneImpl() const { return new LoadInst(getOperand(0), Twine(), isVolatile(), getAlignment(), getOrdering(), getSynchScope()); } StoreInst *StoreInst::cloneImpl() const { return new StoreInst(getOperand(0), getOperand(1), isVolatile(), getAlignment(), getOrdering(), getSynchScope()); } AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const { AtomicCmpXchgInst *Result = new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2), getSuccessOrdering(), getFailureOrdering(), getSynchScope()); Result->setVolatile(isVolatile()); Result->setWeak(isWeak()); return Result; } AtomicRMWInst *AtomicRMWInst::cloneImpl() const { AtomicRMWInst *Result = new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1), getOrdering(), getSynchScope()); Result->setVolatile(isVolatile()); return Result; } FenceInst *FenceInst::cloneImpl() const { return new FenceInst(getContext(), getOrdering(), getSynchScope()); } TruncInst *TruncInst::cloneImpl() const { return new TruncInst(getOperand(0), getType()); } ZExtInst *ZExtInst::cloneImpl() const { return new ZExtInst(getOperand(0), getType()); } SExtInst *SExtInst::cloneImpl() const { return new SExtInst(getOperand(0), getType()); } FPTruncInst *FPTruncInst::cloneImpl() const { return new FPTruncInst(getOperand(0), getType()); } FPExtInst *FPExtInst::cloneImpl() const { return new FPExtInst(getOperand(0), getType()); } UIToFPInst *UIToFPInst::cloneImpl() const { return new UIToFPInst(getOperand(0), getType()); } SIToFPInst *SIToFPInst::cloneImpl() const { return new SIToFPInst(getOperand(0), getType()); } FPToUIInst *FPToUIInst::cloneImpl() const { return new FPToUIInst(getOperand(0), getType()); } FPToSIInst *FPToSIInst::cloneImpl() const { return new FPToSIInst(getOperand(0), getType()); } PtrToIntInst *PtrToIntInst::cloneImpl() const { return new PtrToIntInst(getOperand(0), getType()); } IntToPtrInst *IntToPtrInst::cloneImpl() const { return new IntToPtrInst(getOperand(0), getType()); } BitCastInst *BitCastInst::cloneImpl() const { return new BitCastInst(getOperand(0), getType()); } AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const { return new AddrSpaceCastInst(getOperand(0), getType()); } CallInst *CallInst::cloneImpl() const { return new(getNumOperands()) CallInst(*this); } SelectInst *SelectInst::cloneImpl() const { return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2)); } VAArgInst *VAArgInst::cloneImpl() const { return new VAArgInst(getOperand(0), getType()); } ExtractElementInst *ExtractElementInst::cloneImpl() const { return ExtractElementInst::Create(getOperand(0), getOperand(1)); } InsertElementInst *InsertElementInst::cloneImpl() const { return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2)); } ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const { return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2)); } PHINode *PHINode::cloneImpl() const { return new PHINode(*this); } LandingPadInst *LandingPadInst::cloneImpl() const { return new LandingPadInst(*this); } ReturnInst *ReturnInst::cloneImpl() const { return new(getNumOperands()) ReturnInst(*this); } BranchInst *BranchInst::cloneImpl() const { return new(getNumOperands()) BranchInst(*this); } SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); } IndirectBrInst *IndirectBrInst::cloneImpl() const { return new IndirectBrInst(*this); } InvokeInst *InvokeInst::cloneImpl() const { return new(getNumOperands()) InvokeInst(*this); } ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); } CleanupEndPadInst *CleanupEndPadInst::cloneImpl() const { return new (getNumOperands()) CleanupEndPadInst(*this); } CleanupReturnInst *CleanupReturnInst::cloneImpl() const { return new (getNumOperands()) CleanupReturnInst(*this); } CatchEndPadInst *CatchEndPadInst::cloneImpl() const { return new (getNumOperands()) CatchEndPadInst(*this); } CatchReturnInst *CatchReturnInst::cloneImpl() const { return new (getNumOperands()) CatchReturnInst(*this); } CatchPadInst *CatchPadInst::cloneImpl() const { return new (getNumOperands()) CatchPadInst(*this); } TerminatePadInst *TerminatePadInst::cloneImpl() const { return new (getNumOperands()) TerminatePadInst(*this); } CleanupPadInst *CleanupPadInst::cloneImpl() const { return new (getNumOperands()) CleanupPadInst(*this); } UnreachableInst *UnreachableInst::cloneImpl() const { LLVMContext &Context = getContext(); return new UnreachableInst(Context); }
/* * GraphBLAS Template Library (GBTL), Version 3.0 * * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and * Authors. * * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF * THE UNITED STATES GOVERNMENT. NEITHER THE UNITED STATES GOVERNMENT NOR THE * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED * RIGHTS. * * Released under a BSD-style license, please see LICENSE file or contact * permission@sei.cmu.edu for full terms. * * [DISTRIBUTION STATEMENT A] This material has been approved for public release * and unlimited distribution. Please see Copyright notice for non-US * Government use and distribution. * * This Software includes and/or makes use of the following Third-Party Software * subject to its own license: * * 1. Boost Unit Test Framework * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html) * Copyright 2001 Boost software license, Gennadiy Rozental. * * DM20-0442 */ #include <iostream> #include <graphblas/graphblas.hpp> using namespace grb; #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE matrix_methods_test_suite #include <boost/test/included/unit_test.hpp> BOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE) //**************************************************************************** BOOST_AUTO_TEST_CASE(matrix_resize_test) { IndexArrayType i = {1, 2, 3, 4}; std::vector<double> v = {1, 2, 3, 4}; // matrix = diag{ -, 1, 2, 3, 4, -}; IndexType const NSIZE = 6; Matrix<double> m1(NSIZE, NSIZE); m1.build(i, i, v); //print_matrix(std::cerr, m1, "m1(6,6)"); BOOST_CHECK_EQUAL(m1.nvals(), i.size()); BOOST_CHECK_EQUAL(m1.nrows(), NSIZE); BOOST_CHECK_EQUAL(m1.ncols(), NSIZE); // Make it bigger and set an element m1.resize(2*NSIZE, 2*NSIZE); //print_matrix(std::cerr, m1, "m1(12,12)"); BOOST_CHECK_EQUAL(m1.nvals(), i.size()); BOOST_CHECK_EQUAL(m1.nrows(), 2*NSIZE); BOOST_CHECK_EQUAL(m1.ncols(), 2*NSIZE); m1.setElement(NSIZE + 1, NSIZE + 1, 99); BOOST_CHECK_EQUAL(m1.nvals(), i.size() + 1); BOOST_CHECK_EQUAL(m1.extractElement(NSIZE + 1, NSIZE + 1), 99); // Reduce num columns check remaining elements m1.resize(2*NSIZE, 4UL); //print_matrix(std::cerr, m1, "m1(12, 4)"); BOOST_CHECK_EQUAL(m1.nvals(), 3); BOOST_CHECK_EQUAL(m1.nrows(), 2*NSIZE); BOOST_CHECK_EQUAL(m1.ncols(), 4); BOOST_CHECK_EQUAL(m1.extractElement(1, 1), 1); BOOST_CHECK_EQUAL(m1.extractElement(2, 2), 2); BOOST_CHECK_EQUAL(m1.extractElement(3, 3), 3); // Reduce num rows check remaining elements m1.resize(3UL, 4UL); //print_matrix(std::cerr, m1, "m1(3, 4)"); BOOST_CHECK_EQUAL(m1.nvals(), 2); BOOST_CHECK_EQUAL(m1.nrows(), 3); BOOST_CHECK_EQUAL(m1.ncols(), 4); BOOST_CHECK_EQUAL(m1.extractElement(1, 1), 1); BOOST_CHECK_EQUAL(m1.extractElement(2, 2), 2); // reduce both and check remaining elements m1.resize(2UL, 2UL); //print_matrix(std::cerr, m1, "m1(2,2)"); BOOST_CHECK_EQUAL(m1.nvals(), 1); BOOST_CHECK_EQUAL(m1.nrows(), 2); BOOST_CHECK_EQUAL(m1.ncols(), 2); BOOST_CHECK_EQUAL(m1.extractElement(1, 1), 1); // Make it bigger show that elements don't reappear m1.resize(2*NSIZE, 2*NSIZE); //print_matrix(std::cerr, m1, "m1(12,12)"); BOOST_CHECK_EQUAL(m1.nvals(), 1); BOOST_CHECK_EQUAL(m1.nrows(), 2*NSIZE); BOOST_CHECK_EQUAL(m1.ncols(), 2*NSIZE); } //**************************************************************************** BOOST_AUTO_TEST_CASE(matrix_removeElement_test) { IndexArrayType i = {0, 0, 0, 1, 1, 1, 2, 2}; IndexArrayType j = {1, 2, 3, 0, 2, 3, 0, 1}; std::vector<double> v = {1, 2, 3, 4, 6, 7, 8, 9}; //std::vector<std::vector<double> > mat = {{0, 1, 2, 3}, // {4, 0, 6, 7}, // {8, 9, 0, 0}}; Matrix<double, DirectedMatrixTag> m1(3, 4); m1.build(i, j, v); BOOST_CHECK_EQUAL(m1.nvals(), i.size()); // remove something that does not exist BOOST_CHECK(!m1.hasElement(1, 1)); m1.removeElement(1, 1); BOOST_CHECK_EQUAL(m1.nvals(), i.size()); BOOST_CHECK(!m1.hasElement(1, 1)); // remove something that exists BOOST_CHECK(m1.hasElement(1, 2)); m1.removeElement(1, 2); BOOST_CHECK_EQUAL(m1.nvals(), i.size() - 1); BOOST_CHECK(!m1.hasElement(1, 2)); } BOOST_AUTO_TEST_SUITE_END()
// SystemPage.cpp #include "StdAfx.h" #include "../../../Common/MyWindows.h" #include <ShlObj.h> #include "../../../Common/Defs.h" #include "../../../Common/StringConvert.h" #include "../../../Windows/DLL.h" #include "../../../Windows/ErrorMsg.h" #include "HelpUtils.h" #include "IFolder.h" #include "LangUtils.h" #include "PropertyNameRes.h" #include "SystemPage.h" #include "SystemPageRes.h" using namespace NWindows; #ifndef _UNICODE extern bool g_IsNT; #endif static const UInt32 kLangIDs[] = { IDT_SYSTEM_ASSOCIATE }; #define kSystemTopic "FM/options.htm#system" CSysString CModifiedExtInfo::GetString() const { const char *s; if (State == kExtState_7Zip) s = "7-Zip"; else if (State == kExtState_Clear) s = ""; else if (Other7Zip) s = "[7-Zip]"; else return ProgramKey; return CSysString (s); }; int CSystemPage::AddIcon(const UString &iconPath, int iconIndex) { if (iconPath.IsEmpty()) return -1; if (iconIndex == -1) iconIndex = 0; HICON hicon; #ifdef UNDER_CE ExtractIconExW(iconPath, iconIndex, NULL, &hicon, 1); if (!hicon) #else // we expand path from REG_EXPAND_SZ registry item. UString path; DWORD size = MAX_PATH + 10; DWORD needLen = ::ExpandEnvironmentStringsW(iconPath, path.GetBuf(size + 2), size); path.ReleaseBuf_CalcLen(size); if (needLen == 0 || needLen >= size) path = iconPath; int num = ExtractIconExW(path, iconIndex, NULL, &hicon, 1); if (num != 1 || !hicon) #endif return -1; _imageList.AddIcon(hicon); DestroyIcon(hicon); return _numIcons++; } void CSystemPage::RefreshListItem(unsigned group, unsigned listIndex) { const CAssoc &assoc = _items[GetRealIndex(listIndex)]; _listView.SetSubItem(listIndex, group + 1, assoc.Pair[group].GetString()); LVITEMW newItem; memset(&newItem, 0, sizeof(newItem)); newItem.iItem = listIndex; newItem.mask = LVIF_IMAGE; newItem.iImage = assoc.GetIconIndex(); _listView.SetItem(&newItem); } void CSystemPage::ChangeState(unsigned group, const CUIntVector &indices) { if (indices.IsEmpty()) return; bool thereAreClearItems = false; unsigned counters[3] = { 0, 0, 0 }; unsigned i; for (i = 0; i < indices.Size(); i++) { const CModifiedExtInfo &mi = _items[GetRealIndex(indices[i])].Pair[group]; int state = kExtState_7Zip; if (mi.State == kExtState_7Zip) state = kExtState_Clear; else if (mi.State == kExtState_Clear) { thereAreClearItems = true; if (mi.Other) state = kExtState_Other; } counters[state]++; } int state = kExtState_Clear; if (counters[kExtState_Other] != 0) state = kExtState_Other; else if (counters[kExtState_7Zip] != 0) state = kExtState_7Zip; for (i = 0; i < indices.Size(); i++) { unsigned listIndex = indices[i]; CAssoc &assoc = _items[GetRealIndex(listIndex)]; CModifiedExtInfo &mi = assoc.Pair[group]; bool change = false; switch (state) { case kExtState_Clear: change = true; break; case kExtState_Other: change = mi.Other; break; default: change = !(mi.Other && thereAreClearItems); break; } if (change) { mi.State = state; RefreshListItem(group, listIndex); } } _needSave = true; Changed(); } bool CSystemPage::OnInit() { _needSave = false; LangSetDlgItems(*this, kLangIDs, ARRAY_SIZE(kLangIDs)); _listView.Attach(GetItem(IDL_SYSTEM_ASSOCIATE)); _listView.SetUnicodeFormat(); DWORD newFlags = LVS_EX_FULLROWSELECT; _listView.SetExtendedListViewStyle(newFlags, newFlags); _numIcons = 0; _imageList.Create(16, 16, ILC_MASK | ILC_COLOR32, 0, 0); _listView.SetImageList(_imageList, LVSIL_SMALL); _listView.InsertColumn(0, LangString(IDS_PROP_FILE_TYPE), 72); UString s; #if NUM_EXT_GROUPS == 1 s = "Program"; #else #ifndef UNDER_CE const unsigned kSize = 256; BOOL res; DWORD size = kSize; #ifndef _UNICODE if (!g_IsNT) { AString s2; res = GetUserNameA(s2.GetBuf(size), &size); s2.ReleaseBuf_CalcLen(MyMin((unsigned)size, kSize)); s = GetUnicodeString(s2); } else #endif { res = GetUserNameW(s.GetBuf(size), &size); s.ReleaseBuf_CalcLen(MyMin((unsigned)size, kSize)); } if (!res) #endif s = "Current User"; #endif LV_COLUMNW ci; ci.mask = LVCF_TEXT | LVCF_FMT | LVCF_WIDTH | LVCF_SUBITEM; ci.cx = 128; ci.fmt = LVCFMT_CENTER; ci.pszText = s.Ptr_non_const(); ci.iSubItem = 1; _listView.InsertColumn(1, &ci); #if NUM_EXT_GROUPS > 1 { LangString(IDS_SYSTEM_ALL_USERS, s); ci.pszText = s.Ptr_non_const(); ci.iSubItem = 2; _listView.InsertColumn(2, &ci); } #endif _extDB.Read(); _items.Clear(); FOR_VECTOR (i, _extDB.Exts) { const CExtPlugins &extInfo = _extDB.Exts[i]; LVITEMW item; item.iItem = i; item.mask = LVIF_TEXT | LVIF_PARAM | LVIF_IMAGE; item.lParam = i; item.iSubItem = 0; // ListView always uses internal iImage that is 0 by default? // so we always use LVIF_IMAGE. item.iImage = -1; item.pszText = extInfo.Ext.Ptr_non_const(); CAssoc assoc; const CPluginToIcon &plug = extInfo.Plugins[0]; assoc.SevenZipImageIndex = AddIcon(plug.IconPath, plug.IconIndex); CSysString texts[NUM_EXT_GROUPS]; unsigned g; for (g = 0; g < NUM_EXT_GROUPS; g++) { CModifiedExtInfo &mi = assoc.Pair[g]; mi.ReadFromRegistry(GetHKey(g), GetSystemString(extInfo.Ext)); mi.SetState(plug.IconPath); mi.ImageIndex = AddIcon(mi.IconPath, mi.IconIndex); texts[g] = mi.GetString(); } item.iImage = assoc.GetIconIndex(); int itemIndex = _listView.InsertItem(&item); for (g = 0; g < NUM_EXT_GROUPS; g++) _listView.SetSubItem(itemIndex, 1 + g, texts[g]); _items.Add(assoc); } if (_listView.GetItemCount() > 0) _listView.SetItemState(0, LVIS_FOCUSED, LVIS_FOCUSED); return CPropertyPage::OnInit(); } static UString GetProgramCommand() { UString s ('\"'); s += fs2us(NDLL::GetModuleDirPrefix()); s += "7zFM.exe\" \"%1\""; return s; } LONG CSystemPage::OnApply() { if (!_needSave) return PSNRET_NOERROR; const UString command = GetProgramCommand(); LONG res = 0; FOR_VECTOR (listIndex, _extDB.Exts) { unsigned realIndex = GetRealIndex(listIndex); const CExtPlugins &extInfo = _extDB.Exts[realIndex]; CAssoc &assoc = _items[realIndex]; for (unsigned g = 0; g < NUM_EXT_GROUPS; g++) { CModifiedExtInfo &mi = assoc.Pair[g]; HKEY key = GetHKey(g); if (mi.OldState != mi.State) { LONG res2 = 0; if (mi.State == kExtState_7Zip) { UString title = extInfo.Ext; title += " Archive"; const CPluginToIcon &plug = extInfo.Plugins[0]; res2 = NRegistryAssoc::AddShellExtensionInfo(key, GetSystemString(extInfo.Ext), title, command, plug.IconPath, plug.IconIndex); } else if (mi.State == kExtState_Clear) res2 = NRegistryAssoc::DeleteShellExtensionInfo(key, GetSystemString(extInfo.Ext)); if (res == 0) res = res2; if (res2 == 0) mi.OldState = mi.State; mi.State = mi.OldState; RefreshListItem(g, listIndex); } } } #ifndef UNDER_CE SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); #endif WasChanged = true; _needSave = false; if (res != 0) MessageBoxW(*this, NError::MyFormatMessage(res), L"7-Zip", MB_ICONERROR); return PSNRET_NOERROR; } void CSystemPage::OnNotifyHelp() { ShowHelpWindow(kSystemTopic); } bool CSystemPage::OnButtonClicked(int buttonID, HWND buttonHWND) { switch (buttonID) { /* case IDC_SYSTEM_SELECT_ALL: _listView.SelectAll(); return true; */ case IDB_SYSTEM_CURRENT: case IDB_SYSTEM_ALL: ChangeState(buttonID == IDB_SYSTEM_CURRENT ? 0 : 1); return true; } return CPropertyPage::OnButtonClicked(buttonID, buttonHWND); } bool CSystemPage::OnNotify(UINT controlID, LPNMHDR lParam) { if (lParam->hwndFrom == HWND(_listView)) { switch (lParam->code) { case NM_RETURN: { ChangeState(0); return true; } case NM_CLICK: { #ifdef UNDER_CE NMLISTVIEW *item = (NMLISTVIEW *)lParam; #else NMITEMACTIVATE *item = (NMITEMACTIVATE *)lParam; if (item->uKeyFlags == 0) #endif { if (item->iItem >= 0) { // unsigned realIndex = GetRealIndex(item->iItem); if (item->iSubItem >= 1 && item->iSubItem <= 2) { CUIntVector indices; indices.Add(item->iItem); ChangeState(item->iSubItem < 2 ? 0 : 1, indices); } } } break; } case LVN_KEYDOWN: { if (OnListKeyDown(LPNMLVKEYDOWN(lParam))) return true; break; } /* case NM_RCLICK: case NM_DBLCLK: case LVN_BEGINRDRAG: // PostMessage(kRefreshpluginsListMessage, 0); PostMessage(kUpdateDatabase, 0); break; */ } } return CPropertyPage::OnNotify(controlID, lParam); } void CSystemPage::ChangeState(unsigned group) { CUIntVector indices; int itemIndex = -1; while ((itemIndex = _listView.GetNextSelectedItem(itemIndex)) != -1) indices.Add(itemIndex); if (indices.IsEmpty()) FOR_VECTOR (i, _items) indices.Add(i); ChangeState(group, indices); } bool CSystemPage::OnListKeyDown(LPNMLVKEYDOWN keyDownInfo) { bool ctrl = IsKeyDown(VK_CONTROL); bool alt = IsKeyDown(VK_MENU); if (alt) return false; if ((ctrl && keyDownInfo->wVKey == 'A') || (!ctrl && keyDownInfo->wVKey == VK_MULTIPLY)) { _listView.SelectAll(); return true; } switch (keyDownInfo->wVKey) { case VK_SPACE: case VK_ADD: case VK_SUBTRACT: case VK_SEPARATOR: case VK_DIVIDE: #ifndef UNDER_CE case VK_OEM_PLUS: case VK_OEM_MINUS: #endif if (!ctrl) { ChangeState(keyDownInfo->wVKey == VK_SPACE ? 0 : 1); return true; } break; } return false; }
/*============================================================================ CMake - Cross Platform Makefile Generator Copyright 2000-2009 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #include "vtkArchive.h" #include "vtksys/Glob.hxx" #include "vtksys/SystemTools.hxx" // LibArchive includes #include <archive.h> #include <archive_entry.h> // STD includes #include <cstring> #include <iostream> namespace { // -------------------------------------------------------------------------- class vtkArchiveTools { public: static void Message(const char* title, const char* message) { std::cerr << title << " " << message << std::endl << std::flush; } static void Message(const char* m) { std::cerr << m << std::endl << std::flush; } static void Stdout(const char* s) { std::cout << s; std::cout.flush(); } static void Error(const char* m1, const char* m2) { std::string message = "vtkArchive Error: "; if(m1) { message += m1; } if(m2) { message += " "; message += m2; } vtkArchiveTools::Message(message.c_str(), "Error"); } }; // -------------------------------------------------------------------------- #define BSDTAR_FILESIZE_PRINTF "%lu" #define BSDTAR_FILESIZE_TYPE unsigned long void list_item_verbose(FILE *out, struct archive_entry *entry) { char tmp[100]; size_t w; const char *p; const char *fmt; time_t tim; static time_t now; size_t u_width = 6; size_t gs_width = 13; /* * We avoid collecting the entire list in memory at once by * listing things as we see them. However, that also means we can't * just pre-compute the field widths. Instead, we start with guesses * and just widen them as necessary. These numbers are completely * arbitrary. */ if (!now) { time(&now); } fprintf(out, "%s %d ", archive_entry_strmode(entry), archive_entry_nlink(entry)); /* Use uname if it's present, else uid. */ p = archive_entry_uname(entry); if ((p == NULL) || (*p == '\0')) { sprintf(tmp, "%lu ", (unsigned long)archive_entry_uid(entry)); p = tmp; } w = strlen(p); if (w > u_width) { u_width = w; } fprintf(out, "%-*s ", (int)u_width, p); /* Use gname if it's present, else gid. */ p = archive_entry_gname(entry); if (p != NULL && p[0] != '\0') { fprintf(out, "%s", p); w = strlen(p); } else { sprintf(tmp, "%lu", (unsigned long)archive_entry_gid(entry)); w = strlen(tmp); fprintf(out, "%s", tmp); } /* * Print device number or file size, right-aligned so as to make * total width of group and devnum/filesize fields be gs_width. * If gs_width is too small, grow it. */ if (archive_entry_filetype(entry) == AE_IFCHR || archive_entry_filetype(entry) == AE_IFBLK) { sprintf(tmp, "%lu,%lu", (unsigned long)archive_entry_rdevmajor(entry), (unsigned long)archive_entry_rdevminor(entry)); } else { /* * Note the use of platform-dependent macros to format * the filesize here. We need the format string and the * corresponding type for the cast. */ sprintf(tmp, BSDTAR_FILESIZE_PRINTF, (BSDTAR_FILESIZE_TYPE)archive_entry_size(entry)); } if (w + strlen(tmp) >= gs_width) { gs_width = w+strlen(tmp)+1; } fprintf(out, "%*s", (int)(gs_width - w), tmp); /* Format the time using 'ls -l' conventions. */ tim = archive_entry_mtime(entry); #define HALF_YEAR (time_t)365 * 86400 / 2 #if defined(_WIN32) && !defined(__CYGWIN__) /* Windows' strftime function does not support %e format. */ #define DAY_FMT "%d" #else #define DAY_FMT "%e" /* Day number without leading zeros */ #endif if (tim < now - HALF_YEAR || tim > now + HALF_YEAR) { fmt = DAY_FMT " %b %Y"; } else { fmt = DAY_FMT " %b %H:%M"; } strftime(tmp, sizeof(tmp), fmt, localtime(&tim)); fprintf(out, " %s ", tmp); fprintf(out, "%s", archive_entry_pathname(entry)); /* Extra information for links. */ if (archive_entry_hardlink(entry)) /* Hard link */ { fprintf(out, " link to %s", archive_entry_hardlink(entry)); } else if (archive_entry_symlink(entry)) /* Symbolic link */ { fprintf(out, " -> %s", archive_entry_symlink(entry)); } } #ifdef __BORLANDC__ # pragma warn -8066 /* unreachable code */ #endif // -------------------------------------------------------------------------- long copy_data(struct archive *ar, struct archive *aw) { long r; const void *buff; size_t size; #if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000 __LA_INT64_T offset; #else off_t offset; #endif for (;;) { r = archive_read_data_block(ar, &buff, &size, &offset); if (r == ARCHIVE_EOF) { return (ARCHIVE_OK); } if (r != ARCHIVE_OK) { return (r); } r = archive_write_data_block(aw, buff, size, offset); if (r != ARCHIVE_OK) { vtkArchiveTools::Message("archive_write_data_block()", archive_error_string(aw)); return (r); } } return r; } } // end of anonymous namespace //----------------------------------------------------------------------------- bool list_archive(const char* archiveFileName, std::vector<std::string>& files) { struct archive* a = archive_read_new(); archive_read_support_filter_all(a); archive_read_support_format_all(a); if (archive_read_open_filename(a, archiveFileName, 10240) != ARCHIVE_OK) { vtkArchiveTools::Error("Problem with archive_read_open_file(): ", archive_error_string(a)); return false; } files.clear(); int r; struct archive_entry* entry; while ((r = archive_read_next_header(a, &entry)) != ARCHIVE_EOF) { if (r != ARCHIVE_OK) { vtkArchiveTools::Error("Problem with archive_read_next_header(): ", archive_error_string(a)); return false; } files.push_back(archive_entry_pathname(entry)); } archive_read_close(a); archive_read_free(a); return true; } //----------------------------------------------------------------------------- bool extract_tar(const char* tarFileName, bool verbose, bool extract, std::vector<std::string> * extracted_files) { struct archive* a = archive_read_new(); struct archive *ext = archive_write_disk_new(); archive_read_support_compression_all(a); archive_read_support_format_all(a); struct archive_entry *entry; int r = archive_read_open_file(a, tarFileName, 10240); if(r) { vtkArchiveTools::Error("Problem with archive_read_open_file(): ", archive_error_string(a)); return false; } for (;;) { r = archive_read_next_header(a, &entry); if (r == ARCHIVE_EOF) { break; } if (r != ARCHIVE_OK) { vtkArchiveTools::Error("Problem with archive_read_next_header(): ", archive_error_string(a)); } if ( extract && extracted_files) { extracted_files->push_back(archive_entry_pathname(entry)); } if (verbose && extract) { vtkArchiveTools::Stdout("x "); vtkArchiveTools::Stdout(archive_entry_pathname(entry)); } if(verbose && !extract) { list_item_verbose(stdout, entry); } else if(!extract) { vtkArchiveTools::Stdout(archive_entry_pathname(entry)); } if(extract) { r = archive_write_disk_set_options(ext, ARCHIVE_EXTRACT_TIME); if (r != ARCHIVE_OK) { vtkArchiveTools::Error( "Problem with archive_write_disk_set_options(): ", archive_error_string(ext)); } r = archive_write_header(ext, entry); if (r != ARCHIVE_OK) { vtkArchiveTools::Error("Problem with archive_write_header(): ", archive_error_string(ext)); vtkArchiveTools::Error("Current file:", archive_entry_pathname(entry)); } else { r = copy_data(a, ext); if (r != ARCHIVE_OK) { vtkArchiveTools::Error("Problem with copy_data(): source:", archive_error_string(a)); vtkArchiveTools::Error("destination: ", archive_error_string(ext)); } r = archive_write_finish_entry(ext); if (r != ARCHIVE_OK) { vtkArchiveTools::Error("Problem with archive_write_finish_entry(): ", archive_error_string(ext)); } } } if (verbose || !extract) { vtkArchiveTools::Stdout("\n"); } } archive_read_close(a); archive_read_finish(a); return true; } //----------------------------------------------------------------------------- // creates a zip file with the full contents of the directory (recurses) // zip entries will include relative path of including tail of directoryToZip bool zip(const char* zipFileName, const char* directoryToZip) { // // to make a zip file: // - check that libarchive supports zip writing // - check arguments // - get a list of files using vtksys Glob // - create the archive // -- go file-by-file and add chunks of data to the archive // - close up and return success // // only support the libarchive version 3.0 + #if !defined(ARCHIVE_VERSION_NUMBER) || ARCHIVE_VERSION_NUMBER < 3000000 return false; #endif if ( !zipFileName || !directoryToZip ) { vtkArchiveTools::Error("Zip:", "Invalid zipfile or directory"); return false; } std::vector<vtksys::String> directoryParts; directoryParts = vtksys::SystemTools::SplitString(directoryToZip, '/', true); std::string directoryName = directoryParts.back(); vtksys::Glob glob; glob.RecurseOn(); glob.RecurseThroughSymlinksOff(); std::string globPattern(directoryToZip); if ( !glob.FindFiles( globPattern + "/*" ) ) { vtkArchiveTools::Error("Zip:", "Could not find files in directory"); return false; } std::vector<std::string> files = glob.GetFiles(); // now zip it up using LibArchive struct archive *zipArchive; struct archive_entry *entry, *dirEntry; char buff[BUFSIZ]; size_t len; // have to read the contents of the files to add them to the archive FILE *fd; zipArchive = archive_write_new(); // create a zip archive #ifdef HAVE_ZLIB_H std::string compression_type = "deflate"; #else std::string compression_type = "store"; #endif archive_write_set_format_zip(zipArchive); archive_write_set_format_option(zipArchive, "zip", "compression", compression_type.c_str()); archive_write_open_filename(zipArchive, zipFileName); // add the data directory dirEntry = archive_entry_new(); archive_entry_set_mtime(dirEntry, 11, 110); archive_entry_copy_pathname(dirEntry, directoryName.c_str()); archive_entry_set_mode(dirEntry, S_IFDIR | 0755); archive_entry_set_size(dirEntry, 512); archive_write_header(zipArchive, dirEntry); archive_entry_free(dirEntry); // add the files std::vector<std::string>::const_iterator sit; sit = files.begin(); while (sit != files.end()) { vtkArchiveTools::Message("Zip: adding:", (*sit).c_str()); const char *fileName = (*sit).c_str(); ++sit; // // add an entry for this file // entry = archive_entry_new(); // use a relative path for the entry file name, including the top // directory so it unzips into a directory of it's own std::string relFileName = vtksys::SystemTools::RelativePath( vtksys::SystemTools::GetParentDirectory(directoryToZip).c_str(), fileName); vtkArchiveTools::Message("Zip: adding rel:", relFileName.c_str()); archive_entry_set_pathname(entry, relFileName.c_str()); // size is required, for now use the vtksys call though it uses struct stat // and may not be portable unsigned long fileLength = vtksys::SystemTools::FileLength(fileName); archive_entry_set_size(entry, fileLength); archive_entry_set_filetype(entry, AE_IFREG); archive_entry_set_perm(entry, 0644); archive_write_header(zipArchive, entry); // // add the data for this entry // fd = fopen(fileName, "rb"); if (!fd) { vtkArchiveTools::Error("Zip: cannot open:", (*sit).c_str()); } else { len = fread(buff, sizeof(char), sizeof(buff), fd); while ( len > 0 ) { archive_write_data(zipArchive, buff, len); len = fread(buff, sizeof(char), sizeof(buff), fd); } fclose(fd); } archive_entry_free(entry); } archive_write_close(zipArchive); int retval = archive_write_free(zipArchive); if (retval != ARCHIVE_OK) { vtkArchiveTools::Error("Zip:", "error on close!"); return false; } return true; } //----------------------------------------------------------------------------- // unzips zip file into destinationDirectory bool unzip(const char* zipFileName, const char* destinationDirectory) { // // Unziping the archive // - check that files and directories exist // - cd to destination // - create an extracter from the file // - create a writer to disk // - read all headers and data into disk // - close up the archives // - cd back to original directory // if ( !zipFileName || !destinationDirectory ) { vtkArchiveTools::Error("Unzip:", "Invalid zipfile or directory"); return false; } if ( !vtksys::SystemTools::FileExists(zipFileName) ) { vtkArchiveTools::Error("Unzip:", "Zip file does not exist"); return false; } if ( !vtksys::SystemTools::FileIsDirectory(destinationDirectory) ) { vtkArchiveTools::Error("Unzip:", "Destination is not a directory"); return false; } std::string cwd = vtksys::SystemTools::GetCurrentWorkingDirectory(true); if ( vtksys::SystemTools::ChangeDirectory(destinationDirectory) ) { vtkArchiveTools::Error("Unzip:", "could not change to destination directory"); return false; } struct archive *zipArchive; struct archive *diskDestination; struct archive_entry *entry; int result; zipArchive = archive_read_new(); // we will typically have zip files, but support all archive types (why not?) archive_read_support_filter_all(zipArchive); archive_read_support_format_all(zipArchive); // Note: the 10240 is just a suggested block size result = archive_read_open_filename(zipArchive, zipFileName, 10240); if (result != ARCHIVE_OK) { vtkArchiveTools::Error("Unzip:", "Cannot open archive file"); return false; } diskDestination = archive_write_disk_new(); archive_write_disk_set_standard_lookup(diskDestination); for (;;) { // for each file entry result = archive_read_next_header(zipArchive, &entry); if (result == ARCHIVE_EOF) { break; } if (result != ARCHIVE_OK) { vtkArchiveTools::Error("Unzip error:", archive_error_string(zipArchive)); if (result < ARCHIVE_WARN) { break; } } result = archive_write_header(diskDestination, entry); if (result != ARCHIVE_OK) { vtkArchiveTools::Error("Unzip error:", archive_error_string(diskDestination)); if (result < ARCHIVE_WARN) { break; } } else { // copy data const void *buff; size_t size; #if defined(ARCHIVE_VERSION_NUMBER) && ARCHIVE_VERSION_NUMBER >= 3000000 __LA_INT64_T offset; #else off_t offset; #endif for (;;) { result = archive_read_data_block(zipArchive, &buff, &size, &offset); if (result == ARCHIVE_EOF) { break; } if (result != ARCHIVE_OK) { vtkArchiveTools::Error("Unzip error:", archive_error_string(zipArchive)); break; } result = archive_write_data_block(diskDestination, buff, size, offset); if (result != ARCHIVE_OK) { vtkArchiveTools::Error("Unzip error:", archive_error_string(diskDestination)); break; } } } } result = archive_read_close(zipArchive); if (result != ARCHIVE_OK) { vtkArchiveTools::Error("Unzip closing zipfile:", archive_error_string(zipArchive)); return false; } result = archive_read_free(zipArchive); if (result != ARCHIVE_OK) { vtkArchiveTools::Error("Unzip freeing zipfile:", archive_error_string(zipArchive)); return false; } result = archive_write_close(diskDestination); if (result != ARCHIVE_OK) { vtkArchiveTools::Error("Unzip closing disk:", archive_error_string(diskDestination)); return false; } result = archive_write_free(diskDestination); if (result != ARCHIVE_OK) { vtkArchiveTools::Error("Unzip freeing disk:", archive_error_string(diskDestination)); return false; } if ( vtksys::SystemTools::ChangeDirectory(cwd.c_str()) ) { vtkArchiveTools::Error("Unzip:", "could not change back to working directory"); return false; } return (result == ARCHIVE_OK); }
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/webauth/authenticator_impl.h" #include <string> #include <utility> #include "base/timer/timer.h" #include "content/browser/webauth/authenticator_common.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "url/origin.h" namespace content { AuthenticatorImpl::AuthenticatorImpl(RenderFrameHost* render_frame_host) : AuthenticatorImpl( render_frame_host, std::make_unique<AuthenticatorCommon>(render_frame_host)) {} AuthenticatorImpl::AuthenticatorImpl( RenderFrameHost* render_frame_host, std::unique_ptr<AuthenticatorCommon> authenticator_common) : WebContentsObserver(WebContents::FromRenderFrameHost(render_frame_host)), render_frame_host_(render_frame_host), authenticator_common_(std::move(authenticator_common)) { DCHECK(render_frame_host_); DCHECK(authenticator_common_); } AuthenticatorImpl::~AuthenticatorImpl() { // This call exists to assert that |render_frame_host_| outlives this object. // If this is violated, ASAN should notice. render_frame_host_->GetRoutingID(); } void AuthenticatorImpl::Bind( mojo::PendingReceiver<blink::mojom::Authenticator> receiver) { // If |render_frame_host_| is being unloaded then binding requests are // rejected. if (!render_frame_host_->IsCurrent()) { return; } DCHECK(!receiver_.is_bound()); receiver_.Bind(std::move(receiver)); } // mojom::Authenticator void AuthenticatorImpl::MakeCredential( blink::mojom::PublicKeyCredentialCreationOptionsPtr options, MakeCredentialCallback callback) { authenticator_common_->MakeCredential( render_frame_host_->GetLastCommittedOrigin(), std::move(options), std::move(callback)); } // mojom:Authenticator void AuthenticatorImpl::GetAssertion( blink::mojom::PublicKeyCredentialRequestOptionsPtr options, GetAssertionCallback callback) { authenticator_common_->GetAssertion( render_frame_host_->GetLastCommittedOrigin(), std::move(options), std::move(callback)); } void AuthenticatorImpl::IsUserVerifyingPlatformAuthenticatorAvailable( IsUserVerifyingPlatformAuthenticatorAvailableCallback callback) { authenticator_common_->IsUserVerifyingPlatformAuthenticatorAvailable( std::move(callback)); } void AuthenticatorImpl::Cancel() { authenticator_common_->Cancel(); } void AuthenticatorImpl::DidFinishNavigation( NavigationHandle* navigation_handle) { // If the RenderFrameHost itself is navigated then this function will cause // request state to be cleaned up. It's also possible for a navigation in the // same frame to use a fresh RenderFrameHost. In this case, // |render_frame_host_->IsCurrent()| will start returning false, causing all // focus checks to fail if any Mojo requests are made in that state. if (!navigation_handle->HasCommitted() || navigation_handle->IsSameDocument() || navigation_handle->GetRenderFrameHost() != render_frame_host_) { return; } receiver_.reset(); authenticator_common_->Cleanup(); } } // namespace content
/* * Copyright (c) 2015 Andrew Kelley * * This file is part of zig, which is MIT licensed. * See http://opensource.org/licenses/MIT */ #include "analyze.hpp" #include "codegen.hpp" #include "error.hpp" #include "astgen.hpp" #include "ir.hpp" #include "ir_print.hpp" #include "os.hpp" #include "parser.hpp" #include "softfloat.hpp" #include "zig_llvm.h" static const size_t default_backward_branch_quota = 1000; static Error ATTRIBUTE_MUST_USE resolve_struct_type(CodeGen *g, ZigType *struct_type); static Error ATTRIBUTE_MUST_USE resolve_struct_zero_bits(CodeGen *g, ZigType *struct_type); static Error ATTRIBUTE_MUST_USE resolve_struct_alignment(CodeGen *g, ZigType *struct_type); static Error ATTRIBUTE_MUST_USE resolve_enum_zero_bits(CodeGen *g, ZigType *enum_type); static Error ATTRIBUTE_MUST_USE resolve_union_zero_bits(CodeGen *g, ZigType *union_type); static Error ATTRIBUTE_MUST_USE resolve_union_alignment(CodeGen *g, ZigType *union_type); static void analyze_fn_body(CodeGen *g, ZigFn *fn_table_entry); static void resolve_llvm_types(CodeGen *g, ZigType *type, ResolveStatus wanted_resolve_status); static void preview_use_decl(CodeGen *g, TldUsingNamespace *using_namespace, ScopeDecls *dest_decls_scope); static void resolve_use_decl(CodeGen *g, TldUsingNamespace *tld_using_namespace, ScopeDecls *dest_decls_scope); static void analyze_fn_async(CodeGen *g, ZigFn *fn, bool resolve_frame); // nullptr means not analyzed yet; this one means currently being analyzed static const AstNode *inferred_async_checking = reinterpret_cast<AstNode *>(0x1); // this one means analyzed and it's not async static const AstNode *inferred_async_none = reinterpret_cast<AstNode *>(0x2); static bool is_top_level_struct(ZigType *import) { return import->id == ZigTypeIdStruct && import->data.structure.root_struct != nullptr; } static ErrorMsg *add_error_note_token(CodeGen *g, ErrorMsg *parent_msg, ZigType *owner, TokenIndex token, Buf *msg) { assert(is_top_level_struct(owner)); RootStruct *root_struct = owner->data.structure.root_struct; uint32_t byte_offset = root_struct->token_locs[token].offset; ErrorMsg *err = err_msg_create_with_offset(root_struct->path, byte_offset, buf_ptr(root_struct->source_code), msg); err_msg_add_note(parent_msg, err); return err; } ErrorMsg *add_token_error_offset(CodeGen *g, ZigType *owner, TokenIndex token, Buf *msg, uint32_t bad_index) { assert(is_top_level_struct(owner)); RootStruct *root_struct = owner->data.structure.root_struct; uint32_t byte_offset = root_struct->token_locs[token].offset + bad_index; ErrorMsg *err = err_msg_create_with_offset(root_struct->path, byte_offset, buf_ptr(root_struct->source_code), msg); g->errors.append(err); g->trace_err = err; return err; } ErrorMsg *add_token_error(CodeGen *g, ZigType *owner, TokenIndex token, Buf *msg) { return add_token_error_offset(g, owner, token, msg, 0); } ErrorMsg *add_node_error(CodeGen *g, AstNode *node, Buf *msg) { return add_token_error(g, node->owner, node->main_token, msg); } ErrorMsg *add_error_note(CodeGen *g, ErrorMsg *parent_msg, const AstNode *node, Buf *msg) { return add_error_note_token(g, parent_msg, node->owner, node->main_token, msg); } ZigType *new_type_table_entry(ZigTypeId id) { ZigType *entry = heap::c_allocator.create<ZigType>(); entry->id = id; return entry; } static ScopeDecls **get_container_scope_ptr(ZigType *type_entry) { switch (type_entry->id) { case ZigTypeIdStruct: return &type_entry->data.structure.decls_scope; case ZigTypeIdEnum: return &type_entry->data.enumeration.decls_scope; case ZigTypeIdUnion: return &type_entry->data.unionation.decls_scope; case ZigTypeIdOpaque: return &type_entry->data.opaque.decls_scope; default: zig_unreachable(); } } static ScopeExpr *find_expr_scope(Scope *scope) { for (;;) { switch (scope->id) { case ScopeIdExpr: return reinterpret_cast<ScopeExpr *>(scope); case ScopeIdDefer: case ScopeIdDeferExpr: case ScopeIdDecls: case ScopeIdFnDef: case ScopeIdCompTime: case ScopeIdNoSuspend: case ScopeIdVarDecl: case ScopeIdCImport: case ScopeIdSuspend: case ScopeIdTypeOf: case ScopeIdBlock: return nullptr; case ScopeIdLoop: case ScopeIdRuntime: scope = scope->parent; continue; } } } static void update_progress_display(CodeGen *g) { stage2_progress_update_node(g->sub_progress_node, g->resolve_queue_index + g->fn_defs_index, g->resolve_queue.length + g->fn_defs.length); } ScopeDecls *get_container_scope(ZigType *type_entry) { return *get_container_scope_ptr(type_entry); } void init_scope(CodeGen *g, Scope *dest, ScopeId id, AstNode *source_node, Scope *parent) { dest->codegen = g; dest->id = id; dest->source_node = source_node; dest->parent = parent; } ScopeDecls *create_decls_scope(CodeGen *g, AstNode *node, Scope *parent, ZigType *container_type, ZigType *import, Buf *bare_name) { ScopeDecls *scope = heap::c_allocator.create<ScopeDecls>(); init_scope(g, &scope->base, ScopeIdDecls, node, parent); scope->decl_table.init(4); scope->container_type = container_type; scope->import = import; scope->bare_name = bare_name; return scope; } ScopeBlock *create_block_scope(CodeGen *g, AstNode *node, Scope *parent) { assert(node->type == NodeTypeBlock); ScopeBlock *scope = heap::c_allocator.create<ScopeBlock>(); init_scope(g, &scope->base, ScopeIdBlock, node, parent); scope->name = node->data.block.name; return scope; } ScopeDefer *create_defer_scope(CodeGen *g, AstNode *node, Scope *parent) { assert(node->type == NodeTypeDefer); ScopeDefer *scope = heap::c_allocator.create<ScopeDefer>(); init_scope(g, &scope->base, ScopeIdDefer, node, parent); return scope; } ScopeDeferExpr *create_defer_expr_scope(CodeGen *g, AstNode *node, Scope *parent) { assert(node->type == NodeTypeDefer); ScopeDeferExpr *scope = heap::c_allocator.create<ScopeDeferExpr>(); init_scope(g, &scope->base, ScopeIdDeferExpr, node, parent); return scope; } Scope *create_var_scope(CodeGen *g, AstNode *node, Scope *parent, ZigVar *var) { ScopeVarDecl *scope = heap::c_allocator.create<ScopeVarDecl>(); init_scope(g, &scope->base, ScopeIdVarDecl, node, parent); scope->var = var; return &scope->base; } ScopeCImport *create_cimport_scope(CodeGen *g, AstNode *node, Scope *parent) { assert(node->type == NodeTypeFnCallExpr); ScopeCImport *scope = heap::c_allocator.create<ScopeCImport>(); init_scope(g, &scope->base, ScopeIdCImport, node, parent); buf_resize(&scope->buf, 0); return scope; } ScopeLoop *create_loop_scope(CodeGen *g, AstNode *node, Scope *parent) { ScopeLoop *scope = heap::c_allocator.create<ScopeLoop>(); init_scope(g, &scope->base, ScopeIdLoop, node, parent); if (node->type == NodeTypeWhileExpr) { scope->name = node->data.while_expr.name; } else if (node->type == NodeTypeForExpr) { scope->name = node->data.for_expr.name; } else { zig_unreachable(); } return scope; } Scope *create_runtime_scope(CodeGen *g, AstNode *node, Scope *parent, Stage1ZirInst *is_comptime) { ScopeRuntime *scope = heap::c_allocator.create<ScopeRuntime>(); scope->is_comptime = is_comptime; init_scope(g, &scope->base, ScopeIdRuntime, node, parent); return &scope->base; } ScopeSuspend *create_suspend_scope(CodeGen *g, AstNode *node, Scope *parent) { assert(node->type == NodeTypeSuspend); ScopeSuspend *scope = heap::c_allocator.create<ScopeSuspend>(); init_scope(g, &scope->base, ScopeIdSuspend, node, parent); return scope; } ScopeFnDef *create_fndef_scope(CodeGen *g, AstNode *node, Scope *parent, ZigFn *fn_entry) { ScopeFnDef *scope = heap::c_allocator.create<ScopeFnDef>(); init_scope(g, &scope->base, ScopeIdFnDef, node, parent); scope->fn_entry = fn_entry; return scope; } Scope *create_comptime_scope(CodeGen *g, AstNode *node, Scope *parent) { ScopeCompTime *scope = heap::c_allocator.create<ScopeCompTime>(); init_scope(g, &scope->base, ScopeIdCompTime, node, parent); return &scope->base; } Scope *create_nosuspend_scope(CodeGen *g, AstNode *node, Scope *parent) { ScopeNoSuspend *scope = heap::c_allocator.create<ScopeNoSuspend>(); init_scope(g, &scope->base, ScopeIdNoSuspend, node, parent); return &scope->base; } Scope *create_typeof_scope(CodeGen *g, AstNode *node, Scope *parent) { ScopeTypeOf *scope = heap::c_allocator.create<ScopeTypeOf>(); init_scope(g, &scope->base, ScopeIdTypeOf, node, parent); return &scope->base; } ScopeExpr *create_expr_scope(CodeGen *g, AstNode *node, Scope *parent) { ScopeExpr *scope = heap::c_allocator.create<ScopeExpr>(); init_scope(g, &scope->base, ScopeIdExpr, node, parent); ScopeExpr *parent_expr = find_expr_scope(parent); if (parent_expr != nullptr) { size_t new_len = parent_expr->children_len + 1; parent_expr->children_ptr = heap::c_allocator.reallocate_nonzero<ScopeExpr *>( parent_expr->children_ptr, parent_expr->children_len, new_len); parent_expr->children_ptr[parent_expr->children_len] = scope; parent_expr->children_len = new_len; } return scope; } ZigType *get_scope_import(Scope *scope) { while (scope) { if (scope->id == ScopeIdDecls) { ScopeDecls *decls_scope = (ScopeDecls *)scope; assert(is_top_level_struct(decls_scope->import)); return decls_scope->import; } scope = scope->parent; } zig_unreachable(); } ScopeTypeOf *get_scope_typeof(Scope *scope) { while (scope) { switch (scope->id) { case ScopeIdTypeOf: return reinterpret_cast<ScopeTypeOf *>(scope); case ScopeIdFnDef: case ScopeIdDecls: return nullptr; default: scope = scope->parent; continue; } } zig_unreachable(); } static ZigType *new_container_type_entry(CodeGen *g, ZigTypeId id, AstNode *source_node, Scope *parent_scope, Buf *bare_name) { ZigType *entry = new_type_table_entry(id); *get_container_scope_ptr(entry) = create_decls_scope(g, source_node, parent_scope, entry, get_scope_import(parent_scope), bare_name); return entry; } static uint8_t bits_needed_for_unsigned(uint64_t x) { if (x == 0) { return 0; } uint8_t base = log2_u64(x); uint64_t upper = (((uint64_t)1) << base) - 1; return (upper >= x) ? base : (base + 1); } AstNode *type_decl_node(ZigType *type_entry) { switch (type_entry->id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdStruct: return type_entry->data.structure.decl_node; case ZigTypeIdEnum: return type_entry->data.enumeration.decl_node; case ZigTypeIdUnion: return type_entry->data.unionation.decl_node; case ZigTypeIdFnFrame: return type_entry->data.frame.fn->proto_node; case ZigTypeIdOpaque: case ZigTypeIdMetaType: case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdUnreachable: case ZigTypeIdInt: case ZigTypeIdFloat: case ZigTypeIdPointer: case ZigTypeIdArray: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdOptional: case ZigTypeIdErrorUnion: case ZigTypeIdErrorSet: case ZigTypeIdFn: case ZigTypeIdBoundFn: case ZigTypeIdVector: case ZigTypeIdAnyFrame: return nullptr; } zig_unreachable(); } bool type_is_resolved(ZigType *type_entry, ResolveStatus status) { switch (type_entry->id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdStruct: return type_entry->data.structure.resolve_status >= status; case ZigTypeIdUnion: return type_entry->data.unionation.resolve_status >= status; case ZigTypeIdEnum: return type_entry->data.enumeration.resolve_status >= status; case ZigTypeIdFnFrame: switch (status) { case ResolveStatusInvalid: zig_unreachable(); case ResolveStatusBeingInferred: zig_unreachable(); case ResolveStatusUnstarted: case ResolveStatusZeroBitsKnown: return true; case ResolveStatusAlignmentKnown: case ResolveStatusSizeKnown: return type_entry->data.frame.locals_struct != nullptr; case ResolveStatusLLVMFwdDecl: case ResolveStatusLLVMFull: return type_entry->llvm_type != nullptr; } zig_unreachable(); case ZigTypeIdOpaque: return status < ResolveStatusSizeKnown; case ZigTypeIdPointer: switch (status) { case ResolveStatusInvalid: zig_unreachable(); case ResolveStatusBeingInferred: zig_unreachable(); case ResolveStatusUnstarted: return true; case ResolveStatusZeroBitsKnown: case ResolveStatusAlignmentKnown: case ResolveStatusSizeKnown: return type_entry->abi_size != SIZE_MAX; case ResolveStatusLLVMFwdDecl: case ResolveStatusLLVMFull: return type_entry->llvm_type != nullptr; } zig_unreachable(); case ZigTypeIdMetaType: case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdUnreachable: case ZigTypeIdInt: case ZigTypeIdFloat: case ZigTypeIdArray: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdOptional: case ZigTypeIdErrorUnion: case ZigTypeIdErrorSet: case ZigTypeIdFn: case ZigTypeIdBoundFn: case ZigTypeIdVector: case ZigTypeIdAnyFrame: return true; } zig_unreachable(); } bool type_is_complete(ZigType *type_entry) { return type_is_resolved(type_entry, ResolveStatusSizeKnown); } uint64_t type_size(CodeGen *g, ZigType *type_entry) { assert(type_is_resolved(type_entry, ResolveStatusSizeKnown)); return type_entry->abi_size; } uint64_t type_size_bits(CodeGen *g, ZigType *type_entry) { assert(type_is_resolved(type_entry, ResolveStatusSizeKnown)); return type_entry->size_in_bits; } uint32_t get_abi_alignment(CodeGen *g, ZigType *type_entry) { assert(type_is_resolved(type_entry, ResolveStatusAlignmentKnown)); return type_entry->abi_align; } static bool is_slice(ZigType *type) { return type->id == ZigTypeIdStruct && type->data.structure.special == StructSpecialSlice; } ZigType *get_smallest_unsigned_int_type(CodeGen *g, uint64_t x) { return get_int_type(g, false, bits_needed_for_unsigned(x)); } ZigType *get_any_frame_type(CodeGen *g, ZigType *result_type) { if (result_type != nullptr && result_type->any_frame_parent != nullptr) { return result_type->any_frame_parent; } else if (result_type == nullptr && g->builtin_types.entry_any_frame != nullptr) { return g->builtin_types.entry_any_frame; } ZigType *entry = new_type_table_entry(ZigTypeIdAnyFrame); entry->abi_size = g->builtin_types.entry_usize->abi_size; entry->size_in_bits = g->builtin_types.entry_usize->size_in_bits; entry->abi_align = g->builtin_types.entry_usize->abi_align; entry->data.any_frame.result_type = result_type; buf_init_from_str(&entry->name, "anyframe"); if (result_type != nullptr) { buf_appendf(&entry->name, "->%s", buf_ptr(&result_type->name)); } if (result_type != nullptr) { result_type->any_frame_parent = entry; } else if (result_type == nullptr) { g->builtin_types.entry_any_frame = entry; } return entry; } ZigType *get_fn_frame_type(CodeGen *g, ZigFn *fn) { if (fn->frame_type != nullptr) { return fn->frame_type; } ZigType *entry = new_type_table_entry(ZigTypeIdFnFrame); buf_resize(&entry->name, 0); buf_appendf(&entry->name, "@Frame(%s)", buf_ptr(&fn->symbol_name)); entry->data.frame.fn = fn; // Async function frames are always non-zero bits because they always have a resume index. entry->abi_size = SIZE_MAX; entry->size_in_bits = SIZE_MAX; fn->frame_type = entry; return entry; } static void append_ptr_type_attrs(Buf *type_name, ZigType *ptr_type) { const char *const_str = ptr_type->data.pointer.is_const ? "const " : ""; const char *volatile_str = ptr_type->data.pointer.is_volatile ? "volatile " : ""; const char *allow_zero_str; if (ptr_type->data.pointer.ptr_len == PtrLenC) { assert(ptr_type->data.pointer.allow_zero); allow_zero_str = ""; } else { allow_zero_str = ptr_type->data.pointer.allow_zero ? "allowzero " : ""; } if (ptr_type->data.pointer.explicit_alignment != 0 || ptr_type->data.pointer.host_int_bytes != 0 || ptr_type->data.pointer.vector_index != VECTOR_INDEX_NONE) { buf_appendf(type_name, "align("); if (ptr_type->data.pointer.explicit_alignment != 0) { buf_appendf(type_name, "%" PRIu32, ptr_type->data.pointer.explicit_alignment); } if (ptr_type->data.pointer.host_int_bytes != 0) { buf_appendf(type_name, ":%" PRIu32 ":%" PRIu32, ptr_type->data.pointer.bit_offset_in_host, ptr_type->data.pointer.host_int_bytes); } if (ptr_type->data.pointer.vector_index == VECTOR_INDEX_RUNTIME) { buf_appendf(type_name, ":?"); } else if (ptr_type->data.pointer.vector_index != VECTOR_INDEX_NONE) { buf_appendf(type_name, ":%" PRIu32, ptr_type->data.pointer.vector_index); } buf_appendf(type_name, ") "); } buf_appendf(type_name, "%s%s%s", const_str, volatile_str, allow_zero_str); if (ptr_type->data.pointer.inferred_struct_field != nullptr) { buf_appendf(type_name, " field '%s' of %s)", buf_ptr(ptr_type->data.pointer.inferred_struct_field->field_name), buf_ptr(&ptr_type->data.pointer.inferred_struct_field->inferred_struct_type->name)); } else { buf_appendf(type_name, "%s", buf_ptr(&ptr_type->data.pointer.child_type->name)); } } ZigType *get_pointer_to_type_extra2(CodeGen *g, ZigType *child_type, bool is_const, bool is_volatile, PtrLen ptr_len, uint32_t byte_alignment, uint32_t bit_offset_in_host, uint32_t host_int_bytes, bool allow_zero, uint32_t vector_index, InferredStructField *inferred_struct_field, ZigValue *sentinel) { assert(ptr_len != PtrLenC || allow_zero); assert(!type_is_invalid(child_type)); assert(ptr_len == PtrLenSingle || child_type->id != ZigTypeIdOpaque); if (byte_alignment != 0) { uint32_t abi_alignment = get_abi_alignment(g, child_type); if (byte_alignment == abi_alignment) byte_alignment = 0; } if (host_int_bytes != 0 && vector_index == VECTOR_INDEX_NONE) { uint32_t child_type_bits = type_size_bits(g, child_type); if (host_int_bytes * 8 == child_type_bits) { assert(bit_offset_in_host == 0); host_int_bytes = 0; } } TypeId type_id = {}; ZigType **parent_pointer = nullptr; if (host_int_bytes != 0 || is_volatile || byte_alignment != 0 || ptr_len != PtrLenSingle || allow_zero || vector_index != VECTOR_INDEX_NONE || inferred_struct_field != nullptr || sentinel != nullptr) { type_id.id = ZigTypeIdPointer; type_id.data.pointer.codegen = g; type_id.data.pointer.child_type = child_type; type_id.data.pointer.is_const = is_const; type_id.data.pointer.is_volatile = is_volatile; type_id.data.pointer.alignment = byte_alignment; type_id.data.pointer.bit_offset_in_host = bit_offset_in_host; type_id.data.pointer.host_int_bytes = host_int_bytes; type_id.data.pointer.ptr_len = ptr_len; type_id.data.pointer.allow_zero = allow_zero; type_id.data.pointer.vector_index = vector_index; type_id.data.pointer.inferred_struct_field = inferred_struct_field; type_id.data.pointer.sentinel = sentinel; auto existing_entry = g->type_table.maybe_get(type_id); if (existing_entry) return existing_entry->value; } else { assert(bit_offset_in_host == 0); parent_pointer = &child_type->pointer_parent[(is_const ? 1 : 0)]; if (*parent_pointer) { assert((*parent_pointer)->data.pointer.explicit_alignment == 0); return *parent_pointer; } } ZigType *entry = new_type_table_entry(ZigTypeIdPointer); buf_resize(&entry->name, 0); if (inferred_struct_field != nullptr) { buf_appendf(&entry->name, "("); } switch (ptr_len) { case PtrLenSingle: assert(sentinel == nullptr); buf_appendf(&entry->name, "*"); break; case PtrLenUnknown: buf_appendf(&entry->name, "[*"); break; case PtrLenC: assert(sentinel == nullptr); buf_appendf(&entry->name, "[*c]"); break; } if (sentinel != nullptr) { buf_appendf(&entry->name, ":"); render_const_value(g, &entry->name, sentinel); } switch (ptr_len) { case PtrLenSingle: case PtrLenC: break; case PtrLenUnknown: buf_appendf(&entry->name, "]"); break; } if (inferred_struct_field != nullptr) { entry->abi_size = SIZE_MAX; entry->size_in_bits = SIZE_MAX; entry->abi_align = UINT32_MAX; } else if (type_is_resolved(child_type, ResolveStatusZeroBitsKnown)) { if (type_has_bits(g, child_type)) { entry->abi_size = g->builtin_types.entry_usize->abi_size; entry->size_in_bits = g->builtin_types.entry_usize->size_in_bits; entry->abi_align = g->builtin_types.entry_usize->abi_align; } else { assert(byte_alignment == 0); entry->abi_size = 0; entry->size_in_bits = 0; entry->abi_align = 0; } } else { entry->abi_size = SIZE_MAX; entry->size_in_bits = SIZE_MAX; entry->abi_align = UINT32_MAX; } entry->data.pointer.ptr_len = ptr_len; entry->data.pointer.child_type = child_type; entry->data.pointer.is_const = is_const; entry->data.pointer.is_volatile = is_volatile; entry->data.pointer.explicit_alignment = byte_alignment; entry->data.pointer.bit_offset_in_host = bit_offset_in_host; entry->data.pointer.host_int_bytes = host_int_bytes; entry->data.pointer.allow_zero = allow_zero; entry->data.pointer.vector_index = vector_index; entry->data.pointer.inferred_struct_field = inferred_struct_field; entry->data.pointer.sentinel = sentinel; append_ptr_type_attrs(&entry->name, entry); if (parent_pointer) { *parent_pointer = entry; } else { g->type_table.put(type_id, entry); } return entry; } ZigType *get_pointer_to_type_extra(CodeGen *g, ZigType *child_type, bool is_const, bool is_volatile, PtrLen ptr_len, uint32_t byte_alignment, uint32_t bit_offset_in_host, uint32_t host_int_bytes, bool allow_zero) { return get_pointer_to_type_extra2(g, child_type, is_const, is_volatile, ptr_len, byte_alignment, bit_offset_in_host, host_int_bytes, allow_zero, VECTOR_INDEX_NONE, nullptr, nullptr); } ZigType *get_pointer_to_type(CodeGen *g, ZigType *child_type, bool is_const) { return get_pointer_to_type_extra2(g, child_type, is_const, false, PtrLenSingle, 0, 0, 0, false, VECTOR_INDEX_NONE, nullptr, nullptr); } ZigType *get_optional_type(CodeGen *g, ZigType *child_type) { ZigType *result = get_optional_type2(g, child_type); if (result == nullptr) { codegen_report_errors_and_exit(g); } return result; } ZigType *get_optional_type2(CodeGen *g, ZigType *child_type) { if (child_type->optional_parent != nullptr) { return child_type->optional_parent; } Error err; if ((err = type_resolve(g, child_type, ResolveStatusSizeKnown))) { return nullptr; } ZigType *entry = new_type_table_entry(ZigTypeIdOptional); buf_resize(&entry->name, 0); buf_appendf(&entry->name, "?%s", buf_ptr(&child_type->name)); if (!type_has_bits(g, child_type)) { entry->size_in_bits = g->builtin_types.entry_bool->size_in_bits; entry->abi_size = g->builtin_types.entry_bool->abi_size; entry->abi_align = g->builtin_types.entry_bool->abi_align; } else if (type_is_nonnull_ptr(g, child_type) || child_type->id == ZigTypeIdErrorSet) { // This is an optimization but also is necessary for calling C // functions where all pointers are optional pointers. // Function types are technically pointers. entry->size_in_bits = child_type->size_in_bits; entry->abi_size = child_type->abi_size; entry->abi_align = child_type->abi_align; } else { // This value only matters if the type is legal in a packed struct, which is not // true for optional types which did not fit the above 2 categories (zero bit child type, // or nonnull ptr child type, or error set child type). entry->size_in_bits = child_type->size_in_bits + 1; // We're going to make a struct with the child type as the first field, // and a bool as the second. Since the child type's abi alignment is guaranteed // to be >= the bool's abi size (1 byte), the added size is exactly equal to the // child type's ABI alignment. assert(child_type->abi_align >= g->builtin_types.entry_bool->abi_size); entry->abi_align = child_type->abi_align; entry->abi_size = child_type->abi_size + child_type->abi_align; } entry->data.maybe.child_type = child_type; entry->data.maybe.resolve_status = ResolveStatusSizeKnown; child_type->optional_parent = entry; return entry; } static size_t align_forward(size_t addr, size_t alignment) { return (addr + alignment - 1) & ~(alignment - 1); } static size_t next_field_offset(size_t offset, size_t align_from_zero, size_t field_size, size_t next_field_align) { // Convert offset to a pretend address which has the specified alignment. size_t addr = offset + align_from_zero; // March the address forward to respect the field alignment. size_t aligned_addr = align_forward(addr + field_size, next_field_align); // Convert back from pretend address to offset. return aligned_addr - align_from_zero; } ZigType *get_error_union_type(CodeGen *g, ZigType *err_set_type, ZigType *payload_type) { assert(err_set_type->id == ZigTypeIdErrorSet); assert(!type_is_invalid(payload_type)); TypeId type_id = {}; type_id.id = ZigTypeIdErrorUnion; type_id.data.error_union.err_set_type = err_set_type; type_id.data.error_union.payload_type = payload_type; auto existing_entry = g->type_table.maybe_get(type_id); if (existing_entry) { return existing_entry->value; } Error err; if ((err = type_resolve(g, err_set_type, ResolveStatusSizeKnown))) return g->builtin_types.entry_invalid; if ((err = type_resolve(g, payload_type, ResolveStatusSizeKnown))) return g->builtin_types.entry_invalid; ZigType *entry = new_type_table_entry(ZigTypeIdErrorUnion); buf_resize(&entry->name, 0); buf_appendf(&entry->name, "%s!%s", buf_ptr(&err_set_type->name), buf_ptr(&payload_type->name)); entry->data.error_union.err_set_type = err_set_type; entry->data.error_union.payload_type = payload_type; if (!type_has_bits(g, payload_type)) { if (type_has_bits(g, err_set_type)) { entry->size_in_bits = err_set_type->size_in_bits; entry->abi_size = err_set_type->abi_size; entry->abi_align = err_set_type->abi_align; } else { entry->size_in_bits = 0; entry->abi_size = 0; entry->abi_align = 0; } } else if (!type_has_bits(g, err_set_type)) { entry->size_in_bits = payload_type->size_in_bits; entry->abi_size = payload_type->abi_size; entry->abi_align = payload_type->abi_align; } else { entry->abi_align = max(err_set_type->abi_align, payload_type->abi_align); size_t field_sizes[2]; size_t field_aligns[2]; field_sizes[err_union_err_index] = err_set_type->abi_size; field_aligns[err_union_err_index] = err_set_type->abi_align; field_sizes[err_union_payload_index] = payload_type->abi_size; field_aligns[err_union_payload_index] = payload_type->abi_align; size_t field2_offset = next_field_offset(0, entry->abi_align, field_sizes[0], field_aligns[1]); entry->abi_size = next_field_offset(field2_offset, entry->abi_align, field_sizes[1], entry->abi_align); entry->size_in_bits = entry->abi_size * 8; entry->data.error_union.pad_bytes = entry->abi_size - (field2_offset + field_sizes[1]); } g->type_table.put(type_id, entry); return entry; } ZigType *get_array_type(CodeGen *g, ZigType *child_type, uint64_t array_size, ZigValue *sentinel) { Error err; TypeId type_id = {}; type_id.id = ZigTypeIdArray; type_id.data.array.codegen = g; type_id.data.array.child_type = child_type; type_id.data.array.size = array_size; type_id.data.array.sentinel = sentinel; auto existing_entry = g->type_table.maybe_get(type_id); if (existing_entry) { return existing_entry->value; } size_t full_array_size = array_size + ((sentinel != nullptr) ? 1 : 0); if (full_array_size != 0 && (err = type_resolve(g, child_type, ResolveStatusSizeKnown))) { codegen_report_errors_and_exit(g); } ZigType *entry = new_type_table_entry(ZigTypeIdArray); buf_resize(&entry->name, 0); buf_appendf(&entry->name, "[%" ZIG_PRI_u64, array_size); if (sentinel != nullptr) { buf_appendf(&entry->name, ":"); render_const_value(g, &entry->name, sentinel); } buf_appendf(&entry->name, "]%s", buf_ptr(&child_type->name)); entry->size_in_bits = child_type->size_in_bits * full_array_size; entry->abi_align = (full_array_size == 0) ? 0 : child_type->abi_align; entry->abi_size = child_type->abi_size * full_array_size; entry->data.array.child_type = child_type; entry->data.array.len = array_size; entry->data.array.sentinel = sentinel; g->type_table.put(type_id, entry); return entry; } ZigType *get_slice_type(CodeGen *g, ZigType *ptr_type) { Error err; assert(ptr_type->id == ZigTypeIdPointer); assert(ptr_type->data.pointer.ptr_len == PtrLenUnknown); ZigType **parent_pointer = &ptr_type->data.pointer.slice_parent; if (*parent_pointer) { return *parent_pointer; } // We use the pointer type's abi size below, so we have to resolve it now. if ((err = type_resolve(g, ptr_type, ResolveStatusSizeKnown))) { codegen_report_errors_and_exit(g); } ZigType *entry = new_type_table_entry(ZigTypeIdStruct); buf_resize(&entry->name, 0); buf_appendf(&entry->name, "["); if (ptr_type->data.pointer.sentinel != nullptr) { buf_appendf(&entry->name, ":"); render_const_value(g, &entry->name, ptr_type->data.pointer.sentinel); } buf_appendf(&entry->name, "]"); append_ptr_type_attrs(&entry->name, ptr_type); unsigned element_count = 2; Buf *ptr_field_name = buf_create_from_str("ptr"); Buf *len_field_name = buf_create_from_str("len"); entry->data.structure.resolve_status = ResolveStatusSizeKnown; entry->data.structure.layout = ContainerLayoutAuto; entry->data.structure.special = StructSpecialSlice; entry->data.structure.src_field_count = element_count; entry->data.structure.gen_field_count = element_count; entry->data.structure.fields = alloc_type_struct_fields(element_count); entry->data.structure.fields_by_name.init(element_count); entry->data.structure.fields[slice_ptr_index]->name = ptr_field_name; entry->data.structure.fields[slice_ptr_index]->type_entry = ptr_type; entry->data.structure.fields[slice_ptr_index]->src_index = slice_ptr_index; entry->data.structure.fields[slice_ptr_index]->gen_index = 0; entry->data.structure.fields[slice_ptr_index]->offset = 0; entry->data.structure.fields[slice_len_index]->name = len_field_name; entry->data.structure.fields[slice_len_index]->type_entry = g->builtin_types.entry_usize; entry->data.structure.fields[slice_len_index]->src_index = slice_len_index; entry->data.structure.fields[slice_len_index]->gen_index = 1; entry->data.structure.fields[slice_len_index]->offset = ptr_type->abi_size; entry->data.structure.fields_by_name.put(ptr_field_name, entry->data.structure.fields[slice_ptr_index]); entry->data.structure.fields_by_name.put(len_field_name, entry->data.structure.fields[slice_len_index]); switch (type_requires_comptime(g, ptr_type)) { case ReqCompTimeInvalid: zig_unreachable(); case ReqCompTimeNo: break; case ReqCompTimeYes: entry->data.structure.requires_comptime = true; } if (!type_has_bits(g, ptr_type)) { entry->data.structure.gen_field_count = 1; entry->data.structure.fields[slice_ptr_index]->gen_index = SIZE_MAX; entry->data.structure.fields[slice_len_index]->gen_index = 0; } if (type_has_bits(g, ptr_type)) { entry->size_in_bits = ptr_type->size_in_bits + g->builtin_types.entry_usize->size_in_bits; entry->abi_size = ptr_type->abi_size + g->builtin_types.entry_usize->abi_size; entry->abi_align = ptr_type->abi_align; } else { entry->size_in_bits = g->builtin_types.entry_usize->size_in_bits; entry->abi_size = g->builtin_types.entry_usize->abi_size; entry->abi_align = g->builtin_types.entry_usize->abi_align; } *parent_pointer = entry; return entry; } static uint32_t node_line_onebased(AstNode *node) { RootStruct *root_struct = node->owner->data.structure.root_struct; assert(node->main_token < root_struct->token_count); return root_struct->token_locs[node->main_token].line + 1; } static uint32_t node_column_onebased(AstNode *node) { RootStruct *root_struct = node->owner->data.structure.root_struct; assert(node->main_token < root_struct->token_count); return root_struct->token_locs[node->main_token].column + 1; } ZigType *get_opaque_type(CodeGen *g, Scope *scope, AstNode *source_node, const char *full_name, Buf *bare_name) { ZigType *entry = new_type_table_entry(ZigTypeIdOpaque); buf_init_from_str(&entry->name, full_name); ZigType *import = scope ? get_scope_import(scope) : nullptr; unsigned line = source_node ? node_line_onebased(source_node) : 0; // Note: duplicated in get_partial_container_type entry->llvm_type = LLVMInt8Type(); entry->llvm_di_type = ZigLLVMCreateDebugForwardDeclType(g->dbuilder, ZigLLVMTag_DW_structure_type(), full_name, import ? ZigLLVMFileToScope(import->data.structure.root_struct->di_file) : nullptr, import ? import->data.structure.root_struct->di_file : nullptr, line); entry->data.opaque.decl_node = source_node; entry->data.opaque.bare_name = bare_name; entry->data.opaque.decls_scope = create_decls_scope( g, source_node, scope, entry, import, &entry->name); // The actual size is unknown, but the value must not be 0 because that // is how type_has_bits is determined. entry->abi_size = SIZE_MAX; entry->size_in_bits = SIZE_MAX; entry->abi_align = 1; return entry; } ZigType *get_bound_fn_type(CodeGen *g, ZigFn *fn_entry) { ZigType *fn_type = fn_entry->type_entry; assert(fn_type->id == ZigTypeIdFn); if (fn_type->data.fn.bound_fn_parent) return fn_type->data.fn.bound_fn_parent; ZigType *bound_fn_type = new_type_table_entry(ZigTypeIdBoundFn); bound_fn_type->data.bound_fn.fn_type = fn_type; buf_resize(&bound_fn_type->name, 0); buf_appendf(&bound_fn_type->name, "(bound %s)", buf_ptr(&fn_type->name)); fn_type->data.fn.bound_fn_parent = bound_fn_type; return bound_fn_type; } const char *calling_convention_name(CallingConvention cc) { switch (cc) { case CallingConventionUnspecified: return "Unspecified"; case CallingConventionC: return "C"; case CallingConventionNaked: return "Naked"; case CallingConventionAsync: return "Async"; case CallingConventionInterrupt: return "Interrupt"; case CallingConventionSignal: return "Signal"; case CallingConventionStdcall: return "Stdcall"; case CallingConventionFastcall: return "Fastcall"; case CallingConventionVectorcall: return "Vectorcall"; case CallingConventionThiscall: return "Thiscall"; case CallingConventionAPCS: return "APCS"; case CallingConventionAAPCS: return "AAPCS"; case CallingConventionAAPCSVFP: return "AAPCSVFP"; case CallingConventionInline: return "Inline"; case CallingConventionSysV: return "SysV"; } zig_unreachable(); } bool calling_convention_allows_zig_types(CallingConvention cc) { switch (cc) { case CallingConventionUnspecified: case CallingConventionAsync: case CallingConventionInline: return true; case CallingConventionC: case CallingConventionNaked: case CallingConventionInterrupt: case CallingConventionSignal: case CallingConventionStdcall: case CallingConventionFastcall: case CallingConventionVectorcall: case CallingConventionThiscall: case CallingConventionAPCS: case CallingConventionAAPCS: case CallingConventionAAPCSVFP: case CallingConventionSysV: return false; } zig_unreachable(); } const char *address_space_name(AddressSpace as) { switch (as) { case AddressSpaceGeneric: return "generic"; case AddressSpaceGS: return "gs"; case AddressSpaceFS: return "fs"; case AddressSpaceSS: return "ss"; } zig_unreachable(); } ZigType *get_stack_trace_type(CodeGen *g) { if (g->stack_trace_type == nullptr) { g->stack_trace_type = get_builtin_type(g, "StackTrace"); assertNoError(type_resolve(g, g->stack_trace_type, ResolveStatusZeroBitsKnown)); } return g->stack_trace_type; } bool want_first_arg_sret(CodeGen *g, FnTypeId *fn_type_id) { if (fn_type_id->cc == CallingConventionUnspecified || fn_type_id->cc == CallingConventionInline) { return handle_is_ptr(g, fn_type_id->return_type); } if (fn_type_id->cc != CallingConventionC) { return false; } if (type_is_c_abi_int_bail(g, fn_type_id->return_type)) { return false; } if (g->zig_target->arch == ZigLLVM_x86 || g->zig_target->arch == ZigLLVM_x86_64 || target_is_arm(g->zig_target) || target_is_riscv(g->zig_target) || target_is_wasm(g->zig_target) || target_is_sparc(g->zig_target) || target_is_ppc(g->zig_target)) { X64CABIClass abi_class = type_c_abi_x86_64_class(g, fn_type_id->return_type); return abi_class == X64CABIClass_MEMORY || abi_class == X64CABIClass_MEMORY_nobyval; } else if (g->zig_target->arch == ZigLLVM_mips || g->zig_target->arch == ZigLLVM_mipsel) { return false; } zig_panic("TODO implement C ABI for this architecture. See https://github.com/ziglang/zig/issues/1481"); } ZigType *get_fn_type(CodeGen *g, FnTypeId *fn_type_id) { Error err; auto table_entry = g->fn_type_table.maybe_get(fn_type_id); if (table_entry) { return table_entry->value; } if (fn_type_id->return_type != nullptr) { if ((err = type_resolve(g, fn_type_id->return_type, ResolveStatusSizeKnown))) return g->builtin_types.entry_invalid; assert(fn_type_id->return_type->id != ZigTypeIdOpaque); } else { zig_panic("TODO implement inferred return types https://github.com/ziglang/zig/issues/447"); } ZigType *fn_type = new_type_table_entry(ZigTypeIdFn); fn_type->data.fn.fn_type_id = *fn_type_id; // populate the name of the type buf_resize(&fn_type->name, 0); buf_appendf(&fn_type->name, "fn("); for (size_t i = 0; i < fn_type_id->param_count; i += 1) { FnTypeParamInfo *param_info = &fn_type_id->param_info[i]; ZigType *param_type = param_info->type; const char *comma = (i == 0) ? "" : ", "; const char *noalias_str = param_info->is_noalias ? "noalias " : ""; buf_appendf(&fn_type->name, "%s%s%s", comma, noalias_str, buf_ptr(&param_type->name)); } if (fn_type_id->is_var_args) { const char *comma = (fn_type_id->param_count == 0) ? "" : ", "; buf_appendf(&fn_type->name, "%s...", comma); } buf_appendf(&fn_type->name, ")"); if (fn_type_id->alignment != 0) { buf_appendf(&fn_type->name, " align(%" PRIu32 ")", fn_type_id->alignment); } if (fn_type_id->cc != CallingConventionUnspecified) { buf_appendf(&fn_type->name, " callconv(.%s)", calling_convention_name(fn_type_id->cc)); } buf_appendf(&fn_type->name, " %s", buf_ptr(&fn_type_id->return_type->name)); // The fn_type is a pointer; not to be confused with the raw function type. fn_type->size_in_bits = g->builtin_types.entry_usize->size_in_bits; fn_type->abi_size = g->builtin_types.entry_usize->abi_size; fn_type->abi_align = g->builtin_types.entry_usize->abi_align; g->fn_type_table.put(&fn_type->data.fn.fn_type_id, fn_type); return fn_type; } static ZigTypeId container_to_type(ContainerKind kind) { switch (kind) { case ContainerKindStruct: return ZigTypeIdStruct; case ContainerKindEnum: return ZigTypeIdEnum; case ContainerKindUnion: return ZigTypeIdUnion; case ContainerKindOpaque: return ZigTypeIdOpaque; } zig_unreachable(); } // This is like get_partial_container_type except it's for the implicit root struct of files. static ZigType *get_root_container_type(CodeGen *g, const char *full_name, Buf *bare_name, RootStruct *root_struct) { ZigType *entry = new_type_table_entry(ZigTypeIdStruct); entry->data.structure.decls_scope = create_decls_scope(g, nullptr, nullptr, entry, entry, bare_name); entry->data.structure.root_struct = root_struct; entry->data.structure.layout = ContainerLayoutAuto; if (full_name[0] == '\0') { buf_init_from_str(&entry->name, "(root)"); } else { buf_init_from_str(&entry->name, full_name); } return entry; } ZigType *get_partial_container_type(CodeGen *g, Scope *scope, ContainerKind kind, AstNode *decl_node, const char *full_name, Buf *bare_name, ContainerLayout layout) { ZigTypeId type_id = container_to_type(kind); ZigType *entry = new_container_type_entry(g, type_id, decl_node, scope, bare_name); switch (kind) { case ContainerKindStruct: entry->data.structure.decl_node = decl_node; entry->data.structure.layout = layout; break; case ContainerKindEnum: entry->data.enumeration.decl_node = decl_node; entry->data.enumeration.layout = layout; break; case ContainerKindUnion: entry->data.unionation.decl_node = decl_node; entry->data.unionation.layout = layout; break; case ContainerKindOpaque: { ZigType *import = scope ? get_scope_import(scope) : nullptr; unsigned line = decl_node ? node_line_onebased(decl_node) : 0; // Note: duplicated in get_opaque_type entry->llvm_type = LLVMInt8Type(); entry->llvm_di_type = ZigLLVMCreateDebugForwardDeclType(g->dbuilder, ZigLLVMTag_DW_structure_type(), full_name, import ? ZigLLVMFileToScope(import->data.structure.root_struct->di_file) : nullptr, import ? import->data.structure.root_struct->di_file : nullptr, line); entry->data.opaque.decl_node = decl_node; entry->abi_size = SIZE_MAX; entry->size_in_bits = SIZE_MAX; entry->abi_align = 1; break; } } buf_init_from_str(&entry->name, full_name); return entry; } ZigValue *analyze_const_value(CodeGen *g, Scope *scope, AstNode *node, ZigType *type_entry, Buf *type_name, UndefAllowed undef) { Error err; ZigValue *result = g->pass1_arena->create<ZigValue>(); ZigValue *result_ptr = g->pass1_arena->create<ZigValue>(); result->special = ConstValSpecialUndef; result->type = (type_entry == nullptr) ? g->builtin_types.entry_anytype : type_entry; result_ptr->special = ConstValSpecialStatic; result_ptr->type = get_pointer_to_type(g, result->type, false); result_ptr->data.x_ptr.mut = ConstPtrMutComptimeVar; result_ptr->data.x_ptr.special = ConstPtrSpecialRef; result_ptr->data.x_ptr.data.ref.pointee = result; size_t backward_branch_count = 0; size_t backward_branch_quota = default_backward_branch_quota; if ((err = ir_eval_const_value(g, scope, node, result_ptr, &backward_branch_count, &backward_branch_quota, nullptr, nullptr, node, type_name, nullptr, nullptr, undef))) { return g->invalid_inst_gen->value; } return result; } Error type_val_resolve_zero_bits(CodeGen *g, ZigValue *type_val, ZigType *parent_type, ZigValue *parent_type_val, bool *is_zero_bits) { Error err; if (type_val->special != ConstValSpecialLazy) { assert(type_val->special == ConstValSpecialStatic); // Self-referencing types via pointers are allowed and have non-zero size ZigType *ty = type_val->data.x_type; while (ty->id == ZigTypeIdPointer && !ty->data.pointer.resolve_loop_flag_zero_bits) { ty = ty->data.pointer.child_type; } if ((ty->id == ZigTypeIdStruct && ty->data.structure.resolve_loop_flag_zero_bits) || (ty->id == ZigTypeIdUnion && ty->data.unionation.resolve_loop_flag_zero_bits) || (ty->id == ZigTypeIdPointer && ty->data.pointer.resolve_loop_flag_zero_bits)) { *is_zero_bits = false; return ErrorNone; } if ((err = type_resolve(g, type_val->data.x_type, ResolveStatusZeroBitsKnown))) return err; *is_zero_bits = (type_val->data.x_type->abi_size == 0); return ErrorNone; } switch (type_val->data.x_lazy->id) { case LazyValueIdInvalid: case LazyValueIdAlignOf: case LazyValueIdSizeOf: case LazyValueIdTypeInfoDecls: zig_unreachable(); case LazyValueIdPtrType: { LazyValuePtrType *lazy_ptr_type = reinterpret_cast<LazyValuePtrType *>(type_val->data.x_lazy); if (parent_type_val == lazy_ptr_type->elem_type->value) { // Does a struct which contains a pointer field to itself have bits? Yes. *is_zero_bits = false; return ErrorNone; } else { if (parent_type_val == nullptr) { parent_type_val = type_val; } return type_val_resolve_zero_bits(g, lazy_ptr_type->elem_type->value, parent_type, parent_type_val, is_zero_bits); } } case LazyValueIdPtrTypeSimple: case LazyValueIdPtrTypeSimpleConst: { LazyValuePtrTypeSimple *lazy_ptr_type = reinterpret_cast<LazyValuePtrTypeSimple *>(type_val->data.x_lazy); if (parent_type_val == lazy_ptr_type->elem_type->value) { // Does a struct which contains a pointer field to itself have bits? Yes. *is_zero_bits = false; return ErrorNone; } else { if (parent_type_val == nullptr) { parent_type_val = type_val; } return type_val_resolve_zero_bits(g, lazy_ptr_type->elem_type->value, parent_type, parent_type_val, is_zero_bits); } } case LazyValueIdArrayType: { LazyValueArrayType *lazy_array_type = reinterpret_cast<LazyValueArrayType *>(type_val->data.x_lazy); // The sentinel counts as an extra element if (lazy_array_type->length == 0 && lazy_array_type->sentinel == nullptr) { *is_zero_bits = true; return ErrorNone; } if ((err = type_val_resolve_zero_bits(g, lazy_array_type->elem_type->value, parent_type, nullptr, is_zero_bits))) return err; return ErrorNone; } case LazyValueIdOptType: case LazyValueIdSliceType: case LazyValueIdErrUnionType: *is_zero_bits = false; return ErrorNone; case LazyValueIdFnType: { LazyValueFnType *lazy_fn_type = reinterpret_cast<LazyValueFnType *>(type_val->data.x_lazy); *is_zero_bits = lazy_fn_type->is_generic; return ErrorNone; } } zig_unreachable(); } Error type_val_resolve_is_opaque_type(CodeGen *g, ZigValue *type_val, bool *is_opaque_type) { if (type_val->special != ConstValSpecialLazy) { assert(type_val->special == ConstValSpecialStatic); if (type_val->data.x_type == g->builtin_types.entry_anytype) { *is_opaque_type = false; return ErrorNone; } *is_opaque_type = (type_val->data.x_type->id == ZigTypeIdOpaque); return ErrorNone; } switch (type_val->data.x_lazy->id) { case LazyValueIdInvalid: case LazyValueIdAlignOf: case LazyValueIdSizeOf: case LazyValueIdTypeInfoDecls: zig_unreachable(); case LazyValueIdSliceType: case LazyValueIdPtrType: case LazyValueIdPtrTypeSimple: case LazyValueIdPtrTypeSimpleConst: case LazyValueIdFnType: case LazyValueIdOptType: case LazyValueIdErrUnionType: case LazyValueIdArrayType: *is_opaque_type = false; return ErrorNone; } zig_unreachable(); } static ReqCompTime type_val_resolve_requires_comptime(CodeGen *g, ZigValue *type_val) { if (type_val->special != ConstValSpecialLazy) { return type_requires_comptime(g, type_val->data.x_type); } switch (type_val->data.x_lazy->id) { case LazyValueIdInvalid: case LazyValueIdAlignOf: case LazyValueIdSizeOf: case LazyValueIdTypeInfoDecls: zig_unreachable(); case LazyValueIdSliceType: { LazyValueSliceType *lazy_slice_type = reinterpret_cast<LazyValueSliceType *>(type_val->data.x_lazy); return type_val_resolve_requires_comptime(g, lazy_slice_type->elem_type->value); } case LazyValueIdPtrType: { LazyValuePtrType *lazy_ptr_type = reinterpret_cast<LazyValuePtrType *>(type_val->data.x_lazy); return type_val_resolve_requires_comptime(g, lazy_ptr_type->elem_type->value); } case LazyValueIdPtrTypeSimple: case LazyValueIdPtrTypeSimpleConst: { LazyValuePtrTypeSimple *lazy_ptr_type = reinterpret_cast<LazyValuePtrTypeSimple *>(type_val->data.x_lazy); return type_val_resolve_requires_comptime(g, lazy_ptr_type->elem_type->value); } case LazyValueIdOptType: { LazyValueOptType *lazy_opt_type = reinterpret_cast<LazyValueOptType *>(type_val->data.x_lazy); return type_val_resolve_requires_comptime(g, lazy_opt_type->payload_type->value); } case LazyValueIdArrayType: { LazyValueArrayType *lazy_array_type = reinterpret_cast<LazyValueArrayType *>(type_val->data.x_lazy); return type_val_resolve_requires_comptime(g, lazy_array_type->elem_type->value); } case LazyValueIdFnType: { LazyValueFnType *lazy_fn_type = reinterpret_cast<LazyValueFnType *>(type_val->data.x_lazy); if (lazy_fn_type->is_generic) return ReqCompTimeYes; switch (type_val_resolve_requires_comptime(g, lazy_fn_type->return_type->value)) { case ReqCompTimeInvalid: return ReqCompTimeInvalid; case ReqCompTimeYes: return ReqCompTimeYes; case ReqCompTimeNo: break; } size_t param_count = lazy_fn_type->proto_node->data.fn_proto.params.length; for (size_t i = 0; i < param_count; i += 1) { AstNode *param_node = lazy_fn_type->proto_node->data.fn_proto.params.at(i); bool param_is_var_args = param_node->data.param_decl.is_var_args; if (param_is_var_args) break; switch (type_val_resolve_requires_comptime(g, lazy_fn_type->param_types[i]->value)) { case ReqCompTimeInvalid: return ReqCompTimeInvalid; case ReqCompTimeYes: return ReqCompTimeYes; case ReqCompTimeNo: break; } } return ReqCompTimeNo; } case LazyValueIdErrUnionType: { LazyValueErrUnionType *lazy_err_union_type = reinterpret_cast<LazyValueErrUnionType *>(type_val->data.x_lazy); return type_val_resolve_requires_comptime(g, lazy_err_union_type->payload_type->value); } } zig_unreachable(); } Error type_val_resolve_abi_size(CodeGen *g, AstNode *source_node, ZigValue *type_val, size_t *abi_size, size_t *size_in_bits) { Error err; start_over: if (type_val->special != ConstValSpecialLazy) { assert(type_val->special == ConstValSpecialStatic); ZigType *ty = type_val->data.x_type; if ((err = type_resolve(g, ty, ResolveStatusSizeKnown))) return err; *abi_size = ty->abi_size; *size_in_bits = ty->size_in_bits; return ErrorNone; } switch (type_val->data.x_lazy->id) { case LazyValueIdInvalid: case LazyValueIdAlignOf: case LazyValueIdSizeOf: case LazyValueIdTypeInfoDecls: zig_unreachable(); case LazyValueIdSliceType: { LazyValueSliceType *lazy_slice_type = reinterpret_cast<LazyValueSliceType *>(type_val->data.x_lazy); bool is_zero_bits; if ((err = type_val_resolve_zero_bits(g, lazy_slice_type->elem_type->value, nullptr, nullptr, &is_zero_bits))) { return err; } if (is_zero_bits) { *abi_size = g->builtin_types.entry_usize->abi_size; *size_in_bits = g->builtin_types.entry_usize->size_in_bits; } else { *abi_size = g->builtin_types.entry_usize->abi_size * 2; *size_in_bits = g->builtin_types.entry_usize->size_in_bits * 2; } return ErrorNone; } case LazyValueIdPtrType: { LazyValuePtrType *lazy_ptr_type = reinterpret_cast<LazyValuePtrType *>(type_val->data.x_lazy); bool is_zero_bits; if ((err = type_val_resolve_zero_bits(g, lazy_ptr_type->elem_type->value, nullptr, nullptr, &is_zero_bits))) { return err; } if (is_zero_bits) { *abi_size = 0; *size_in_bits = 0; } else { *abi_size = g->builtin_types.entry_usize->abi_size; *size_in_bits = g->builtin_types.entry_usize->size_in_bits; } return ErrorNone; } case LazyValueIdPtrTypeSimple: case LazyValueIdPtrTypeSimpleConst: { LazyValuePtrTypeSimple *lazy_ptr_type = reinterpret_cast<LazyValuePtrTypeSimple *>(type_val->data.x_lazy); bool is_zero_bits; if ((err = type_val_resolve_zero_bits(g, lazy_ptr_type->elem_type->value, nullptr, nullptr, &is_zero_bits))) { return err; } if (is_zero_bits) { *abi_size = 0; *size_in_bits = 0; } else { *abi_size = g->builtin_types.entry_usize->abi_size; *size_in_bits = g->builtin_types.entry_usize->size_in_bits; } return ErrorNone; } case LazyValueIdFnType: *abi_size = g->builtin_types.entry_usize->abi_size; *size_in_bits = g->builtin_types.entry_usize->size_in_bits; return ErrorNone; case LazyValueIdOptType: case LazyValueIdErrUnionType: case LazyValueIdArrayType: if ((err = ir_resolve_lazy(g, source_node, type_val))) return err; goto start_over; } zig_unreachable(); } Error type_val_resolve_abi_align(CodeGen *g, AstNode *source_node, ZigValue *type_val, uint32_t *abi_align) { Error err; if (type_val->special != ConstValSpecialLazy) { assert(type_val->special == ConstValSpecialStatic); ZigType *ty = type_val->data.x_type; if (ty->id == ZigTypeIdPointer) { *abi_align = g->builtin_types.entry_usize->abi_align; return ErrorNone; } if ((err = type_resolve(g, ty, ResolveStatusAlignmentKnown))) return err; *abi_align = ty->abi_align; return ErrorNone; } switch (type_val->data.x_lazy->id) { case LazyValueIdInvalid: case LazyValueIdAlignOf: case LazyValueIdSizeOf: case LazyValueIdTypeInfoDecls: zig_unreachable(); case LazyValueIdSliceType: case LazyValueIdPtrType: case LazyValueIdPtrTypeSimple: case LazyValueIdPtrTypeSimpleConst: case LazyValueIdFnType: *abi_align = g->builtin_types.entry_usize->abi_align; return ErrorNone; case LazyValueIdOptType: { if ((err = ir_resolve_lazy(g, nullptr, type_val))) return err; return type_val_resolve_abi_align(g, source_node, type_val, abi_align); } case LazyValueIdArrayType: { LazyValueArrayType *lazy_array_type = reinterpret_cast<LazyValueArrayType *>(type_val->data.x_lazy); if (lazy_array_type->length + (lazy_array_type->sentinel != nullptr) != 0) return type_val_resolve_abi_align(g, source_node, lazy_array_type->elem_type->value, abi_align); *abi_align = 0; return ErrorNone; } case LazyValueIdErrUnionType: { LazyValueErrUnionType *lazy_err_union_type = reinterpret_cast<LazyValueErrUnionType *>(type_val->data.x_lazy); uint32_t payload_abi_align; if ((err = type_val_resolve_abi_align(g, source_node, lazy_err_union_type->payload_type->value, &payload_abi_align))) { return err; } *abi_align = (payload_abi_align > g->err_tag_type->abi_align) ? payload_abi_align : g->err_tag_type->abi_align; return ErrorNone; } } zig_unreachable(); } static OnePossibleValue type_val_resolve_has_one_possible_value(CodeGen *g, ZigValue *type_val) { if (type_val->special != ConstValSpecialLazy) { return type_has_one_possible_value(g, type_val->data.x_type); } switch (type_val->data.x_lazy->id) { case LazyValueIdInvalid: case LazyValueIdAlignOf: case LazyValueIdSizeOf: case LazyValueIdTypeInfoDecls: zig_unreachable(); case LazyValueIdSliceType: // it has the len field case LazyValueIdOptType: // it has the optional bit case LazyValueIdFnType: return OnePossibleValueNo; case LazyValueIdArrayType: { LazyValueArrayType *lazy_array_type = reinterpret_cast<LazyValueArrayType *>(type_val->data.x_lazy); if (lazy_array_type->length == 0) return OnePossibleValueYes; return type_val_resolve_has_one_possible_value(g, lazy_array_type->elem_type->value); } case LazyValueIdPtrType: case LazyValueIdPtrTypeSimple: case LazyValueIdPtrTypeSimpleConst: { Error err; bool zero_bits; if ((err = type_val_resolve_zero_bits(g, type_val, nullptr, nullptr, &zero_bits))) { return OnePossibleValueInvalid; } if (zero_bits) { return OnePossibleValueYes; } else { return OnePossibleValueNo; } } case LazyValueIdErrUnionType: { LazyValueErrUnionType *lazy_err_union_type = reinterpret_cast<LazyValueErrUnionType *>(type_val->data.x_lazy); switch (type_val_resolve_has_one_possible_value(g, lazy_err_union_type->err_set_type->value)) { case OnePossibleValueInvalid: return OnePossibleValueInvalid; case OnePossibleValueNo: return OnePossibleValueNo; case OnePossibleValueYes: return type_val_resolve_has_one_possible_value(g, lazy_err_union_type->payload_type->value); } } } zig_unreachable(); } ZigType *analyze_type_expr(CodeGen *g, Scope *scope, AstNode *node) { Error err; // Hot path for simple identifiers, to avoid unnecessary memory allocations. if (node->type == NodeTypeIdentifier) { RootStruct *root_struct = node->owner->data.structure.root_struct; Buf *variable_name = token_identifier_buf(root_struct, node->main_token); if (buf_eql_str(variable_name, "_")) goto abort_hot_path; ZigType *primitive_type; if ((err = get_primitive_type(g, variable_name, &primitive_type))) { goto abort_hot_path; } else { return primitive_type; } abort_hot_path:; } ZigValue *result = analyze_const_value(g, scope, node, g->builtin_types.entry_type, nullptr, UndefBad); if (type_is_invalid(result->type)) return g->builtin_types.entry_invalid; src_assert(result->special == ConstValSpecialStatic, node); src_assert(result->data.x_type != nullptr, node); return result->data.x_type; } ZigType *get_generic_fn_type(CodeGen *g, FnTypeId *fn_type_id) { ZigType *fn_type = new_type_table_entry(ZigTypeIdFn); buf_resize(&fn_type->name, 0); buf_appendf(&fn_type->name, "fn("); size_t i = 0; for (; i < fn_type_id->next_param_index; i += 1) { const char *comma_str = (i == 0) ? "" : ","; buf_appendf(&fn_type->name, "%s%s", comma_str, buf_ptr(&fn_type_id->param_info[i].type->name)); } for (; i < fn_type_id->param_count; i += 1) { const char *comma_str = (i == 0) ? "" : ","; buf_appendf(&fn_type->name, "%sanytype", comma_str); } buf_append_str(&fn_type->name, ")"); if (fn_type_id->cc != CallingConventionUnspecified) { buf_appendf(&fn_type->name, " callconv(.%s)", calling_convention_name(fn_type_id->cc)); } buf_append_str(&fn_type->name, " anytype"); fn_type->data.fn.fn_type_id = *fn_type_id; fn_type->data.fn.is_generic = true; fn_type->abi_size = 0; fn_type->size_in_bits = 0; fn_type->abi_align = 0; return fn_type; } CallingConvention cc_from_fn_proto(AstNodeFnProto *fn_proto) { // Compatible with the C ABI if (fn_proto->is_extern || fn_proto->is_export) return CallingConventionC; if (fn_proto->fn_inline == FnInlineAlways) return CallingConventionInline; return CallingConventionUnspecified; } void init_fn_type_id(FnTypeId *fn_type_id, AstNode *proto_node, CallingConvention cc, size_t param_count_alloc) { assert(proto_node->type == NodeTypeFnProto); AstNodeFnProto *fn_proto = &proto_node->data.fn_proto; fn_type_id->cc = cc; fn_type_id->param_count = fn_proto->params.length; fn_type_id->param_info = heap::c_allocator.allocate<FnTypeParamInfo>(param_count_alloc); fn_type_id->next_param_index = 0; fn_type_id->is_var_args = fn_proto->is_var_args; } static bool analyze_const_align(CodeGen *g, Scope *scope, AstNode *node, uint32_t *result) { ZigValue *align_result = analyze_const_value(g, scope, node, get_align_amt_type(g), nullptr, UndefBad); if (type_is_invalid(align_result->type)) return false; uint32_t align_bytes = bigint_as_u32(&align_result->data.x_bigint); if (align_bytes == 0) { add_node_error(g, node, buf_sprintf("alignment must be >= 1")); return false; } if (!is_power_of_2(align_bytes)) { add_node_error(g, node, buf_sprintf("alignment value %" PRIu32 " is not a power of 2", align_bytes)); return false; } *result = align_bytes; return true; } static bool analyze_const_string(CodeGen *g, Scope *scope, AstNode *node, Buf **out_buffer) { ZigType *ptr_type = get_pointer_to_type_extra(g, g->builtin_types.entry_u8, true, false, PtrLenUnknown, 0, 0, 0, false); ZigType *str_type = get_slice_type(g, ptr_type); ZigValue *result_val = analyze_const_value(g, scope, node, str_type, nullptr, UndefBad); if (type_is_invalid(result_val->type)) return false; ZigValue *ptr_field = result_val->data.x_struct.fields[slice_ptr_index]; ZigValue *len_field = result_val->data.x_struct.fields[slice_len_index]; assert(ptr_field->data.x_ptr.special == ConstPtrSpecialBaseArray); ZigValue *array_val = ptr_field->data.x_ptr.data.base_array.array_val; if (array_val->data.x_array.special == ConstArraySpecialBuf) { *out_buffer = array_val->data.x_array.data.s_buf; return true; } expand_undef_array(g, array_val); size_t len = bigint_as_usize(&len_field->data.x_bigint); Buf *result = buf_alloc(); buf_resize(result, len); for (size_t i = 0; i < len; i += 1) { size_t new_index = ptr_field->data.x_ptr.data.base_array.elem_index + i; ZigValue *char_val = &array_val->data.x_array.data.s_none.elements[new_index]; if (char_val->special == ConstValSpecialUndef) { add_node_error(g, node, buf_sprintf("use of undefined value")); return false; } uint64_t big_c = bigint_as_u64(&char_val->data.x_bigint); assert(big_c <= UINT8_MAX); uint8_t c = (uint8_t)big_c; buf_ptr(result)[i] = c; } *out_buffer = result; return true; } static Error emit_error_unless_type_allowed_in_packed_container(CodeGen *g, ZigType *type_entry, AstNode *source_node, const char* container_name) { Error err; switch (type_entry->id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdMetaType: case ZigTypeIdUnreachable: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdErrorUnion: case ZigTypeIdErrorSet: case ZigTypeIdBoundFn: case ZigTypeIdOpaque: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: add_node_error(g, source_node, buf_sprintf("type '%s' not allowed in packed %s; no guaranteed in-memory representation", buf_ptr(&type_entry->name), container_name)); return ErrorSemanticAnalyzeFail; case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdInt: case ZigTypeIdFloat: case ZigTypeIdPointer: case ZigTypeIdFn: case ZigTypeIdVector: return ErrorNone; case ZigTypeIdArray: { ZigType *elem_type = type_entry->data.array.child_type; if ((err = emit_error_unless_type_allowed_in_packed_container(g, elem_type, source_node, container_name))) return err; // TODO revisit this when doing https://github.com/ziglang/zig/issues/1512 size_t abi_size_in_bits = type_size(g, type_entry) * 8; size_t size_in_bits = type_size_bits(g, type_entry); if (abi_size_in_bits == size_in_bits) return ErrorNone; add_node_error(g, source_node, buf_sprintf("array of '%s' not allowed in packed %s due to padding bits (must be padded from %zu to %zu bits)", buf_ptr(&elem_type->name), container_name, size_in_bits, abi_size_in_bits)); return ErrorSemanticAnalyzeFail; } case ZigTypeIdStruct: switch (type_entry->data.structure.layout) { case ContainerLayoutPacked: case ContainerLayoutExtern: return ErrorNone; case ContainerLayoutAuto: add_node_error(g, source_node, buf_sprintf("non-packed, non-extern struct '%s' not allowed in packed %s; no guaranteed in-memory representation", buf_ptr(&type_entry->name), container_name)); return ErrorSemanticAnalyzeFail; } zig_unreachable(); case ZigTypeIdUnion: switch (type_entry->data.unionation.layout) { case ContainerLayoutPacked: case ContainerLayoutExtern: return ErrorNone; case ContainerLayoutAuto: add_node_error(g, source_node, buf_sprintf("non-packed, non-extern union '%s' not allowed in packed %s; no guaranteed in-memory representation", buf_ptr(&type_entry->name), container_name)); return ErrorSemanticAnalyzeFail; } zig_unreachable(); case ZigTypeIdOptional: { ZigType *ptr_type; if ((err = get_codegen_ptr_type(g, type_entry, &ptr_type))) return err; if (ptr_type != nullptr) return ErrorNone; add_node_error(g, source_node, buf_sprintf("type '%s' not allowed in packed %s; no guaranteed in-memory representation", buf_ptr(&type_entry->name), container_name)); return ErrorSemanticAnalyzeFail; } case ZigTypeIdEnum: { AstNode *decl_node = type_entry->data.enumeration.decl_node; if (decl_node->data.container_decl.init_arg_expr != nullptr) { return ErrorNone; } ErrorMsg *msg = add_node_error(g, source_node, buf_sprintf("type '%s' not allowed in packed %s; no guaranteed in-memory representation", buf_ptr(&type_entry->name), container_name)); add_error_note(g, msg, decl_node, buf_sprintf("enum declaration does not specify an integer tag type")); return ErrorSemanticAnalyzeFail; } } zig_unreachable(); } static Error emit_error_unless_type_allowed_in_packed_struct(CodeGen *g, ZigType *type_entry, AstNode *source_node) { return emit_error_unless_type_allowed_in_packed_container(g, type_entry, source_node, "struct"); } static Error emit_error_unless_type_allowed_in_packed_union(CodeGen *g, ZigType *type_entry, AstNode *source_node) { return emit_error_unless_type_allowed_in_packed_container(g, type_entry, source_node, "union"); } Error type_allowed_in_extern(CodeGen *g, ZigType *type_entry, ExternPosition position, bool *result) { Error err; switch (type_entry->id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdMetaType: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdErrorUnion: case ZigTypeIdErrorSet: case ZigTypeIdBoundFn: case ZigTypeIdVoid: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: *result = false; return ErrorNone; case ZigTypeIdUnreachable: *result = position == ExternPositionFunctionReturn; return ErrorNone; case ZigTypeIdOpaque: case ZigTypeIdBool: *result = true; return ErrorNone; case ZigTypeIdInt: switch (type_entry->data.integral.bit_count) { case 8: case 16: case 32: case 64: case 128: *result = true; return ErrorNone; default: *result = false; return ErrorNone; } case ZigTypeIdVector: return type_allowed_in_extern(g, type_entry->data.vector.elem_type, ExternPositionOther, result); case ZigTypeIdFloat: *result = true; return ErrorNone; case ZigTypeIdArray: if ((err = type_allowed_in_extern(g, type_entry->data.array.child_type, ExternPositionOther, result))) return err; *result = *result && position != ExternPositionFunctionParameter && position != ExternPositionFunctionReturn; return ErrorNone; case ZigTypeIdFn: *result = !calling_convention_allows_zig_types(type_entry->data.fn.fn_type_id.cc); return ErrorNone; case ZigTypeIdPointer: if ((err = type_resolve(g, type_entry, ResolveStatusZeroBitsKnown))) return err; bool has_bits; if ((err = type_has_bits2(g, type_entry, &has_bits))) return err; *result = has_bits; return ErrorNone; case ZigTypeIdStruct: *result = type_entry->data.structure.layout == ContainerLayoutExtern || type_entry->data.structure.layout == ContainerLayoutPacked; return ErrorNone; case ZigTypeIdOptional: { ZigType *child_type = type_entry->data.maybe.child_type; if (child_type->id != ZigTypeIdPointer && child_type->id != ZigTypeIdFn) { *result = false; return ErrorNone; } bool is_nonnull_ptr; if ((err = type_is_nonnull_ptr2(g, child_type, &is_nonnull_ptr))) return err; if (!is_nonnull_ptr) { *result = false; return ErrorNone; } return type_allowed_in_extern(g, child_type, ExternPositionOther, result); } case ZigTypeIdEnum: { if ((err = type_resolve(g, type_entry, ResolveStatusZeroBitsKnown))) return err; ZigType *tag_int_type = type_entry->data.enumeration.tag_int_type; if (type_entry->data.enumeration.has_explicit_tag_type) return type_allowed_in_extern(g, tag_int_type, position, result); *result = type_entry->data.enumeration.layout == ContainerLayoutExtern || type_entry->data.enumeration.layout == ContainerLayoutPacked; return ErrorNone; } case ZigTypeIdUnion: *result = type_entry->data.unionation.layout == ContainerLayoutExtern || type_entry->data.unionation.layout == ContainerLayoutPacked; return ErrorNone; } zig_unreachable(); } ZigType *get_auto_err_set_type(CodeGen *g, ZigFn *fn_entry) { ZigType *err_set_type = new_type_table_entry(ZigTypeIdErrorSet); buf_resize(&err_set_type->name, 0); buf_appendf(&err_set_type->name, "@typeInfo(@typeInfo(@TypeOf(%s)).Fn.return_type.?).ErrorUnion.error_set", buf_ptr(&fn_entry->symbol_name)); err_set_type->data.error_set.err_count = 0; err_set_type->data.error_set.errors = nullptr; err_set_type->data.error_set.infer_fn = fn_entry; err_set_type->data.error_set.incomplete = true; err_set_type->size_in_bits = g->builtin_types.entry_global_error_set->size_in_bits; err_set_type->abi_align = g->builtin_types.entry_global_error_set->abi_align; err_set_type->abi_size = g->builtin_types.entry_global_error_set->abi_size; return err_set_type; } // Sync this with get_llvm_cc in codegen.cpp Error emit_error_unless_callconv_allowed_for_target(CodeGen *g, AstNode *source_node, CallingConvention cc) { Error ret = ErrorNone; const char *allowed_platforms = nullptr; switch (cc) { case CallingConventionUnspecified: case CallingConventionC: case CallingConventionNaked: case CallingConventionAsync: case CallingConventionInline: break; case CallingConventionInterrupt: if (g->zig_target->arch != ZigLLVM_x86 && g->zig_target->arch != ZigLLVM_x86_64 && g->zig_target->arch != ZigLLVM_avr && g->zig_target->arch != ZigLLVM_msp430) { allowed_platforms = "x86, x86_64, AVR, and MSP430"; } break; case CallingConventionSignal: if (g->zig_target->arch != ZigLLVM_avr) allowed_platforms = "AVR"; break; case CallingConventionStdcall: case CallingConventionFastcall: case CallingConventionThiscall: if (g->zig_target->arch != ZigLLVM_x86) allowed_platforms = "x86"; break; case CallingConventionVectorcall: if (g->zig_target->arch != ZigLLVM_x86 && !(target_is_arm(g->zig_target) && target_arch_pointer_bit_width(g->zig_target->arch) == 64)) { allowed_platforms = "x86 and AArch64"; } break; case CallingConventionAPCS: case CallingConventionAAPCS: case CallingConventionAAPCSVFP: if (!target_is_arm(g->zig_target)) allowed_platforms = "ARM"; break; case CallingConventionSysV: if (g->zig_target->arch != ZigLLVM_x86_64) allowed_platforms = "x86_64"; } if (allowed_platforms != nullptr) { add_node_error(g, source_node, buf_sprintf( "callconv '%s' is only available on %s, not %s", calling_convention_name(cc), allowed_platforms, target_arch_name(g->zig_target->arch))); ret = ErrorSemanticAnalyzeFail; } return ret; } static ZigType *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *child_scope, ZigFn *fn_entry, CallingConvention cc) { assert(proto_node->type == NodeTypeFnProto); AstNodeFnProto *fn_proto = &proto_node->data.fn_proto; Error err; FnTypeId fn_type_id = {0}; init_fn_type_id(&fn_type_id, proto_node, cc, proto_node->data.fn_proto.params.length); for (; fn_type_id.next_param_index < fn_type_id.param_count; fn_type_id.next_param_index += 1) { AstNode *param_node = fn_proto->params.at(fn_type_id.next_param_index); assert(param_node->type == NodeTypeParamDecl); bool param_is_comptime = param_node->data.param_decl.is_comptime; bool param_is_var_args = param_node->data.param_decl.is_var_args; if (param_is_comptime) { if (!calling_convention_allows_zig_types(fn_type_id.cc)) { add_node_error(g, param_node, buf_sprintf("comptime parameter not allowed in function with calling convention '%s'", calling_convention_name(fn_type_id.cc))); return g->builtin_types.entry_invalid; } if (param_node->data.param_decl.type != nullptr) { ZigType *type_entry = analyze_type_expr(g, child_scope, param_node->data.param_decl.type); if (type_is_invalid(type_entry)) { return g->builtin_types.entry_invalid; } FnTypeParamInfo *param_info = &fn_type_id.param_info[fn_type_id.next_param_index]; param_info->type = type_entry; param_info->is_noalias = param_node->data.param_decl.is_noalias; fn_type_id.next_param_index += 1; } return get_generic_fn_type(g, &fn_type_id); } else if (param_is_var_args) { if (fn_type_id.cc == CallingConventionC) { fn_type_id.param_count = fn_type_id.next_param_index; continue; } else { add_node_error(g, param_node, buf_sprintf("var args only allowed in functions with C calling convention")); return g->builtin_types.entry_invalid; } } else if (param_node->data.param_decl.anytype_token != 0) { if (!calling_convention_allows_zig_types(fn_type_id.cc)) { add_node_error(g, param_node, buf_sprintf("parameter of type 'anytype' not allowed in function with calling convention '%s'", calling_convention_name(fn_type_id.cc))); return g->builtin_types.entry_invalid; } return get_generic_fn_type(g, &fn_type_id); } ZigType *type_entry = analyze_type_expr(g, child_scope, param_node->data.param_decl.type); if (type_is_invalid(type_entry)) { return g->builtin_types.entry_invalid; } if (!calling_convention_allows_zig_types(fn_type_id.cc)) { if ((err = type_resolve(g, type_entry, ResolveStatusZeroBitsKnown))) return g->builtin_types.entry_invalid; if (!type_has_bits(g, type_entry)) { add_node_error(g, param_node->data.param_decl.type, buf_sprintf("parameter of type '%s' has 0 bits; not allowed in function with calling convention '%s'", buf_ptr(&type_entry->name), calling_convention_name(fn_type_id.cc))); return g->builtin_types.entry_invalid; } } if (!calling_convention_allows_zig_types(fn_type_id.cc)) { bool ok_type; if ((err = type_allowed_in_extern(g, type_entry, ExternPositionFunctionParameter, &ok_type))) return g->builtin_types.entry_invalid; if (!ok_type) { add_node_error(g, param_node->data.param_decl.type, buf_sprintf("parameter of type '%s' not allowed in function with calling convention '%s'", buf_ptr(&type_entry->name), calling_convention_name(fn_type_id.cc))); return g->builtin_types.entry_invalid; } } if(!is_valid_param_type(type_entry)){ if(type_entry->id == ZigTypeIdOpaque){ add_node_error(g, param_node->data.param_decl.type, buf_sprintf("parameter of opaque type '%s' not allowed", buf_ptr(&type_entry->name))); } else { add_node_error(g, param_node->data.param_decl.type, buf_sprintf("parameter of type '%s' not allowed", buf_ptr(&type_entry->name))); } return g->builtin_types.entry_invalid; } switch (type_requires_comptime(g, type_entry)) { case ReqCompTimeNo: break; case ReqCompTimeYes: add_node_error(g, param_node->data.param_decl.type, buf_sprintf("parameter of type '%s' must be declared comptime", buf_ptr(&type_entry->name))); return g->builtin_types.entry_invalid; case ReqCompTimeInvalid: return g->builtin_types.entry_invalid; } FnTypeParamInfo *param_info = &fn_type_id.param_info[fn_type_id.next_param_index]; param_info->type = type_entry; param_info->is_noalias = param_node->data.param_decl.is_noalias; } if (fn_proto->align_expr != nullptr) { if (target_is_wasm(g->zig_target)) { // In Wasm, specifying alignment of function pointers makes little sense // since function pointers are in fact indices to a Wasm table, therefore // any alignment check on those is invalid. This can cause unexpected // behaviour when checking expected alignment with `@ptrToInt(fn_ptr)` // or similar. This commit proposes to make `align` expressions a // compile error when compiled to Wasm architecture. // // Some references: // [1] [Mozilla: WebAssembly Tables](https://developer.mozilla.org/en-US/docs/WebAssembly/Understanding_the_text_format#WebAssembly_tables) // [2] [Sunfishcode's Wasm Ref Manual](https://github.com/sunfishcode/wasm-reference-manual/blob/master/WebAssembly.md#indirect-call) add_node_error(g, fn_proto->align_expr, buf_sprintf("align(N) expr is not allowed on function prototypes in wasm32/wasm64")); return g->builtin_types.entry_invalid; } if (!analyze_const_align(g, child_scope, fn_proto->align_expr, &fn_type_id.alignment)) { return g->builtin_types.entry_invalid; } fn_entry->align_bytes = fn_type_id.alignment; } if (proto_node->data.fn_proto.callconv_expr != nullptr) { if ((err = emit_error_unless_callconv_allowed_for_target(g, proto_node->data.fn_proto.callconv_expr, cc))) return g->builtin_types.entry_invalid; } ZigType *specified_return_type = analyze_type_expr(g, child_scope, fn_proto->return_type); if (type_is_invalid(specified_return_type)) { fn_type_id.return_type = g->builtin_types.entry_invalid; return g->builtin_types.entry_invalid; } if(!is_valid_return_type(specified_return_type)){ ErrorMsg* msg = add_node_error(g, fn_proto->return_type, buf_sprintf("%s return type '%s' not allowed", type_id_name(specified_return_type->id), buf_ptr(&specified_return_type->name))); Tld *tld = find_decl(g, &fn_entry->fndef_scope->base, &specified_return_type->name); if (tld != nullptr) { add_error_note(g, msg, tld->source_node, buf_sprintf("type declared here")); } return g->builtin_types.entry_invalid; } if (fn_proto->auto_err_set) { ZigType *inferred_err_set_type = get_auto_err_set_type(g, fn_entry); if ((err = type_resolve(g, specified_return_type, ResolveStatusSizeKnown))) return g->builtin_types.entry_invalid; fn_type_id.return_type = get_error_union_type(g, inferred_err_set_type, specified_return_type); } else { fn_type_id.return_type = specified_return_type; } if (!calling_convention_allows_zig_types(fn_type_id.cc) && fn_type_id.return_type->id != ZigTypeIdVoid) { if ((err = type_resolve(g, fn_type_id.return_type, ResolveStatusSizeKnown))) return g->builtin_types.entry_invalid; bool ok_type; if ((err = type_allowed_in_extern(g, fn_type_id.return_type, ExternPositionFunctionReturn, &ok_type))) return g->builtin_types.entry_invalid; if (!ok_type) { add_node_error(g, fn_proto->return_type, buf_sprintf("return type '%s' not allowed in function with calling convention '%s'", buf_ptr(&fn_type_id.return_type->name), calling_convention_name(fn_type_id.cc))); return g->builtin_types.entry_invalid; } } switch (type_requires_comptime(g, fn_type_id.return_type)) { case ReqCompTimeInvalid: return g->builtin_types.entry_invalid; case ReqCompTimeYes: return get_generic_fn_type(g, &fn_type_id); case ReqCompTimeNo: break; } return get_fn_type(g, &fn_type_id); } bool is_valid_return_type(ZigType* type) { switch (type->id) { case ZigTypeIdInvalid: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdOpaque: return false; default: return true; } zig_unreachable(); } bool is_valid_param_type(ZigType* type) { switch (type->id) { case ZigTypeIdInvalid: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdOpaque: case ZigTypeIdUnreachable: return false; default: return true; } zig_unreachable(); } bool type_is_invalid(ZigType *type_entry) { switch (type_entry->id) { case ZigTypeIdInvalid: return true; case ZigTypeIdStruct: return type_entry->data.structure.resolve_status == ResolveStatusInvalid; case ZigTypeIdUnion: return type_entry->data.unionation.resolve_status == ResolveStatusInvalid; case ZigTypeIdEnum: return type_entry->data.enumeration.resolve_status == ResolveStatusInvalid; case ZigTypeIdFnFrame: return type_entry->data.frame.reported_loop_err; default: return false; } zig_unreachable(); } struct SrcField { const char *name; ZigType *ty; unsigned align; }; static ZigType *get_struct_type(CodeGen *g, const char *type_name, SrcField fields[], size_t field_count, unsigned min_abi_align) { ZigType *struct_type = new_type_table_entry(ZigTypeIdStruct); buf_init_from_str(&struct_type->name, type_name); struct_type->data.structure.src_field_count = field_count; struct_type->data.structure.gen_field_count = 0; struct_type->data.structure.resolve_status = ResolveStatusSizeKnown; struct_type->data.structure.fields = alloc_type_struct_fields(field_count); struct_type->data.structure.fields_by_name.init(field_count); size_t abi_align = min_abi_align; for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = struct_type->data.structure.fields[i]; field->name = buf_create_from_str(fields[i].name); field->type_entry = fields[i].ty; field->src_index = i; field->align = fields[i].align; if (type_has_bits(g, field->type_entry)) { assert(type_is_resolved(field->type_entry, ResolveStatusSizeKnown)); unsigned field_abi_align = max(field->align, field->type_entry->abi_align); if (field_abi_align > abi_align) { abi_align = field_abi_align; } } auto prev_entry = struct_type->data.structure.fields_by_name.put_unique(field->name, field); assert(prev_entry == nullptr); } size_t next_offset = 0; for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = struct_type->data.structure.fields[i]; if (!type_has_bits(g, field->type_entry)) continue; field->offset = next_offset; // find the next non-zero-byte field for offset calculations size_t next_src_field_index = i + 1; for (; next_src_field_index < field_count; next_src_field_index += 1) { if (type_has_bits(g, struct_type->data.structure.fields[next_src_field_index]->type_entry)) break; } size_t next_abi_align; if (next_src_field_index == field_count) { next_abi_align = abi_align; } else { next_abi_align = max(fields[next_src_field_index].align, struct_type->data.structure.fields[next_src_field_index]->type_entry->abi_align); } next_offset = next_field_offset(next_offset, abi_align, field->type_entry->abi_size, next_abi_align); } struct_type->abi_align = abi_align; struct_type->abi_size = next_offset; struct_type->size_in_bits = next_offset * 8; return struct_type; } static size_t get_store_size_bytes(size_t size_in_bits) { return (size_in_bits + 7) / 8; } static size_t get_abi_align_bytes(size_t size_in_bits, size_t pointer_size_bytes) { size_t store_size_bytes = get_store_size_bytes(size_in_bits); if (store_size_bytes >= pointer_size_bytes) return pointer_size_bytes; return round_to_next_power_of_2(store_size_bytes); } static size_t get_abi_size_bytes(size_t size_in_bits, size_t pointer_size_bytes) { size_t store_size_bytes = get_store_size_bytes(size_in_bits); size_t abi_align = get_abi_align_bytes(size_in_bits, pointer_size_bytes); return align_forward(store_size_bytes, abi_align); } ZigType *resolve_struct_field_type(CodeGen *g, TypeStructField *struct_field) { Error err; if (struct_field->type_entry == nullptr) { if ((err = ir_resolve_lazy(g, struct_field->decl_node, struct_field->type_val))) { return nullptr; } struct_field->type_entry = struct_field->type_val->data.x_type; } return struct_field->type_entry; } static Error resolve_struct_type(CodeGen *g, ZigType *struct_type) { assert(struct_type->id == ZigTypeIdStruct); Error err; if (struct_type->data.structure.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; if (struct_type->data.structure.resolve_status >= ResolveStatusSizeKnown) return ErrorNone; if ((err = resolve_struct_alignment(g, struct_type))) return err; AstNode *decl_node = struct_type->data.structure.decl_node; if (struct_type->data.structure.resolve_loop_flag_other) { if (struct_type->data.structure.resolve_status != ResolveStatusInvalid) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; add_node_error(g, decl_node, buf_sprintf("struct '%s' depends on itself", buf_ptr(&struct_type->name))); } return ErrorSemanticAnalyzeFail; } assert(struct_type->data.structure.fields || struct_type->data.structure.src_field_count == 0); size_t field_count = struct_type->data.structure.src_field_count; bool packed = (struct_type->data.structure.layout == ContainerLayoutPacked); struct_type->data.structure.resolve_loop_flag_other = true; uint32_t *host_int_bytes = packed ? heap::c_allocator.allocate<uint32_t>(struct_type->data.structure.gen_field_count) : nullptr; size_t packed_bits_offset = 0; size_t next_offset = 0; size_t first_packed_bits_offset_misalign = SIZE_MAX; size_t gen_field_index = 0; size_t size_in_bits = 0; size_t abi_align = struct_type->abi_align; // Calculate offsets for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = struct_type->data.structure.fields[i]; if (field->gen_index == SIZE_MAX) continue; field->gen_index = gen_field_index; field->offset = next_offset; if (packed) { ZigType *field_type = resolve_struct_field_type(g, field); if (field_type == nullptr) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if ((err = type_resolve(g, field->type_entry, ResolveStatusSizeKnown))) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return err; } if ((err = emit_error_unless_type_allowed_in_packed_struct(g, field->type_entry, field->decl_node))) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return err; } size_t field_size_in_bits = type_size_bits(g, field_type); size_t next_packed_bits_offset = packed_bits_offset + field_size_in_bits; size_in_bits += field_size_in_bits; if (first_packed_bits_offset_misalign != SIZE_MAX) { // this field is not byte-aligned; it is part of the previous field with a bit offset field->bit_offset_in_host = packed_bits_offset - first_packed_bits_offset_misalign; size_t full_bit_count = next_packed_bits_offset - first_packed_bits_offset_misalign; size_t full_abi_size = get_abi_size_bytes(full_bit_count, g->pointer_size_bytes); if (full_abi_size * 8 == full_bit_count) { // next field recovers ABI alignment host_int_bytes[gen_field_index] = full_abi_size; gen_field_index += 1; // TODO: https://github.com/ziglang/zig/issues/1512 next_offset = next_field_offset(next_offset, abi_align, full_abi_size, 1); size_in_bits = next_offset * 8; first_packed_bits_offset_misalign = SIZE_MAX; } } else if (get_abi_size_bytes(field_type->size_in_bits, g->pointer_size_bytes) * 8 != field_size_in_bits) { first_packed_bits_offset_misalign = packed_bits_offset; field->bit_offset_in_host = 0; } else { // This is a byte-aligned field (both start and end) in a packed struct. host_int_bytes[gen_field_index] = field_type->size_in_bits / 8; field->bit_offset_in_host = 0; gen_field_index += 1; // TODO: https://github.com/ziglang/zig/issues/1512 next_offset = next_field_offset(next_offset, abi_align, field_type->size_in_bits / 8, 1); size_in_bits = next_offset * 8; } packed_bits_offset = next_packed_bits_offset; } else { size_t field_abi_size; size_t field_size_in_bits; if ((err = type_val_resolve_abi_size(g, field->decl_node, field->type_val, &field_abi_size, &field_size_in_bits))) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return err; } gen_field_index += 1; size_t next_src_field_index = i + 1; for (; next_src_field_index < field_count; next_src_field_index += 1) { if (struct_type->data.structure.fields[next_src_field_index]->gen_index != SIZE_MAX) { break; } } size_t next_align = (next_src_field_index == field_count) ? abi_align : struct_type->data.structure.fields[next_src_field_index]->align; next_offset = next_field_offset(next_offset, abi_align, field_abi_size, next_align); size_in_bits = next_offset * 8; } } if (first_packed_bits_offset_misalign != SIZE_MAX) { size_t full_bit_count = packed_bits_offset - first_packed_bits_offset_misalign; size_t full_abi_size = get_abi_size_bytes(full_bit_count, g->pointer_size_bytes); next_offset = next_field_offset(next_offset, abi_align, full_abi_size, abi_align); host_int_bytes[gen_field_index] = full_abi_size; gen_field_index += 1; } struct_type->abi_size = next_offset; struct_type->size_in_bits = size_in_bits; struct_type->data.structure.resolve_status = ResolveStatusSizeKnown; struct_type->data.structure.gen_field_count = (uint32_t)gen_field_index; struct_type->data.structure.resolve_loop_flag_other = false; struct_type->data.structure.host_int_bytes = host_int_bytes; // Resolve types for fields for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = struct_type->data.structure.fields[i]; ZigType *field_type = resolve_struct_field_type(g, field); if (field_type == nullptr) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if ((err = type_resolve(g, field_type, ResolveStatusSizeKnown))) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return err; } if (struct_type->data.structure.layout == ContainerLayoutExtern) { bool ok_type; if ((err = type_allowed_in_extern(g, field_type, ExternPositionOther, &ok_type))) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (!ok_type) { add_node_error(g, field->decl_node, buf_sprintf("extern structs cannot contain fields of type '%s'", buf_ptr(&field_type->name))); struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } } } return ErrorNone; } static Error resolve_union_alignment(CodeGen *g, ZigType *union_type) { assert(union_type->id == ZigTypeIdUnion); Error err; if (union_type->data.unionation.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; if (union_type->data.unionation.resolve_status >= ResolveStatusAlignmentKnown) return ErrorNone; if ((err = resolve_union_zero_bits(g, union_type))) return err; if (union_type->data.unionation.resolve_status >= ResolveStatusAlignmentKnown) return ErrorNone; AstNode *decl_node = union_type->data.structure.decl_node; if (union_type->data.unionation.resolve_loop_flag_other) { if (union_type->data.unionation.resolve_status != ResolveStatusInvalid) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; add_node_error(g, decl_node, buf_sprintf("union '%s' depends on itself", buf_ptr(&union_type->name))); } return ErrorSemanticAnalyzeFail; } // set temporary flag union_type->data.unionation.resolve_loop_flag_other = true; TypeUnionField *most_aligned_union_member = nullptr; uint32_t field_count = union_type->data.unionation.src_field_count; bool packed = union_type->data.unionation.layout == ContainerLayoutPacked; for (uint32_t i = 0; i < field_count; i += 1) { TypeUnionField *field = &union_type->data.unionation.fields[i]; if (field->gen_index == UINT32_MAX) continue; AstNode *align_expr = nullptr; if (union_type->data.unionation.decl_node->type == NodeTypeContainerDecl) { align_expr = field->decl_node->data.struct_field.align_expr; } if (align_expr != nullptr) { if (!analyze_const_align(g, &union_type->data.unionation.decls_scope->base, align_expr, &field->align)) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } add_node_error(g, field->decl_node, buf_create_from_str("TODO implement field alignment syntax for unions. https://github.com/ziglang/zig/issues/3125")); } else if (packed) { field->align = 1; } else if (field->type_entry != nullptr) { if ((err = type_resolve(g, field->type_entry, ResolveStatusAlignmentKnown))) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return err; } field->align = field->type_entry->abi_align; } else { if ((err = type_val_resolve_abi_align(g, field->decl_node, field->type_val, &field->align))) { if (g->trace_err != nullptr) { g->trace_err = add_error_note(g, g->trace_err, field->decl_node, buf_create_from_str("while checking this field")); } union_type->data.unionation.resolve_status = ResolveStatusInvalid; return err; } if (union_type->data.unionation.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; } if (most_aligned_union_member == nullptr || field->align > most_aligned_union_member->align) { most_aligned_union_member = field; } } // unset temporary flag union_type->data.unionation.resolve_loop_flag_other = false; union_type->data.unionation.resolve_status = ResolveStatusAlignmentKnown; union_type->data.unionation.most_aligned_union_member = most_aligned_union_member; ZigType *tag_type = union_type->data.unionation.tag_type; if (tag_type != nullptr && type_has_bits(g, tag_type)) { if ((err = type_resolve(g, tag_type, ResolveStatusAlignmentKnown))) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (most_aligned_union_member == nullptr) { union_type->abi_align = tag_type->abi_align; union_type->data.unionation.gen_tag_index = SIZE_MAX; union_type->data.unionation.gen_union_index = SIZE_MAX; } else if (tag_type->abi_align > most_aligned_union_member->align) { union_type->abi_align = tag_type->abi_align; union_type->data.unionation.gen_tag_index = 0; union_type->data.unionation.gen_union_index = 1; } else { union_type->abi_align = most_aligned_union_member->align; union_type->data.unionation.gen_union_index = 0; union_type->data.unionation.gen_tag_index = 1; } } else { union_type->abi_align = most_aligned_union_member? most_aligned_union_member->align : 0; union_type->data.unionation.gen_union_index = SIZE_MAX; union_type->data.unionation.gen_tag_index = SIZE_MAX; } return ErrorNone; } ZigType *resolve_union_field_type(CodeGen *g, TypeUnionField *union_field) { Error err; if (union_field->type_entry == nullptr) { if ((err = ir_resolve_lazy(g, union_field->decl_node, union_field->type_val))) { return nullptr; } union_field->type_entry = union_field->type_val->data.x_type; } return union_field->type_entry; } static Error resolve_union_type(CodeGen *g, ZigType *union_type) { assert(union_type->id == ZigTypeIdUnion); Error err; if (union_type->data.unionation.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; if (union_type->data.unionation.resolve_status >= ResolveStatusSizeKnown) return ErrorNone; if ((err = resolve_union_alignment(g, union_type))) return err; AstNode *decl_node = union_type->data.unionation.decl_node; uint32_t field_count = union_type->data.unionation.src_field_count; TypeUnionField *most_aligned_union_member = union_type->data.unionation.most_aligned_union_member; assert(union_type->data.unionation.fields); size_t union_abi_size = 0; size_t union_size_in_bits = 0; if (union_type->data.unionation.resolve_loop_flag_other) { if (union_type->data.unionation.resolve_status != ResolveStatusInvalid) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; add_node_error(g, decl_node, buf_sprintf("union '%s' depends on itself", buf_ptr(&union_type->name))); } return ErrorSemanticAnalyzeFail; } // set temporary flag union_type->data.unionation.resolve_loop_flag_other = true; const bool is_packed = union_type->data.unionation.layout == ContainerLayoutPacked; for (uint32_t i = 0; i < field_count; i += 1) { TypeUnionField *union_field = &union_type->data.unionation.fields[i]; ZigType *field_type = resolve_union_field_type(g, union_field); if (field_type == nullptr) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if ((err = type_resolve(g, field_type, ResolveStatusSizeKnown))) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (is_packed) { if ((err = emit_error_unless_type_allowed_in_packed_union(g, field_type, union_field->decl_node))) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return err; } } if (type_is_invalid(union_type)) return ErrorSemanticAnalyzeFail; if (!type_has_bits(g, field_type)) continue; union_abi_size = max(union_abi_size, field_type->abi_size); union_size_in_bits = max(union_size_in_bits, field_type->size_in_bits); } // The union itself for now has to be treated as being independently aligned. // See https://github.com/ziglang/zig/issues/2166. if (most_aligned_union_member != nullptr) { union_abi_size = align_forward(union_abi_size, most_aligned_union_member->align); } // unset temporary flag union_type->data.unionation.resolve_loop_flag_other = false; union_type->data.unionation.resolve_status = ResolveStatusSizeKnown; union_type->data.unionation.union_abi_size = union_abi_size; ZigType *tag_type = union_type->data.unionation.tag_type; if (tag_type != nullptr && type_has_bits(g, tag_type)) { if ((err = type_resolve(g, tag_type, ResolveStatusSizeKnown))) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (most_aligned_union_member == nullptr) { union_type->abi_size = tag_type->abi_size; union_type->size_in_bits = tag_type->size_in_bits; } else { size_t field_sizes[2]; size_t field_aligns[2]; field_sizes[union_type->data.unionation.gen_tag_index] = tag_type->abi_size; field_aligns[union_type->data.unionation.gen_tag_index] = tag_type->abi_align; field_sizes[union_type->data.unionation.gen_union_index] = union_abi_size; field_aligns[union_type->data.unionation.gen_union_index] = most_aligned_union_member->align; size_t field2_offset = next_field_offset(0, union_type->abi_align, field_sizes[0], field_aligns[1]); union_type->abi_size = next_field_offset(field2_offset, union_type->abi_align, field_sizes[1], union_type->abi_align); union_type->size_in_bits = union_type->abi_size * 8; } } else { union_type->abi_size = union_abi_size; union_type->size_in_bits = union_size_in_bits; } return ErrorNone; } static Error type_is_valid_extern_enum_tag(CodeGen *g, ZigType *ty, bool *result) { // Only integer types are allowed by the C ABI if(ty->id != ZigTypeIdInt) { *result = false; return ErrorNone; } // According to the ANSI C standard the enumeration type should be either a // signed char, a signed integer or an unsigned one. But GCC/Clang allow // other integral types as a compiler extension so let's accomodate them // aswell. return type_allowed_in_extern(g, ty, ExternPositionOther, result); } static Error resolve_enum_zero_bits(CodeGen *g, ZigType *enum_type) { Error err; assert(enum_type->id == ZigTypeIdEnum); if (enum_type->data.enumeration.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; if (enum_type->data.enumeration.resolve_status >= ResolveStatusZeroBitsKnown) return ErrorNone; AstNode *decl_node = enum_type->data.enumeration.decl_node; if (enum_type->data.enumeration.resolve_loop_flag) { if (enum_type->data.enumeration.resolve_status != ResolveStatusInvalid) { enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; add_node_error(g, decl_node, buf_sprintf("enum '%s' depends on itself", buf_ptr(&enum_type->name))); } return ErrorSemanticAnalyzeFail; } enum_type->data.enumeration.resolve_loop_flag = true; uint32_t field_count; if (decl_node->type == NodeTypeContainerDecl) { assert(!enum_type->data.enumeration.fields); field_count = (uint32_t)decl_node->data.container_decl.fields.length; } else { field_count = enum_type->data.enumeration.src_field_count + enum_type->data.enumeration.non_exhaustive; } if (field_count == 0) { add_node_error(g, decl_node, buf_sprintf("enums must have 1 or more fields")); enum_type->data.enumeration.src_field_count = field_count; enum_type->data.enumeration.fields = nullptr; enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } Scope *scope = &enum_type->data.enumeration.decls_scope->base; ZigType *tag_int_type; if (enum_type->data.enumeration.layout == ContainerLayoutExtern) { tag_int_type = get_c_int_type(g, CIntTypeInt); } else { tag_int_type = get_smallest_unsigned_int_type(g, field_count - 1); } enum_type->size_in_bits = tag_int_type->size_in_bits; enum_type->abi_size = tag_int_type->abi_size; enum_type->abi_align = tag_int_type->abi_align; ZigType *wanted_tag_int_type = nullptr; if (decl_node->type == NodeTypeContainerDecl) { if (decl_node->data.container_decl.init_arg_expr != nullptr) { wanted_tag_int_type = analyze_type_expr(g, scope, decl_node->data.container_decl.init_arg_expr); enum_type->data.enumeration.has_explicit_tag_type = true; } } else { wanted_tag_int_type = enum_type->data.enumeration.tag_int_type; enum_type->data.enumeration.has_explicit_tag_type = true; } if (wanted_tag_int_type != nullptr) { if (type_is_invalid(wanted_tag_int_type)) { enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; } else if (wanted_tag_int_type->id != ZigTypeIdInt && wanted_tag_int_type->id != ZigTypeIdComptimeInt) { enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; add_node_error(g, decl_node->data.container_decl.init_arg_expr, buf_sprintf("expected integer, found '%s'", buf_ptr(&wanted_tag_int_type->name))); } else { if (enum_type->data.enumeration.layout == ContainerLayoutExtern) { bool ok_type; if ((err = type_is_valid_extern_enum_tag(g, wanted_tag_int_type, &ok_type))) { enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; return err; } if (!ok_type) { enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; ErrorMsg *msg = add_node_error(g, decl_node->data.container_decl.init_arg_expr, buf_sprintf("'%s' is not a valid tag type for an extern enum", buf_ptr(&wanted_tag_int_type->name))); add_error_note(g, msg, decl_node->data.container_decl.init_arg_expr, buf_sprintf("any integral type of size 8, 16, 32, 64 or 128 bit is valid")); return ErrorSemanticAnalyzeFail; } } tag_int_type = wanted_tag_int_type; } } enum_type->data.enumeration.tag_int_type = tag_int_type; enum_type->size_in_bits = tag_int_type->size_in_bits; enum_type->abi_size = tag_int_type->abi_size; enum_type->abi_align = tag_int_type->abi_align; BigInt bi_one; bigint_init_unsigned(&bi_one, 1); if (decl_node->type == NodeTypeContainerDecl) { AstNode *last_field_node = decl_node->data.container_decl.fields.at(field_count - 1); if (buf_eql_str(last_field_node->data.struct_field.name, "_")) { if (last_field_node->data.struct_field.value != nullptr) { add_node_error(g, last_field_node, buf_sprintf("value assigned to '_' field of non-exhaustive enum")); enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; } if (decl_node->data.container_decl.init_arg_expr == nullptr) { add_node_error(g, decl_node, buf_sprintf("non-exhaustive enum must specify size")); enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; } enum_type->data.enumeration.non_exhaustive = true; } else { enum_type->data.enumeration.non_exhaustive = false; } } if (enum_type->data.enumeration.non_exhaustive) { field_count -= 1; if (field_count > 1 && log2_u64(field_count) == enum_type->size_in_bits) { add_node_error(g, decl_node, buf_sprintf("non-exhaustive enum specifies every value")); enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; } } if (decl_node->type == NodeTypeContainerDecl) { enum_type->data.enumeration.src_field_count = field_count; enum_type->data.enumeration.fields = heap::c_allocator.allocate<TypeEnumField>(field_count); enum_type->data.enumeration.fields_by_name.init(field_count); HashMap<BigInt, AstNode *, bigint_hash, bigint_eql> occupied_tag_values = {}; occupied_tag_values.init(field_count); TypeEnumField *last_enum_field = nullptr; for (uint32_t field_i = 0; field_i < field_count; field_i += 1) { AstNode *field_node = decl_node->data.container_decl.fields.at(field_i); TypeEnumField *type_enum_field = &enum_type->data.enumeration.fields[field_i]; type_enum_field->name = field_node->data.struct_field.name; type_enum_field->decl_index = field_i; type_enum_field->decl_node = field_node; if (field_node->data.struct_field.type != nullptr) { ErrorMsg *msg = add_node_error(g, field_node->data.struct_field.type, buf_sprintf("structs and unions, not enums, support field types")); add_error_note(g, msg, decl_node, buf_sprintf("consider 'union(enum)' here")); } else if (field_node->data.struct_field.align_expr != nullptr) { ErrorMsg *msg = add_node_error(g, field_node->data.struct_field.align_expr, buf_sprintf("structs and unions, not enums, support field alignment")); add_error_note(g, msg, decl_node, buf_sprintf("consider 'union(enum)' here")); } if (buf_eql_str(type_enum_field->name, "_")) { add_node_error(g, field_node, buf_sprintf("'_' field of non-exhaustive enum must be last")); enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; } auto field_entry = enum_type->data.enumeration.fields_by_name.put_unique(type_enum_field->name, type_enum_field); if (field_entry != nullptr) { ErrorMsg *msg = add_node_error(g, field_node, buf_sprintf("duplicate enum field: '%s'", buf_ptr(type_enum_field->name))); add_error_note(g, msg, field_entry->value->decl_node, buf_sprintf("other field here")); enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; continue; } AstNode *tag_value = field_node->data.struct_field.value; if (tag_value != nullptr) { // A user-specified value is available ZigValue *result = analyze_const_value(g, scope, tag_value, tag_int_type, nullptr, UndefBad); if (type_is_invalid(result->type)) { enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; continue; } assert(result->special != ConstValSpecialRuntime); assert(result->type->id == ZigTypeIdInt || result->type->id == ZigTypeIdComptimeInt); bigint_init_bigint(&type_enum_field->value, &result->data.x_bigint); } else { // No value was explicitly specified: allocate the last value + 1 // or, if this is the first element, zero if (last_enum_field != nullptr) { bigint_add(&type_enum_field->value, &last_enum_field->value, &bi_one); } else { bigint_init_unsigned(&type_enum_field->value, 0); } // Make sure we can represent this number with tag_int_type if (!bigint_fits_in_bits(&type_enum_field->value, tag_int_type->size_in_bits, tag_int_type->data.integral.is_signed)) { enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; Buf *val_buf = buf_alloc(); bigint_append_buf(val_buf, &type_enum_field->value, 10); add_node_error(g, field_node, buf_sprintf("enumeration value %s too large for type '%s'", buf_ptr(val_buf), buf_ptr(&tag_int_type->name))); break; } } // Make sure the value is unique auto entry = occupied_tag_values.put_unique(type_enum_field->value, field_node); if (entry != nullptr && enum_type->data.enumeration.layout != ContainerLayoutExtern) { enum_type->data.enumeration.resolve_status = ResolveStatusInvalid; Buf *val_buf = buf_alloc(); bigint_append_buf(val_buf, &type_enum_field->value, 10); ErrorMsg *msg = add_node_error(g, field_node, buf_sprintf("enum tag value %s already taken", buf_ptr(val_buf))); add_error_note(g, msg, entry->value, buf_sprintf("other occurrence here")); } last_enum_field = type_enum_field; } occupied_tag_values.deinit(); } if (enum_type->data.enumeration.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; enum_type->data.enumeration.resolve_loop_flag = false; enum_type->data.enumeration.resolve_status = ResolveStatusSizeKnown; return ErrorNone; } static Error resolve_struct_zero_bits(CodeGen *g, ZigType *struct_type) { assert(struct_type->id == ZigTypeIdStruct); Error err; if (struct_type->data.structure.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; if (struct_type->data.structure.resolve_status >= ResolveStatusZeroBitsKnown) return ErrorNone; AstNode *decl_node = struct_type->data.structure.decl_node; if (struct_type->data.structure.resolve_loop_flag_zero_bits) { if (struct_type->data.structure.resolve_status != ResolveStatusInvalid) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; add_node_error(g, decl_node, buf_sprintf("struct '%s' depends on itself", buf_ptr(&struct_type->name))); } return ErrorSemanticAnalyzeFail; } struct_type->data.structure.resolve_loop_flag_zero_bits = true; size_t field_count; if (decl_node->type == NodeTypeContainerDecl) { field_count = decl_node->data.container_decl.fields.length; struct_type->data.structure.src_field_count = (uint32_t)field_count; src_assert(struct_type->data.structure.fields == nullptr, decl_node); struct_type->data.structure.fields = alloc_type_struct_fields(field_count); } else if (is_anon_container(struct_type) || struct_type->data.structure.created_by_at_type) { field_count = struct_type->data.structure.src_field_count; src_assert(field_count == 0 || struct_type->data.structure.fields != nullptr, decl_node); } else zig_unreachable(); struct_type->data.structure.fields_by_name.init(field_count); Scope *scope = &struct_type->data.structure.decls_scope->base; size_t gen_field_index = 0; for (size_t i = 0; i < field_count; i += 1) { TypeStructField *type_struct_field = struct_type->data.structure.fields[i]; AstNode *field_node; if (decl_node->type == NodeTypeContainerDecl) { field_node = decl_node->data.container_decl.fields.at(i); type_struct_field->name = field_node->data.struct_field.name; type_struct_field->decl_node = field_node; if (field_node->data.struct_field.comptime_token != 0) { if (field_node->data.struct_field.value == nullptr) { add_token_error(g, field_node->owner, field_node->data.struct_field.comptime_token, buf_sprintf("comptime struct field missing initialization value")); struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } type_struct_field->is_comptime = true; } if (field_node->data.struct_field.type == nullptr) { add_node_error(g, field_node, buf_sprintf("struct field missing type")); struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } } else if (is_anon_container(struct_type) || struct_type->data.structure.created_by_at_type) { field_node = type_struct_field->decl_node; src_assert(type_struct_field->type_entry != nullptr, field_node); } else zig_unreachable(); auto field_entry = struct_type->data.structure.fields_by_name.put_unique(type_struct_field->name, type_struct_field); if (field_entry != nullptr) { ErrorMsg *msg = add_node_error(g, field_node, buf_sprintf("duplicate struct field: '%s'", buf_ptr(type_struct_field->name))); add_error_note(g, msg, field_entry->value->decl_node, buf_sprintf("other field here")); struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } ZigValue *field_type_val; if (decl_node->type == NodeTypeContainerDecl) { field_type_val = analyze_const_value(g, scope, field_node->data.struct_field.type, g->builtin_types.entry_type, nullptr, LazyOkNoUndef); if (type_is_invalid(field_type_val->type)) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } assert(field_type_val->special != ConstValSpecialRuntime); type_struct_field->type_val = field_type_val; if (struct_type->data.structure.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; } else if (is_anon_container(struct_type) || struct_type->data.structure.created_by_at_type) { field_type_val = type_struct_field->type_val; } else zig_unreachable(); bool field_is_opaque_type; if ((err = type_val_resolve_is_opaque_type(g, field_type_val, &field_is_opaque_type))) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (field_is_opaque_type) { add_node_error(g, field_node, buf_sprintf("opaque types have unknown size and therefore cannot be directly embedded in structs")); struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } type_struct_field->src_index = i; type_struct_field->gen_index = SIZE_MAX; if (type_struct_field->is_comptime) continue; switch (type_val_resolve_requires_comptime(g, field_type_val)) { case ReqCompTimeYes: struct_type->data.structure.requires_comptime = true; break; case ReqCompTimeInvalid: if (g->trace_err != nullptr) { g->trace_err = add_error_note(g, g->trace_err, field_node, buf_create_from_str("while checking this field")); } struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; case ReqCompTimeNo: break; } bool field_is_zero_bits; if ((err = type_val_resolve_zero_bits(g, field_type_val, struct_type, nullptr, &field_is_zero_bits))) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (field_is_zero_bits) continue; type_struct_field->gen_index = gen_field_index; gen_field_index += 1; } struct_type->data.structure.resolve_loop_flag_zero_bits = false; struct_type->data.structure.gen_field_count = (uint32_t)gen_field_index; if (gen_field_index != 0) { struct_type->abi_size = SIZE_MAX; struct_type->size_in_bits = SIZE_MAX; } if (struct_type->data.structure.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; struct_type->data.structure.resolve_status = ResolveStatusZeroBitsKnown; return ErrorNone; } static Error resolve_struct_alignment(CodeGen *g, ZigType *struct_type) { assert(struct_type->id == ZigTypeIdStruct); Error err; if (struct_type->data.structure.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; if (struct_type->data.structure.resolve_status >= ResolveStatusAlignmentKnown) return ErrorNone; if ((err = resolve_struct_zero_bits(g, struct_type))) return err; if (struct_type->data.structure.resolve_status >= ResolveStatusAlignmentKnown) return ErrorNone; AstNode *decl_node = struct_type->data.structure.decl_node; if (struct_type->data.structure.resolve_loop_flag_other) { if (struct_type->data.structure.resolve_status != ResolveStatusInvalid) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; add_node_error(g, decl_node, buf_sprintf("struct '%s' depends on itself", buf_ptr(&struct_type->name))); } return ErrorSemanticAnalyzeFail; } struct_type->data.structure.resolve_loop_flag_other = true; size_t field_count = struct_type->data.structure.src_field_count; bool packed = struct_type->data.structure.layout == ContainerLayoutPacked; for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = struct_type->data.structure.fields[i]; if (field->gen_index == SIZE_MAX) continue; AstNode *align_expr = (field->decl_node->type == NodeTypeStructField) ? field->decl_node->data.struct_field.align_expr : nullptr; if (align_expr != nullptr) { if (!analyze_const_align(g, &struct_type->data.structure.decls_scope->base, align_expr, &field->align)) { struct_type->data.structure.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } } else if (packed) { field->align = 1; } else { if ((err = type_val_resolve_abi_align(g, field->decl_node, field->type_val, &field->align))) { if (g->trace_err != nullptr) { g->trace_err = add_error_note(g, g->trace_err, field->decl_node, buf_create_from_str("while checking this field")); } struct_type->data.structure.resolve_status = ResolveStatusInvalid; return err; } if (struct_type->data.structure.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; } if (field->align > struct_type->abi_align) { struct_type->abi_align = field->align; } } if (!type_has_bits(g, struct_type)) { assert(struct_type->abi_align == 0); } struct_type->data.structure.resolve_loop_flag_other = false; if (struct_type->data.structure.resolve_status == ResolveStatusInvalid) { return ErrorSemanticAnalyzeFail; } struct_type->data.structure.resolve_status = ResolveStatusAlignmentKnown; return ErrorNone; } static Error resolve_union_zero_bits(CodeGen *g, ZigType *union_type) { assert(union_type->id == ZigTypeIdUnion); Error err; if (union_type->data.unionation.resolve_status == ResolveStatusInvalid) return ErrorSemanticAnalyzeFail; if (union_type->data.unionation.resolve_status >= ResolveStatusZeroBitsKnown) return ErrorNone; AstNode *decl_node = union_type->data.unionation.decl_node; if (union_type->data.unionation.resolve_loop_flag_zero_bits) { if (union_type->data.unionation.resolve_status != ResolveStatusInvalid) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; add_node_error(g, decl_node, buf_sprintf("union '%s' depends on itself", buf_ptr(&union_type->name))); } return ErrorSemanticAnalyzeFail; } union_type->data.unionation.resolve_loop_flag_zero_bits = true; uint32_t field_count; if (decl_node->type == NodeTypeContainerDecl) { assert(union_type->data.unionation.fields == nullptr); field_count = (uint32_t)decl_node->data.container_decl.fields.length; union_type->data.unionation.src_field_count = field_count; union_type->data.unionation.fields = heap::c_allocator.allocate<TypeUnionField>(field_count); union_type->data.unionation.fields_by_name.init(field_count); } else { field_count = union_type->data.unionation.src_field_count; assert(field_count == 0 || union_type->data.unionation.fields != nullptr); } if (field_count == 0) { add_node_error(g, decl_node, buf_sprintf("unions must have 1 or more fields")); union_type->data.unionation.src_field_count = field_count; union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } Scope *scope = &union_type->data.unionation.decls_scope->base; HashMap<BigInt, AstNode *, bigint_hash, bigint_eql> occupied_tag_values = {}; bool is_auto_enum; // union(enum) or union(enum(expr)) bool is_explicit_enum; // union(expr) AstNode *enum_type_node; // expr in union(enum(expr)) or union(expr) if (decl_node->type == NodeTypeContainerDecl) { is_auto_enum = decl_node->data.container_decl.auto_enum; is_explicit_enum = decl_node->data.container_decl.init_arg_expr != nullptr; enum_type_node = decl_node->data.container_decl.init_arg_expr; } else { is_auto_enum = false; is_explicit_enum = union_type->data.unionation.tag_type != nullptr; enum_type_node = nullptr; } union_type->data.unionation.have_explicit_tag_type = is_auto_enum || is_explicit_enum; bool is_auto_layout = union_type->data.unionation.layout == ContainerLayoutAuto; bool want_safety = (field_count >= 2) && (is_auto_layout || is_explicit_enum) && !(g->build_mode == BuildModeFastRelease || g->build_mode == BuildModeSmallRelease); ZigType *tag_type; bool create_enum_type = is_auto_enum || (!is_explicit_enum && want_safety); bool *covered_enum_fields; bool *is_zero_bits = heap::c_allocator.allocate<bool>(field_count); if (create_enum_type) { occupied_tag_values.init(field_count); ZigType *tag_int_type; if (enum_type_node != nullptr) { tag_int_type = analyze_type_expr(g, scope, enum_type_node); if (type_is_invalid(tag_int_type)) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (tag_int_type->id != ZigTypeIdInt && tag_int_type->id != ZigTypeIdComptimeInt) { add_node_error(g, enum_type_node, buf_sprintf("expected integer tag type, found '%s'", buf_ptr(&tag_int_type->name))); union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (tag_int_type->id == ZigTypeIdInt) { BigInt bi; bigint_init_unsigned(&bi, field_count - 1); if (!bigint_fits_in_bits(&bi, tag_int_type->data.integral.bit_count, tag_int_type->data.integral.is_signed)) { ErrorMsg *msg = add_node_error(g, enum_type_node, buf_sprintf("specified integer tag type cannot represent every field")); add_error_note(g, msg, enum_type_node, buf_sprintf("type %s cannot fit values in range 0...%" PRIu32, buf_ptr(&tag_int_type->name), field_count - 1)); union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } } } else { tag_int_type = get_smallest_unsigned_int_type(g, field_count - 1); } tag_type = new_type_table_entry(ZigTypeIdEnum); buf_resize(&tag_type->name, 0); buf_appendf(&tag_type->name, "@typeInfo(%s).Union.tag_type.?", buf_ptr(&union_type->name)); tag_type->llvm_type = tag_int_type->llvm_type; tag_type->llvm_di_type = tag_int_type->llvm_di_type; tag_type->abi_size = tag_int_type->abi_size; tag_type->abi_align = tag_int_type->abi_align; tag_type->size_in_bits = tag_int_type->size_in_bits; tag_type->data.enumeration.tag_int_type = tag_int_type; tag_type->data.enumeration.resolve_status = ResolveStatusSizeKnown; tag_type->data.enumeration.decl_node = decl_node; tag_type->data.enumeration.layout = ContainerLayoutAuto; tag_type->data.enumeration.src_field_count = field_count; tag_type->data.enumeration.fields = heap::c_allocator.allocate<TypeEnumField>(field_count); tag_type->data.enumeration.fields_by_name.init(field_count); tag_type->data.enumeration.decls_scope = create_decls_scope( g, nullptr, nullptr, tag_type, get_scope_import(scope), &tag_type->name); } else if (enum_type_node != nullptr) { tag_type = analyze_type_expr(g, scope, enum_type_node); } else { if (decl_node->type == NodeTypeContainerDecl) { tag_type = nullptr; } else { tag_type = union_type->data.unionation.tag_type; } } if (tag_type != nullptr) { if (type_is_invalid(tag_type)) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (tag_type->id != ZigTypeIdEnum) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; add_node_error(g, enum_type_node != nullptr ? enum_type_node : decl_node, buf_sprintf("expected enum tag type, found '%s'", buf_ptr(&tag_type->name))); return ErrorSemanticAnalyzeFail; } if ((err = type_resolve(g, tag_type, ResolveStatusAlignmentKnown))) { assert(g->errors.length != 0); return err; } covered_enum_fields = heap::c_allocator.allocate<bool>(tag_type->data.enumeration.src_field_count); } union_type->data.unionation.tag_type = tag_type; for (uint32_t i = 0; i < field_count; i += 1) { TypeUnionField *union_field = &union_type->data.unionation.fields[i]; if (decl_node->type == NodeTypeContainerDecl) { AstNode *field_node = decl_node->data.container_decl.fields.at(i); union_field->name = field_node->data.struct_field.name; union_field->decl_node = field_node; union_field->gen_index = UINT32_MAX; is_zero_bits[i] = false; auto field_entry = union_type->data.unionation.fields_by_name.put_unique(union_field->name, union_field); if (field_entry != nullptr) { ErrorMsg *msg = add_node_error(g, union_field->decl_node, buf_sprintf("duplicate union field: '%s'", buf_ptr(union_field->name))); add_error_note(g, msg, field_entry->value->decl_node, buf_sprintf("other field here")); union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (field_node->data.struct_field.type == nullptr) { if (is_auto_enum || is_explicit_enum) { union_field->type_entry = g->builtin_types.entry_void; is_zero_bits[i] = true; } else { add_node_error(g, field_node, buf_sprintf("union field missing type")); union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } } else { ZigValue *field_type_val = analyze_const_value(g, scope, field_node->data.struct_field.type, g->builtin_types.entry_type, nullptr, LazyOkNoUndef); if (type_is_invalid(field_type_val->type)) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } assert(field_type_val->special != ConstValSpecialRuntime); union_field->type_val = field_type_val; } if (field_node->data.struct_field.value != nullptr && !is_auto_enum) { ErrorMsg *msg = add_node_error(g, field_node->data.struct_field.value, buf_create_from_str("untagged union field assignment")); add_error_note(g, msg, decl_node, buf_create_from_str("consider 'union(enum)' here")); } } if (union_field->type_val != nullptr) { bool field_is_opaque_type; if ((err = type_val_resolve_is_opaque_type(g, union_field->type_val, &field_is_opaque_type))) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (field_is_opaque_type) { add_node_error(g, union_field->decl_node, buf_create_from_str( "opaque types have unknown size and therefore cannot be directly embedded in unions")); union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } switch (type_val_resolve_requires_comptime(g, union_field->type_val)) { case ReqCompTimeInvalid: if (g->trace_err != nullptr) { g->trace_err = add_error_note(g, g->trace_err, union_field->decl_node, buf_create_from_str("while checking this field")); } union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; case ReqCompTimeYes: union_type->data.unionation.requires_comptime = true; break; case ReqCompTimeNo: break; } if ((err = type_val_resolve_zero_bits(g, union_field->type_val, union_type, nullptr, &is_zero_bits[i]))) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } } if (create_enum_type) { union_field->enum_field = &tag_type->data.enumeration.fields[i]; union_field->enum_field->name = union_field->name; union_field->enum_field->decl_index = i; union_field->enum_field->decl_node = union_field->decl_node; auto prev_entry = tag_type->data.enumeration.fields_by_name.put_unique(union_field->enum_field->name, union_field->enum_field); assert(prev_entry == nullptr); // caught by union de-duplicator above AstNode *tag_value = decl_node->type == NodeTypeContainerDecl ? union_field->decl_node->data.struct_field.value : nullptr; // In this first pass we resolve explicit tag values. // In a second pass we will fill in the unspecified ones. if (tag_value != nullptr) { ZigType *tag_int_type = tag_type->data.enumeration.tag_int_type; ZigValue *result = analyze_const_value(g, scope, tag_value, tag_int_type, nullptr, UndefBad); if (type_is_invalid(result->type)) { union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } assert(result->special != ConstValSpecialRuntime); assert(result->type->id == ZigTypeIdInt); auto entry = occupied_tag_values.put_unique(result->data.x_bigint, tag_value); if (entry == nullptr) { bigint_init_bigint(&union_field->enum_field->value, &result->data.x_bigint); } else { Buf *val_buf = buf_alloc(); bigint_append_buf(val_buf, &result->data.x_bigint, 10); ErrorMsg *msg = add_node_error(g, tag_value, buf_sprintf("enum tag value %s already taken", buf_ptr(val_buf))); add_error_note(g, msg, entry->value, buf_sprintf("other occurrence here")); union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } } } else if (tag_type != nullptr) { union_field->enum_field = find_enum_type_field(tag_type, union_field->name); if (union_field->enum_field == nullptr) { ErrorMsg *msg = add_node_error(g, union_field->decl_node, buf_sprintf("enum field not found: '%s'", buf_ptr(union_field->name))); add_error_note(g, msg, tag_type->data.enumeration.decl_node, buf_sprintf("enum declared here")); union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } covered_enum_fields[union_field->enum_field->decl_index] = true; } else { union_field->enum_field = heap::c_allocator.create<TypeEnumField>(); union_field->enum_field->name = union_field->name; union_field->enum_field->decl_index = i; bigint_init_unsigned(&union_field->enum_field->value, i); } assert(union_field->enum_field != nullptr); } uint32_t gen_field_index = 0; for (uint32_t i = 0; i < field_count; i += 1) { TypeUnionField *union_field = &union_type->data.unionation.fields[i]; if (!is_zero_bits[i]) { union_field->gen_index = gen_field_index; gen_field_index += 1; } } heap::c_allocator.deallocate(is_zero_bits, field_count); bool src_have_tag = is_auto_enum || is_explicit_enum; if (src_have_tag && union_type->data.unionation.layout != ContainerLayoutAuto) { const char *qual_str; switch (union_type->data.unionation.layout) { case ContainerLayoutAuto: zig_unreachable(); case ContainerLayoutPacked: qual_str = "packed"; break; case ContainerLayoutExtern: qual_str = "extern"; break; } AstNode *source_node = enum_type_node != nullptr ? enum_type_node : decl_node; add_node_error(g, source_node, buf_sprintf("%s union does not support enum tag type", qual_str)); union_type->data.unionation.resolve_status = ResolveStatusInvalid; return ErrorSemanticAnalyzeFail; } if (create_enum_type) { if (decl_node->type == NodeTypeContainerDecl) { // Now iterate again and populate the unspecified tag values uint32_t next_maybe_unoccupied_index = 0; for (uint32_t field_i = 0; field_i < field_count; field_i += 1) { AstNode *field_node = decl_node->data.container_decl.fields.at(field_i); TypeUnionField *union_field = &union_type->data.unionation.fields[field_i]; AstNode *tag_value = field_node->data.struct_field.value; if (tag_value == nullptr) { if (occupied_tag_values.size() == 0) { bigint_init_unsigned(&union_field->enum_field->value, next_maybe_unoccupied_index); next_maybe_unoccupied_index += 1; } else { BigInt proposed_value; for (;;) { bigint_init_unsigned(&proposed_value, next_maybe_unoccupied_index); next_maybe_unoccupied_index += 1; auto entry = occupied_tag_values.put_unique(proposed_value, field_node); if (entry != nullptr) { continue; } break; } bigint_init_bigint(&union_field->enum_field->value, &proposed_value); } } } } } else if (tag_type != nullptr) { for (uint32_t i = 0; i < tag_type->data.enumeration.src_field_count; i += 1) { TypeEnumField *enum_field = &tag_type->data.enumeration.fields[i]; if (!covered_enum_fields[i]) { ErrorMsg *msg = add_node_error(g, decl_node, buf_sprintf("enum field missing: '%s'", buf_ptr(enum_field->name))); if (decl_node->type == NodeTypeContainerDecl) { AstNode *enum_decl_node = tag_type->data.enumeration.decl_node; AstNode *field_node = enum_decl_node->data.container_decl.fields.at(i); add_error_note(g, msg, field_node, buf_sprintf("declared here")); } union_type->data.unionation.resolve_status = ResolveStatusInvalid; } } heap::c_allocator.deallocate(covered_enum_fields, tag_type->data.enumeration.src_field_count); } if (union_type->data.unionation.resolve_status == ResolveStatusInvalid) { return ErrorSemanticAnalyzeFail; } union_type->data.unionation.resolve_loop_flag_zero_bits = false; union_type->data.unionation.gen_field_count = gen_field_index; bool zero_bits = gen_field_index == 0 && (tag_type == nullptr || !type_has_bits(g, tag_type)); if (!zero_bits) { union_type->abi_size = SIZE_MAX; union_type->size_in_bits = SIZE_MAX; } union_type->data.unionation.resolve_status = ResolveStatusZeroBitsKnown; return ErrorNone; } static Error resolve_opaque_type(CodeGen *g, ZigType *opaque_type) { Error err = ErrorNone; AstNode *container_node = opaque_type->data.opaque.decl_node; if (container_node != nullptr) { assert(container_node->type == NodeTypeContainerDecl); AstNodeContainerDecl *container_decl = &container_node->data.container_decl; for (size_t i = 0; i < container_decl->fields.length; i++) { AstNode *field_node = container_decl->fields.items[i]; add_node_error(g, field_node, buf_create_from_str("opaque types cannot have fields")); err = ErrorSemanticAnalyzeFail; } } return err; } void append_namespace_qualification(CodeGen *g, Buf *buf, ZigType *container_type) { if (g->root_import == container_type || buf_len(&container_type->name) == 0) return; buf_append_buf(buf, &container_type->name); buf_append_char(buf, NAMESPACE_SEP_CHAR); } static void get_fully_qualified_decl_name(CodeGen *g, Buf *buf, Tld *tld, bool is_test) { buf_resize(buf, 0); Scope *scope = tld->parent_scope; while (scope->id != ScopeIdDecls) { scope = scope->parent; } ScopeDecls *decls_scope = reinterpret_cast<ScopeDecls *>(scope); append_namespace_qualification(g, buf, decls_scope->container_type); if (is_test) { buf_append_str(buf, "test \""); buf_append_buf(buf, tld->name); buf_append_char(buf, '"'); } else { buf_append_buf(buf, tld->name); } } static ZigFn *create_fn_raw(CodeGen *g, bool is_noinline) { ZigFn *fn_entry = heap::c_allocator.create<ZigFn>(); fn_entry->stage1_zir = heap::c_allocator.create<Stage1Zir>(); fn_entry->is_noinline = is_noinline; return fn_entry; } ZigFn *create_fn(CodeGen *g, AstNode *proto_node) { assert(proto_node->type == NodeTypeFnProto); AstNodeFnProto *fn_proto = &proto_node->data.fn_proto; ZigFn *fn_entry = create_fn_raw(g, fn_proto->fn_inline == FnInlineNever); fn_entry->proto_node = proto_node; fn_entry->body_node = (proto_node->data.fn_proto.fn_def_node == nullptr) ? nullptr : proto_node->data.fn_proto.fn_def_node->data.fn_def.body; fn_entry->analyzed_executable.source_node = fn_entry->body_node; return fn_entry; } ZigType *get_test_fn_type(CodeGen *g) { if (g->test_fn_type) return g->test_fn_type; FnTypeId fn_type_id = {0}; fn_type_id.return_type = get_error_union_type(g, g->builtin_types.entry_global_error_set, g->builtin_types.entry_void); g->test_fn_type = get_fn_type(g, &fn_type_id); return g->test_fn_type; } void add_var_export(CodeGen *g, ZigVar *var, const char *symbol_name, GlobalLinkageId linkage) { GlobalExport *global_export = var->export_list.add_one(); memset(global_export, 0, sizeof(GlobalExport)); buf_init_from_str(&global_export->name, symbol_name); global_export->linkage = linkage; } void add_fn_export(CodeGen *g, ZigFn *fn_table_entry, const char *symbol_name, GlobalLinkageId linkage, CallingConvention cc) { CallingConvention winapi_cc = g->zig_target->arch == ZigLLVM_x86 ? CallingConventionStdcall : CallingConventionC; if (cc == CallingConventionC && strcmp(symbol_name, "main") == 0 && g->link_libc) { g->stage1.have_c_main = true; } else if (cc == winapi_cc && g->zig_target->os == OsWindows) { if (strcmp(symbol_name, "WinMain") == 0) { g->stage1.have_winmain = true; } else if (strcmp(symbol_name, "wWinMain") == 0) { g->stage1.have_wwinmain = true; } else if (strcmp(symbol_name, "WinMainCRTStartup") == 0) { g->stage1.have_winmain_crt_startup = true; } else if (strcmp(symbol_name, "wWinMainCRTStartup") == 0) { g->stage1.have_wwinmain_crt_startup = true; } else if (strcmp(symbol_name, "DllMainCRTStartup") == 0) { g->stage1.have_dllmain_crt_startup = true; } } GlobalExport *fn_export = fn_table_entry->export_list.add_one(); memset(fn_export, 0, sizeof(GlobalExport)); buf_init_from_str(&fn_export->name, symbol_name); fn_export->linkage = linkage; } static void resolve_decl_fn(CodeGen *g, TldFn *tld_fn) { AstNode *source_node = tld_fn->base.source_node; if (source_node->type == NodeTypeFnProto) { AstNodeFnProto *fn_proto = &source_node->data.fn_proto; AstNode *fn_def_node = fn_proto->fn_def_node; ZigFn *fn_table_entry = create_fn(g, source_node); tld_fn->fn_entry = fn_table_entry; bool is_extern = (fn_table_entry->body_node == nullptr); if (fn_proto->is_export || is_extern) { buf_init_from_buf(&fn_table_entry->symbol_name, tld_fn->base.name); } else { get_fully_qualified_decl_name(g, &fn_table_entry->symbol_name, &tld_fn->base, false); } if (!is_extern) { fn_table_entry->fndef_scope = create_fndef_scope(g, fn_table_entry->body_node, tld_fn->base.parent_scope, fn_table_entry); for (size_t i = 0; i < fn_proto->params.length; i += 1) { AstNode *param_node = fn_proto->params.at(i); assert(param_node->type == NodeTypeParamDecl); if (param_node->data.param_decl.name == nullptr) { add_node_error(g, param_node, buf_sprintf("missing parameter name")); } } } else { fn_table_entry->inferred_async_node = inferred_async_none; g->external_symbol_names.put_unique(tld_fn->base.name, &tld_fn->base); } Scope *child_scope = fn_table_entry->fndef_scope ? &fn_table_entry->fndef_scope->base : tld_fn->base.parent_scope; CallingConvention cc; if (fn_proto->callconv_expr != nullptr) { if (fn_proto->fn_inline == FnInlineAlways) { add_node_error(g, fn_proto->callconv_expr, buf_sprintf("explicit callconv incompatible with inline keyword")); } ZigType *cc_enum_value = get_builtin_type(g, "CallingConvention"); ZigValue *result_val = analyze_const_value(g, child_scope, fn_proto->callconv_expr, cc_enum_value, nullptr, UndefBad); if (type_is_invalid(result_val->type)) { fn_table_entry->type_entry = g->builtin_types.entry_invalid; tld_fn->base.resolution = TldResolutionInvalid; return; } cc = (CallingConvention)bigint_as_u32(&result_val->data.x_enum_tag); } else { cc = cc_from_fn_proto(fn_proto); } if (fn_proto->section_expr != nullptr) { if (!analyze_const_string(g, child_scope, fn_proto->section_expr, &fn_table_entry->section_name)) { fn_table_entry->type_entry = g->builtin_types.entry_invalid; tld_fn->base.resolution = TldResolutionInvalid; return; } } fn_table_entry->type_entry = analyze_fn_type(g, source_node, child_scope, fn_table_entry, cc); if (type_is_invalid(fn_table_entry->type_entry)) { tld_fn->base.resolution = TldResolutionInvalid; return; } const CallingConvention fn_cc = fn_table_entry->type_entry->data.fn.fn_type_id.cc; if (fn_proto->is_export) { switch (fn_cc) { case CallingConventionAsync: add_node_error(g, fn_def_node, buf_sprintf("exported function cannot be async")); fn_table_entry->type_entry = g->builtin_types.entry_invalid; tld_fn->base.resolution = TldResolutionInvalid; return; case CallingConventionInline: add_node_error(g, fn_def_node, buf_sprintf("exported function cannot be inline")); fn_table_entry->type_entry = g->builtin_types.entry_invalid; tld_fn->base.resolution = TldResolutionInvalid; return; case CallingConventionC: case CallingConventionNaked: case CallingConventionInterrupt: case CallingConventionSignal: case CallingConventionStdcall: case CallingConventionFastcall: case CallingConventionVectorcall: case CallingConventionThiscall: case CallingConventionAPCS: case CallingConventionAAPCS: case CallingConventionAAPCSVFP: case CallingConventionSysV: add_fn_export(g, fn_table_entry, buf_ptr(&fn_table_entry->symbol_name), GlobalLinkageIdStrong, fn_cc); break; case CallingConventionUnspecified: // An exported function without a specific calling // convention defaults to C add_fn_export(g, fn_table_entry, buf_ptr(&fn_table_entry->symbol_name), GlobalLinkageIdStrong, CallingConventionC); break; } } if (!fn_table_entry->type_entry->data.fn.is_generic) { if (fn_def_node) g->fn_defs.append(fn_table_entry); } // if the calling convention implies that it cannot be async, we save that for later // and leave the value to be nullptr to indicate that we have not emitted possible // compile errors for improperly calling async functions. if (fn_cc == CallingConventionAsync) { fn_table_entry->inferred_async_node = fn_table_entry->proto_node; } } else if (source_node->type == NodeTypeTestDecl) { ZigFn *fn_table_entry = create_fn_raw(g, false); get_fully_qualified_decl_name(g, &fn_table_entry->symbol_name, &tld_fn->base, true); tld_fn->fn_entry = fn_table_entry; fn_table_entry->proto_node = source_node; fn_table_entry->fndef_scope = create_fndef_scope(g, source_node, tld_fn->base.parent_scope, fn_table_entry); fn_table_entry->type_entry = get_test_fn_type(g); fn_table_entry->body_node = source_node->data.test_decl.body; fn_table_entry->is_test = true; g->fn_defs.append(fn_table_entry); g->test_fns.append(fn_table_entry); } else { zig_unreachable(); } } static void resolve_decl_comptime(CodeGen *g, TldCompTime *tld_comptime) { assert(tld_comptime->base.source_node->type == NodeTypeCompTime); AstNode *expr_node = tld_comptime->base.source_node->data.comptime_expr.expr; analyze_const_value(g, tld_comptime->base.parent_scope, expr_node, g->builtin_types.entry_void, nullptr, UndefBad); } static void add_top_level_decl(CodeGen *g, ScopeDecls *decls_scope, Tld *tld) { bool is_export = false; if (tld->id == TldIdVar) { assert(tld->source_node->type == NodeTypeVariableDeclaration); is_export = tld->source_node->data.variable_declaration.is_export; } else if (tld->id == TldIdFn) { assert(tld->source_node->type == NodeTypeFnProto); is_export = tld->source_node->data.fn_proto.is_export; if (!tld->source_node->data.fn_proto.is_extern && tld->source_node->data.fn_proto.fn_def_node == nullptr) { add_node_error(g, tld->source_node, buf_sprintf("non-extern function has no body")); return; } if (!tld->source_node->data.fn_proto.is_extern && tld->source_node->data.fn_proto.is_var_args) { add_node_error(g, tld->source_node, buf_sprintf("non-extern function is variadic")); return; } } else if (tld->id == TldIdUsingNamespace) { g->resolve_queue.append(tld); } if (is_export) { g->resolve_queue.append(tld); auto entry = g->exported_symbol_names.put_unique(tld->name, tld); if (entry) { AstNode *other_source_node = entry->value->source_node; ErrorMsg *msg = add_node_error(g, tld->source_node, buf_sprintf("exported symbol collision: '%s'", buf_ptr(tld->name))); add_error_note(g, msg, other_source_node, buf_sprintf("other symbol here")); } } if (tld->name != nullptr) { auto entry = decls_scope->decl_table.put_unique(tld->name, tld); if (entry) { Tld *other_tld = entry->value; if (other_tld->id == TldIdVar) { ZigVar *var = reinterpret_cast<TldVar *>(other_tld)->var; if (var != nullptr && var->var_type != nullptr && type_is_invalid(var->var_type)) { return; // already reported compile error } } ErrorMsg *msg = add_node_error(g, tld->source_node, buf_sprintf("redefinition of '%s'", buf_ptr(tld->name))); add_error_note(g, msg, other_tld->source_node, buf_sprintf("previous definition here")); return; } } } static void preview_test_decl(CodeGen *g, AstNode *node, ScopeDecls *decls_scope) { assert(node->type == NodeTypeTestDecl); if (!g->is_test_build) return; ZigType *import = get_scope_import(&decls_scope->base); if (import->data.structure.root_struct->package != g->main_pkg) return; Buf *decl_name_buf = node->data.test_decl.name; Buf *test_name; if (decl_name_buf != nullptr) { test_name = g->test_name_prefix ? buf_sprintf("%s%s", buf_ptr(g->test_name_prefix), buf_ptr(decl_name_buf)) : decl_name_buf; if (g->test_filter != nullptr && strstr(buf_ptr(test_name), buf_ptr(g->test_filter)) == nullptr) { return; } } else { // Unnamed test blocks are always executed. test_name = buf_sprintf("%s", g->test_name_prefix ? buf_ptr(g->test_name_prefix) : ""); } TldFn *tld_fn = heap::c_allocator.create<TldFn>(); init_tld(&tld_fn->base, TldIdFn, test_name, VisibModPrivate, node, &decls_scope->base); g->resolve_queue.append(&tld_fn->base); } static void preview_comptime_decl(CodeGen *g, AstNode *node, ScopeDecls *decls_scope) { assert(node->type == NodeTypeCompTime); TldCompTime *tld_comptime = heap::c_allocator.create<TldCompTime>(); init_tld(&tld_comptime->base, TldIdCompTime, nullptr, VisibModPrivate, node, &decls_scope->base); g->resolve_queue.append(&tld_comptime->base); } void init_tld(Tld *tld, TldId id, Buf *name, VisibMod visib_mod, AstNode *source_node, Scope *parent_scope) { tld->id = id; tld->name = name; tld->visib_mod = visib_mod; tld->source_node = source_node; tld->import = source_node ? source_node->owner : nullptr; tld->parent_scope = parent_scope; } void update_compile_var(CodeGen *g, Buf *name, ZigValue *value) { ScopeDecls *builtin_scope = get_container_scope(g->compile_var_import); Tld *tld = find_container_decl(g, builtin_scope, name); assert(tld != nullptr); resolve_top_level_decl(g, tld, tld->source_node, false); assert(tld->id == TldIdVar && tld->resolution == TldResolutionOk); TldVar *tld_var = (TldVar *)tld; copy_const_val(g, tld_var->var->const_value, value); tld_var->var->var_type = value->type; tld_var->var->align_bytes = get_abi_alignment(g, value->type); } void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) { switch (node->type) { case NodeTypeFnDef: scan_decls(g, decls_scope, node->data.fn_def.fn_proto); break; case NodeTypeVariableDeclaration: { Buf *name = node->data.variable_declaration.symbol; VisibMod visib_mod = node->data.variable_declaration.visib_mod; TldVar *tld_var = heap::c_allocator.create<TldVar>(); init_tld(&tld_var->base, TldIdVar, name, visib_mod, node, &decls_scope->base); tld_var->extern_lib_name = node->data.variable_declaration.lib_name; add_top_level_decl(g, decls_scope, &tld_var->base); break; } case NodeTypeFnProto: { // if the name is missing, we immediately announce an error Buf *fn_name = node->data.fn_proto.name; if (fn_name == nullptr) { add_node_error(g, node, buf_sprintf("missing function name")); break; } VisibMod visib_mod = node->data.fn_proto.visib_mod; TldFn *tld_fn = heap::c_allocator.create<TldFn>(); init_tld(&tld_fn->base, TldIdFn, fn_name, visib_mod, node, &decls_scope->base); tld_fn->extern_lib_name = node->data.fn_proto.lib_name; add_top_level_decl(g, decls_scope, &tld_fn->base); break; } case NodeTypeUsingNamespace: { VisibMod visib_mod = node->data.using_namespace.visib_mod; TldUsingNamespace *tld_using_namespace = heap::c_allocator.create<TldUsingNamespace>(); init_tld(&tld_using_namespace->base, TldIdUsingNamespace, nullptr, visib_mod, node, &decls_scope->base); add_top_level_decl(g, decls_scope, &tld_using_namespace->base); decls_scope->use_decls.append(tld_using_namespace); break; } case NodeTypeTestDecl: preview_test_decl(g, node, decls_scope); break; case NodeTypeCompTime: preview_comptime_decl(g, node, decls_scope); break; case NodeTypeContainerDecl: case NodeTypeNoSuspend: case NodeTypeParamDecl: case NodeTypeReturnExpr: case NodeTypeDefer: case NodeTypeBlock: case NodeTypeGroupedExpr: case NodeTypeBinOpExpr: case NodeTypeCatchExpr: case NodeTypeFnCallExpr: case NodeTypeArrayAccessExpr: case NodeTypeSliceExpr: case NodeTypeFloatLiteral: case NodeTypeIntLiteral: case NodeTypeStringLiteral: case NodeTypeCharLiteral: case NodeTypeBoolLiteral: case NodeTypeNullLiteral: case NodeTypeUndefinedLiteral: case NodeTypeIdentifier: case NodeTypePrefixOpExpr: case NodeTypePointerType: case NodeTypeIfBoolExpr: case NodeTypeWhileExpr: case NodeTypeForExpr: case NodeTypeSwitchExpr: case NodeTypeSwitchProng: case NodeTypeSwitchRange: case NodeTypeBreak: case NodeTypeContinue: case NodeTypeUnreachable: case NodeTypeAsmExpr: case NodeTypeFieldAccessExpr: case NodeTypePtrDeref: case NodeTypeUnwrapOptional: case NodeTypeStructField: case NodeTypeContainerInitExpr: case NodeTypeStructValueField: case NodeTypeArrayType: case NodeTypeInferredArrayType: case NodeTypeErrorType: case NodeTypeIfErrorExpr: case NodeTypeIfOptional: case NodeTypeErrorSetDecl: case NodeTypeResume: case NodeTypeAwaitExpr: case NodeTypeSuspend: case NodeTypeEnumLiteral: case NodeTypeAnyFrameType: case NodeTypeErrorSetField: case NodeTypeAnyTypeField: zig_unreachable(); } } static Error resolve_decl_container(CodeGen *g, TldContainer *tld_container) { ZigType *type_entry = tld_container->type_entry; assert(type_entry); switch (type_entry->id) { case ZigTypeIdStruct: return resolve_struct_type(g, tld_container->type_entry); case ZigTypeIdEnum: return resolve_enum_zero_bits(g, tld_container->type_entry); case ZigTypeIdUnion: return resolve_union_type(g, tld_container->type_entry); case ZigTypeIdOpaque: return resolve_opaque_type(g, tld_container->type_entry); default: zig_unreachable(); } } ZigType *validate_var_type(CodeGen *g, AstNodeVariableDeclaration *source_node, ZigType *type_entry) { switch (type_entry->id) { case ZigTypeIdInvalid: return g->builtin_types.entry_invalid; case ZigTypeIdOpaque: if (source_node->is_extern) return type_entry; ZIG_FALLTHROUGH; case ZigTypeIdUnreachable: case ZigTypeIdUndefined: case ZigTypeIdNull: add_node_error(g, source_node->type, buf_sprintf("variable of type '%s' not allowed", buf_ptr(&type_entry->name))); return g->builtin_types.entry_invalid; case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdMetaType: case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdInt: case ZigTypeIdFloat: case ZigTypeIdPointer: case ZigTypeIdArray: case ZigTypeIdStruct: case ZigTypeIdOptional: case ZigTypeIdErrorUnion: case ZigTypeIdErrorSet: case ZigTypeIdEnum: case ZigTypeIdUnion: case ZigTypeIdFn: case ZigTypeIdBoundFn: case ZigTypeIdVector: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: return type_entry; } zig_unreachable(); } // Set name to nullptr to make the variable anonymous (not visible to programmer). // TODO merge with definition of add_local_var in ir.cpp ZigVar *add_variable(CodeGen *g, AstNode *source_node, Scope *parent_scope, Buf *name, bool is_const, ZigValue *const_value, Tld *src_tld, ZigType *var_type) { Error err; assert(const_value != nullptr); assert(var_type != nullptr); ZigVar *variable_entry = heap::c_allocator.create<ZigVar>(); variable_entry->const_value = const_value; variable_entry->var_type = var_type; variable_entry->parent_scope = parent_scope; variable_entry->shadowable = false; variable_entry->src_arg_index = SIZE_MAX; assert(name); variable_entry->name = strdup(buf_ptr(name)); if ((err = type_resolve(g, var_type, ResolveStatusAlignmentKnown))) { variable_entry->var_type = g->builtin_types.entry_invalid; } else { variable_entry->align_bytes = get_abi_alignment(g, var_type); } Scope *child_scope; if (source_node && source_node->type == NodeTypeParamDecl) { child_scope = create_var_scope(g, source_node, parent_scope, variable_entry); } else { // it's already in the decls table child_scope = parent_scope; } variable_entry->src_is_const = is_const; variable_entry->gen_is_const = is_const; variable_entry->decl_node = source_node; variable_entry->child_scope = child_scope; return variable_entry; } static void validate_export_var_type(CodeGen *g, ZigType* type, AstNode *source_node) { switch (type->id) { case ZigTypeIdMetaType: add_node_error(g, source_node, buf_sprintf("cannot export variable of type 'type'")); break; default: break; } } static void resolve_decl_var(CodeGen *g, TldVar *tld_var, bool allow_lazy) { AstNode *source_node = tld_var->base.source_node; AstNodeVariableDeclaration *var_decl = &source_node->data.variable_declaration; bool is_const = var_decl->is_const; bool is_extern = var_decl->is_extern; bool is_export = var_decl->is_export; bool is_thread_local = var_decl->threadlocal_tok != 0; ZigType *explicit_type = nullptr; if (var_decl->type) { if (tld_var->analyzing_type) { add_node_error(g, var_decl->type, buf_sprintf("type of '%s' depends on itself", buf_ptr(tld_var->base.name))); explicit_type = g->builtin_types.entry_invalid; } else { tld_var->analyzing_type = true; ZigType *proposed_type = analyze_type_expr(g, tld_var->base.parent_scope, var_decl->type); explicit_type = validate_var_type(g, var_decl, proposed_type); } } assert(!is_export || !is_extern); ZigValue *init_value = nullptr; // TODO more validation for types that can't be used for export/extern variables ZigType *implicit_type = nullptr; if (explicit_type != nullptr && type_is_invalid(explicit_type)) { implicit_type = explicit_type; } else if (var_decl->expr) { init_value = analyze_const_value(g, tld_var->base.parent_scope, var_decl->expr, explicit_type, var_decl->symbol, allow_lazy ? LazyOk : UndefOk); assert(init_value); implicit_type = init_value->type; if (implicit_type->id == ZigTypeIdUnreachable) { add_node_error(g, source_node, buf_sprintf("variable initialization is unreachable")); implicit_type = g->builtin_types.entry_invalid; } else if ((!is_const || is_extern) && (implicit_type->id == ZigTypeIdComptimeFloat || implicit_type->id == ZigTypeIdComptimeInt || implicit_type->id == ZigTypeIdEnumLiteral)) { add_node_error(g, source_node, buf_sprintf("unable to infer variable type")); implicit_type = g->builtin_types.entry_invalid; } else if (implicit_type->id == ZigTypeIdNull) { add_node_error(g, source_node, buf_sprintf("unable to infer variable type")); implicit_type = g->builtin_types.entry_invalid; } else if (implicit_type->id == ZigTypeIdMetaType && !is_const) { add_node_error(g, source_node, buf_sprintf("variable of type 'type' must be constant")); implicit_type = g->builtin_types.entry_invalid; } assert(implicit_type->id == ZigTypeIdInvalid || init_value->special != ConstValSpecialRuntime); } else if (!is_extern) { add_node_error(g, source_node, buf_sprintf("variables must be initialized")); implicit_type = g->builtin_types.entry_invalid; } else if (explicit_type == nullptr) { // extern variable without explicit type add_node_error(g, source_node, buf_sprintf("unable to infer variable type")); implicit_type = g->builtin_types.entry_invalid; } ZigType *type = explicit_type ? explicit_type : implicit_type; assert(type != nullptr); // should have been caught by the parser ZigValue *init_val = (init_value != nullptr) ? init_value : create_const_runtime(g, type); tld_var->var = add_variable(g, source_node, tld_var->base.parent_scope, var_decl->symbol, is_const, init_val, &tld_var->base, type); tld_var->var->is_thread_local = is_thread_local; if (implicit_type != nullptr && type_is_invalid(implicit_type)) { tld_var->var->var_type = g->builtin_types.entry_invalid; } if (var_decl->align_expr != nullptr) { if (!analyze_const_align(g, tld_var->base.parent_scope, var_decl->align_expr, &tld_var->var->align_bytes)) { tld_var->var->var_type = g->builtin_types.entry_invalid; } } if (var_decl->section_expr != nullptr) { if (!analyze_const_string(g, tld_var->base.parent_scope, var_decl->section_expr, &tld_var->var->section_name)) { tld_var->var->section_name = nullptr; } } if (is_thread_local && is_const) { add_node_error(g, source_node, buf_sprintf("threadlocal variable cannot be constant")); } if (is_export) { validate_export_var_type(g, type, source_node); add_var_export(g, tld_var->var, tld_var->var->name, GlobalLinkageIdStrong); } if (is_extern) { g->external_symbol_names.put_unique(tld_var->base.name, &tld_var->base); } g->global_vars.append(tld_var); } static void add_symbols_from_container(CodeGen *g, TldUsingNamespace *src_using_namespace, TldUsingNamespace *dst_using_namespace, ScopeDecls* dest_decls_scope) { if (src_using_namespace->base.resolution == TldResolutionUnresolved || src_using_namespace->base.resolution == TldResolutionResolving) { assert(src_using_namespace->base.parent_scope->id == ScopeIdDecls); ScopeDecls *src_decls_scope = (ScopeDecls *)src_using_namespace->base.parent_scope; preview_use_decl(g, src_using_namespace, src_decls_scope); if (src_using_namespace != dst_using_namespace) { resolve_use_decl(g, src_using_namespace, src_decls_scope); } } ZigValue *use_expr = src_using_namespace->using_namespace_value; if (type_is_invalid(use_expr->type)) { dest_decls_scope->any_imports_failed = true; return; } dst_using_namespace->base.resolution = TldResolutionOk; assert(use_expr->special != ConstValSpecialRuntime); // The source scope for the imported symbols ScopeDecls *src_scope = get_container_scope(use_expr->data.x_type); // The top-level container where the symbols are defined, it's used in the // loop below in order to exclude the ones coming from an import statement ZigType *src_import = get_scope_import(&src_scope->base); assert(src_import != nullptr); if (src_scope->any_imports_failed) { dest_decls_scope->any_imports_failed = true; } auto it = src_scope->decl_table.entry_iterator(); for (;;) { auto *entry = it.next(); if (!entry) break; Buf *target_tld_name = entry->key; Tld *target_tld = entry->value; if (target_tld->visib_mod == VisibModPrivate) { continue; } if (target_tld->import != src_import) { continue; } auto existing_entry = dest_decls_scope->decl_table.put_unique(target_tld_name, target_tld); if (existing_entry) { Tld *existing_decl = existing_entry->value; if (existing_decl != target_tld) { ErrorMsg *msg = add_node_error(g, dst_using_namespace->base.source_node, buf_sprintf("import of '%s' overrides existing definition", buf_ptr(target_tld_name))); add_error_note(g, msg, existing_decl->source_node, buf_sprintf("previous definition here")); add_error_note(g, msg, target_tld->source_node, buf_sprintf("imported definition here")); } } } for (size_t i = 0; i < src_scope->use_decls.length; i += 1) { TldUsingNamespace *tld_using_namespace = src_scope->use_decls.at(i); if (tld_using_namespace->base.visib_mod != VisibModPrivate) add_symbols_from_container(g, tld_using_namespace, dst_using_namespace, dest_decls_scope); } } static void resolve_use_decl(CodeGen *g, TldUsingNamespace *tld_using_namespace, ScopeDecls *dest_decls_scope) { if (tld_using_namespace->base.resolution == TldResolutionOk || tld_using_namespace->base.resolution == TldResolutionInvalid) { return; } add_symbols_from_container(g, tld_using_namespace, tld_using_namespace, dest_decls_scope); } static void preview_use_decl(CodeGen *g, TldUsingNamespace *using_namespace, ScopeDecls *dest_decls_scope) { if (using_namespace->base.resolution == TldResolutionOk || using_namespace->base.resolution == TldResolutionInvalid || using_namespace->using_namespace_value != nullptr) { return; } using_namespace->base.resolution = TldResolutionResolving; assert(using_namespace->base.source_node->type == NodeTypeUsingNamespace); ZigValue *result = analyze_const_value(g, &dest_decls_scope->base, using_namespace->base.source_node->data.using_namespace.expr, g->builtin_types.entry_type, nullptr, UndefBad); using_namespace->using_namespace_value = result; if (type_is_invalid(result->type)) { dest_decls_scope->any_imports_failed = true; using_namespace->base.resolution = TldResolutionInvalid; using_namespace->using_namespace_value = g->invalid_inst_gen->value; return; } if (!is_container(result->data.x_type)) { add_node_error(g, using_namespace->base.source_node, buf_sprintf("expected struct, enum, or union; found '%s'", buf_ptr(&result->data.x_type->name))); dest_decls_scope->any_imports_failed = true; using_namespace->base.resolution = TldResolutionInvalid; using_namespace->using_namespace_value = g->invalid_inst_gen->value; return; } } void resolve_top_level_decl(CodeGen *g, Tld *tld, AstNode *source_node, bool allow_lazy) { bool want_resolve_lazy = tld->resolution == TldResolutionOkLazy && !allow_lazy; if (tld->resolution != TldResolutionUnresolved && !want_resolve_lazy) return; tld->resolution = TldResolutionResolving; update_progress_display(g); switch (tld->id) { case TldIdVar: { TldVar *tld_var = (TldVar *)tld; if (want_resolve_lazy) { ir_resolve_lazy(g, source_node, tld_var->var->const_value); } else { resolve_decl_var(g, tld_var, allow_lazy); } tld->resolution = allow_lazy ? TldResolutionOkLazy : TldResolutionOk; break; } case TldIdFn: { TldFn *tld_fn = (TldFn *)tld; resolve_decl_fn(g, tld_fn); tld->resolution = TldResolutionOk; break; } case TldIdContainer: { TldContainer *tld_container = (TldContainer *)tld; resolve_decl_container(g, tld_container); tld->resolution = TldResolutionOk; break; } case TldIdCompTime: { TldCompTime *tld_comptime = (TldCompTime *)tld; resolve_decl_comptime(g, tld_comptime); tld->resolution = TldResolutionOk; break; } case TldIdUsingNamespace: { TldUsingNamespace *tld_using_namespace = (TldUsingNamespace *)tld; assert(tld_using_namespace->base.parent_scope->id == ScopeIdDecls); ScopeDecls *dest_decls_scope = (ScopeDecls *)tld_using_namespace->base.parent_scope; preview_use_decl(g, tld_using_namespace, dest_decls_scope); resolve_use_decl(g, tld_using_namespace, dest_decls_scope); tld->resolution = TldResolutionOk; break; } } } void resolve_container_usingnamespace_decls(CodeGen *g, ScopeDecls *decls_scope) { // resolve all the using_namespace decls for (size_t i = 0; i < decls_scope->use_decls.length; i += 1) { TldUsingNamespace *tld_using_namespace = decls_scope->use_decls.at(i); if (tld_using_namespace->base.resolution == TldResolutionUnresolved) { preview_use_decl(g, tld_using_namespace, decls_scope); resolve_use_decl(g, tld_using_namespace, decls_scope); } } } Tld *find_container_decl(CodeGen *g, ScopeDecls *decls_scope, Buf *name) { resolve_container_usingnamespace_decls(g, decls_scope); auto entry = decls_scope->decl_table.maybe_get(name); return (entry == nullptr) ? nullptr : entry->value; } Tld *find_decl(CodeGen *g, Scope *scope, Buf *name) { while (scope) { if (scope->id == ScopeIdDecls) { ScopeDecls *decls_scope = (ScopeDecls *)scope; Tld *result = find_container_decl(g, decls_scope, name); if (result != nullptr) return result; } scope = scope->parent; } return nullptr; } ZigVar *find_variable(CodeGen *g, Scope *scope, Buf *name, ScopeFnDef **crossed_fndef_scope) { ScopeFnDef *my_crossed_fndef_scope = nullptr; while (scope) { if (scope->id == ScopeIdVarDecl) { ScopeVarDecl *var_scope = (ScopeVarDecl *)scope; if (buf_eql_str(name, var_scope->var->name)) { if (crossed_fndef_scope != nullptr) *crossed_fndef_scope = my_crossed_fndef_scope; return var_scope->var; } } else if (scope->id == ScopeIdDecls) { ScopeDecls *decls_scope = (ScopeDecls *)scope; auto entry = decls_scope->decl_table.maybe_get(name); if (entry) { Tld *tld = entry->value; if (tld->id == TldIdVar) { TldVar *tld_var = (TldVar *)tld; if (tld_var->var) { if (crossed_fndef_scope != nullptr) *crossed_fndef_scope = nullptr; return tld_var->var; } } } } else if (scope->id == ScopeIdFnDef) { my_crossed_fndef_scope = (ScopeFnDef *)scope; } scope = scope->parent; } return nullptr; } ZigFn *scope_fn_entry(Scope *scope) { while (scope) { if (scope->id == ScopeIdFnDef) { ScopeFnDef *fn_scope = (ScopeFnDef *)scope; return fn_scope->fn_entry; } scope = scope->parent; } return nullptr; } ZigPackage *scope_package(Scope *scope) { ZigType *import = get_scope_import(scope); assert(is_top_level_struct(import)); return import->data.structure.root_struct->package; } TypeEnumField *find_enum_type_field(ZigType *enum_type, Buf *name) { assert(enum_type->id == ZigTypeIdEnum); if (enum_type->data.enumeration.src_field_count == 0) return nullptr; auto entry = enum_type->data.enumeration.fields_by_name.maybe_get(name); if (entry == nullptr) return nullptr; return entry->value; } TypeStructField *find_struct_type_field(ZigType *type_entry, Buf *name) { assert(type_entry->id == ZigTypeIdStruct); if (type_entry->data.structure.resolve_status == ResolveStatusBeingInferred) { for (size_t i = 0; i < type_entry->data.structure.src_field_count; i += 1) { TypeStructField *field = type_entry->data.structure.fields[i]; if (buf_eql_buf(field->name, name)) return field; } return nullptr; } else { assert(type_is_resolved(type_entry, ResolveStatusZeroBitsKnown)); if (type_entry->data.structure.src_field_count == 0) return nullptr; auto entry = type_entry->data.structure.fields_by_name.maybe_get(name); if (entry == nullptr) return nullptr; return entry->value; } } TypeUnionField *find_union_type_field(ZigType *type_entry, Buf *name) { assert(type_entry->id == ZigTypeIdUnion); assert(type_is_resolved(type_entry, ResolveStatusZeroBitsKnown)); if (type_entry->data.unionation.src_field_count == 0) return nullptr; auto entry = type_entry->data.unionation.fields_by_name.maybe_get(name); if (entry == nullptr) return nullptr; return entry->value; } TypeUnionField *find_union_field_by_tag(ZigType *type_entry, const BigInt *tag) { assert(type_entry->id == ZigTypeIdUnion); assert(type_is_resolved(type_entry, ResolveStatusZeroBitsKnown)); for (uint32_t i = 0; i < type_entry->data.unionation.src_field_count; i += 1) { TypeUnionField *field = &type_entry->data.unionation.fields[i]; if (bigint_cmp(&field->enum_field->value, tag) == CmpEQ) { return field; } } return nullptr; } TypeEnumField *find_enum_field_by_tag(ZigType *enum_type, const BigInt *tag) { assert(type_is_resolved(enum_type, ResolveStatusZeroBitsKnown)); for (uint32_t i = 0; i < enum_type->data.enumeration.src_field_count; i += 1) { TypeEnumField *field = &enum_type->data.enumeration.fields[i]; if (bigint_cmp(&field->value, tag) == CmpEQ) { return field; } } return nullptr; } bool is_container(ZigType *type_entry) { switch (type_entry->id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdStruct: return type_entry->data.structure.special != StructSpecialSlice; case ZigTypeIdEnum: case ZigTypeIdUnion: case ZigTypeIdOpaque: return true; case ZigTypeIdPointer: case ZigTypeIdMetaType: case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdUnreachable: case ZigTypeIdInt: case ZigTypeIdFloat: case ZigTypeIdArray: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdOptional: case ZigTypeIdErrorUnion: case ZigTypeIdErrorSet: case ZigTypeIdFn: case ZigTypeIdBoundFn: case ZigTypeIdVector: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: return false; } zig_unreachable(); } bool is_ref(ZigType *type_entry) { return type_entry->id == ZigTypeIdPointer && type_entry->data.pointer.ptr_len == PtrLenSingle; } bool is_array_ref(ZigType *type_entry) { ZigType *array = is_ref(type_entry) ? type_entry->data.pointer.child_type : type_entry; return array->id == ZigTypeIdArray; } bool is_container_ref(ZigType *parent_ty) { ZigType *ty = is_ref(parent_ty) ? parent_ty->data.pointer.child_type : parent_ty; return is_slice(ty) || is_container(ty); } ZigType *container_ref_type(ZigType *type_entry) { assert(is_container_ref(type_entry)); return is_ref(type_entry) ? type_entry->data.pointer.child_type : type_entry; } ZigType *get_src_ptr_type(ZigType *type) { if (type->id == ZigTypeIdPointer) return type; if (type->id == ZigTypeIdFn) return type; if (type->id == ZigTypeIdAnyFrame) return type; if (type->id == ZigTypeIdOptional) { if (type->data.maybe.child_type->id == ZigTypeIdPointer) { return type->data.maybe.child_type->data.pointer.allow_zero ? nullptr : type->data.maybe.child_type; } if (type->data.maybe.child_type->id == ZigTypeIdFn) return type->data.maybe.child_type; if (type->data.maybe.child_type->id == ZigTypeIdAnyFrame) return type->data.maybe.child_type; } return nullptr; } Error get_codegen_ptr_type(CodeGen *g, ZigType *type, ZigType **result) { Error err; ZigType *ty = get_src_ptr_type(type); if (ty == nullptr) { *result = nullptr; return ErrorNone; } bool has_bits; if ((err = type_has_bits2(g, ty, &has_bits))) return err; if (!has_bits) { *result = nullptr; return ErrorNone; } *result = ty; return ErrorNone; } ZigType *get_codegen_ptr_type_bail(CodeGen *g, ZigType *type) { Error err; ZigType *result; if ((err = get_codegen_ptr_type(g, type, &result))) { codegen_report_errors_and_exit(g); } return result; } bool type_is_nonnull_ptr(CodeGen *g, ZigType *type) { Error err; bool result; if ((err = type_is_nonnull_ptr2(g, type, &result))) { codegen_report_errors_and_exit(g); } return result; } Error type_is_nonnull_ptr2(CodeGen *g, ZigType *type, bool *result) { Error err; ZigType *ptr_type; if ((err = get_codegen_ptr_type(g, type, &ptr_type))) return err; *result = ptr_type == type && !ptr_allows_addr_zero(type); return ErrorNone; } uint32_t get_async_frame_align_bytes(CodeGen *g) { // Due to how the frame structure is built the minimum alignment is the one // of a usize (or pointer). // label (grep this): [fn_frame_struct_layout] return max(g->builtin_types.entry_usize->abi_align, target_fn_align(g->zig_target)); } uint32_t get_ptr_align(CodeGen *g, ZigType *type) { ZigType *ptr_type; if (type->id == ZigTypeIdStruct) { assert(type->data.structure.special == StructSpecialSlice); TypeStructField *ptr_field = type->data.structure.fields[slice_ptr_index]; ptr_type = resolve_struct_field_type(g, ptr_field); } else { ptr_type = get_src_ptr_type(type); } if (ptr_type->id == ZigTypeIdPointer) { return (ptr_type->data.pointer.explicit_alignment == 0) ? get_abi_alignment(g, ptr_type->data.pointer.child_type) : ptr_type->data.pointer.explicit_alignment; } else if (ptr_type->id == ZigTypeIdFn) { return (ptr_type->data.fn.fn_type_id.alignment == 0) ? target_fn_ptr_align(g->zig_target) : ptr_type->data.fn.fn_type_id.alignment; } else if (ptr_type->id == ZigTypeIdAnyFrame) { return get_async_frame_align_bytes(g); } else { zig_unreachable(); } } bool get_ptr_const(CodeGen *g, ZigType *type) { ZigType *ptr_type; if (type->id == ZigTypeIdStruct) { assert(type->data.structure.special == StructSpecialSlice); TypeStructField *ptr_field = type->data.structure.fields[slice_ptr_index]; ptr_type = resolve_struct_field_type(g, ptr_field); } else { ptr_type = get_src_ptr_type(type); } if (ptr_type->id == ZigTypeIdPointer) { return ptr_type->data.pointer.is_const; } else if (ptr_type->id == ZigTypeIdFn) { return true; } else if (ptr_type->id == ZigTypeIdAnyFrame) { return true; } else { zig_unreachable(); } } AstNode *get_param_decl_node(ZigFn *fn_entry, size_t index) { if (fn_entry->param_source_nodes) return fn_entry->param_source_nodes[index]; else if (fn_entry->proto_node) return fn_entry->proto_node->data.fn_proto.params.at(index); else return nullptr; } static Error define_local_param_variables(CodeGen *g, ZigFn *fn_table_entry) { Error err; ZigType *fn_type = fn_table_entry->type_entry; assert(!fn_type->data.fn.is_generic); FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id; for (size_t i = 0; i < fn_type_id->param_count; i += 1) { FnTypeParamInfo *param_info = &fn_type_id->param_info[i]; AstNode *param_decl_node = get_param_decl_node(fn_table_entry, i); Buf *param_name; bool is_var_args = param_decl_node && param_decl_node->data.param_decl.is_var_args; if (param_decl_node && !is_var_args) { param_name = param_decl_node->data.param_decl.name; } else { param_name = buf_sprintf("arg%" ZIG_PRI_usize "", i); } if (param_name == nullptr) { continue; } ZigType *param_type = param_info->type; if ((err = type_resolve(g, param_type, ResolveStatusSizeKnown))) { return err; } bool is_noalias = param_info->is_noalias; if (is_noalias) { ZigType *ptr_type; if ((err = get_codegen_ptr_type(g, param_type, &ptr_type))) return err; if (ptr_type == nullptr) { add_node_error(g, param_decl_node, buf_sprintf("noalias on non-pointer parameter")); } } ZigVar *var = add_variable(g, param_decl_node, fn_table_entry->child_scope, param_name, true, create_const_runtime(g, param_type), nullptr, param_type); var->src_arg_index = i; fn_table_entry->child_scope = var->child_scope; var->shadowable = var->shadowable || is_var_args; if (type_has_bits(g, param_type)) { fn_table_entry->variable_list.append(var); } } return ErrorNone; } bool resolve_inferred_error_set(CodeGen *g, ZigType *err_set_type, AstNode *source_node) { assert(err_set_type->id == ZigTypeIdErrorSet); ZigFn *infer_fn = err_set_type->data.error_set.infer_fn; if (infer_fn != nullptr && err_set_type->data.error_set.incomplete) { if (infer_fn->anal_state == FnAnalStateInvalid) { return false; } else if (infer_fn->anal_state == FnAnalStateReady) { analyze_fn_body(g, infer_fn); if (infer_fn->anal_state == FnAnalStateInvalid || err_set_type->data.error_set.incomplete) { assert(g->errors.length != 0); return false; } } else { add_node_error(g, source_node, buf_sprintf("cannot resolve inferred error set '%s': function '%s' not fully analyzed yet", buf_ptr(&err_set_type->name), buf_ptr(&err_set_type->data.error_set.infer_fn->symbol_name))); return false; } } return true; } static void resolve_async_fn_frame(CodeGen *g, ZigFn *fn) { ZigType *frame_type = get_fn_frame_type(g, fn); Error err; if ((err = type_resolve(g, frame_type, ResolveStatusSizeKnown))) { if (g->trace_err != nullptr && frame_type->data.frame.resolve_loop_src_node != nullptr && !frame_type->data.frame.reported_loop_err) { frame_type->data.frame.reported_loop_err = true; g->trace_err = add_error_note(g, g->trace_err, frame_type->data.frame.resolve_loop_src_node, buf_sprintf("when analyzing type '%s' here", buf_ptr(&frame_type->name))); } fn->anal_state = FnAnalStateInvalid; return; } } bool fn_is_async(ZigFn *fn) { assert(fn->inferred_async_node != nullptr); assert(fn->inferred_async_node != inferred_async_checking); return fn->inferred_async_node != inferred_async_none; } void add_async_error_notes(CodeGen *g, ErrorMsg *msg, ZigFn *fn) { assert(fn->inferred_async_node != nullptr); assert(fn->inferred_async_node != inferred_async_checking); assert(fn->inferred_async_node != inferred_async_none); if (fn->inferred_async_fn != nullptr) { ErrorMsg *new_msg; if (fn->inferred_async_node->type == NodeTypeAwaitExpr) { new_msg = add_error_note(g, msg, fn->inferred_async_node, buf_create_from_str("await here is a suspend point")); } else { new_msg = add_error_note(g, msg, fn->inferred_async_node, buf_sprintf("async function call here")); } return add_async_error_notes(g, new_msg, fn->inferred_async_fn); } else if (fn->inferred_async_node->type == NodeTypeFnProto) { add_error_note(g, msg, fn->inferred_async_node, buf_sprintf("async calling convention here")); } else if (fn->inferred_async_node->type == NodeTypeSuspend) { add_error_note(g, msg, fn->inferred_async_node, buf_sprintf("suspends here")); } else if (fn->inferred_async_node->type == NodeTypeAwaitExpr) { add_error_note(g, msg, fn->inferred_async_node, buf_sprintf("await here is a suspend point")); } else if (fn->inferred_async_node->type == NodeTypeFnCallExpr && fn->inferred_async_node->data.fn_call_expr.modifier == CallModifierBuiltin) { add_error_note(g, msg, fn->inferred_async_node, buf_sprintf("@frame() causes function to be async")); } else { add_error_note(g, msg, fn->inferred_async_node, buf_sprintf("suspends here")); } } // ErrorNone - not async // ErrorIsAsync - yes async // ErrorSemanticAnalyzeFail - compile error emitted result is invalid static Error analyze_callee_async(CodeGen *g, ZigFn *fn, ZigFn *callee, AstNode *call_node, bool must_not_be_async, CallModifier modifier) { if (modifier == CallModifierNoSuspend) return ErrorNone; bool callee_is_async = false; switch (callee->type_entry->data.fn.fn_type_id.cc) { case CallingConventionUnspecified: break; case CallingConventionAsync: callee_is_async = true; break; default: return ErrorNone; } if (!callee_is_async) { if (callee->anal_state == FnAnalStateReady) { analyze_fn_body(g, callee); if (callee->anal_state == FnAnalStateInvalid) { return ErrorSemanticAnalyzeFail; } } if (callee->anal_state == FnAnalStateComplete) { analyze_fn_async(g, callee, true); if (callee->anal_state == FnAnalStateInvalid) { if (g->trace_err != nullptr) { g->trace_err = add_error_note(g, g->trace_err, call_node, buf_sprintf("while checking if '%s' is async", buf_ptr(&fn->symbol_name))); } return ErrorSemanticAnalyzeFail; } callee_is_async = fn_is_async(callee); } else { // If it's already been determined, use that value. Otherwise // assume non-async, emit an error later if it turned out to be async. if (callee->inferred_async_node == nullptr || callee->inferred_async_node == inferred_async_checking) { callee->assumed_non_async = call_node; callee_is_async = false; } else { callee_is_async = callee->inferred_async_node != inferred_async_none; } } } if (callee_is_async) { bool bad_recursion = (fn->inferred_async_node == inferred_async_none); fn->inferred_async_node = call_node; fn->inferred_async_fn = callee; if (must_not_be_async) { ErrorMsg *msg = add_node_error(g, fn->proto_node, buf_sprintf("function with calling convention '%s' cannot be async", calling_convention_name(fn->type_entry->data.fn.fn_type_id.cc))); add_async_error_notes(g, msg, fn); return ErrorSemanticAnalyzeFail; } if (bad_recursion) { ErrorMsg *msg = add_node_error(g, fn->proto_node, buf_sprintf("recursive function cannot be async")); add_async_error_notes(g, msg, fn); return ErrorSemanticAnalyzeFail; } if (fn->assumed_non_async != nullptr) { ErrorMsg *msg = add_node_error(g, fn->proto_node, buf_sprintf("unable to infer whether '%s' should be async", buf_ptr(&fn->symbol_name))); add_error_note(g, msg, fn->assumed_non_async, buf_sprintf("assumed to be non-async here")); add_async_error_notes(g, msg, fn); fn->anal_state = FnAnalStateInvalid; return ErrorSemanticAnalyzeFail; } return ErrorIsAsync; } return ErrorNone; } // This function resolves functions being inferred async. static void analyze_fn_async(CodeGen *g, ZigFn *fn, bool resolve_frame) { if (fn->inferred_async_node == inferred_async_checking) { // TODO call graph cycle detected, disallow the recursion fn->inferred_async_node = inferred_async_none; return; } if (fn->inferred_async_node == inferred_async_none) { return; } if (fn->inferred_async_node != nullptr) { if (resolve_frame) { resolve_async_fn_frame(g, fn); } return; } fn->inferred_async_node = inferred_async_checking; bool must_not_be_async = false; if (fn->type_entry->data.fn.fn_type_id.cc != CallingConventionUnspecified) { must_not_be_async = true; fn->inferred_async_node = inferred_async_none; } for (size_t i = 0; i < fn->call_list.length; i += 1) { Stage1AirInstCall *call = fn->call_list.at(i); if (call->fn_entry == nullptr) { // TODO function pointer call here, could be anything continue; } switch (analyze_callee_async(g, fn, call->fn_entry, call->base.source_node, must_not_be_async, call->modifier)) { case ErrorSemanticAnalyzeFail: fn->anal_state = FnAnalStateInvalid; return; case ErrorNone: continue; case ErrorIsAsync: if (resolve_frame) { resolve_async_fn_frame(g, fn); } return; default: zig_unreachable(); } } for (size_t i = 0; i < fn->await_list.length; i += 1) { Stage1AirInstAwait *await = fn->await_list.at(i); if (await->is_nosuspend) continue; switch (analyze_callee_async(g, fn, await->target_fn, await->base.source_node, must_not_be_async, CallModifierNone)) { case ErrorSemanticAnalyzeFail: fn->anal_state = FnAnalStateInvalid; return; case ErrorNone: continue; case ErrorIsAsync: if (resolve_frame) { resolve_async_fn_frame(g, fn); } return; default: zig_unreachable(); } } fn->inferred_async_node = inferred_async_none; } static void analyze_fn_ir(CodeGen *g, ZigFn *fn, AstNode *return_type_node) { ZigType *fn_type = fn->type_entry; assert(!fn_type->data.fn.is_generic); FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id; if (fn->analyzed_executable.begin_scope == nullptr) { fn->analyzed_executable.begin_scope = &fn->def_scope->base; } if (fn->analyzed_executable.source_node == nullptr) { fn->analyzed_executable.source_node = fn->body_node; } size_t backward_branch_count = 0; size_t backward_branch_quota = max(fn->branch_quota, default_backward_branch_quota); ZigType *block_return_type = ir_analyze(g, fn->stage1_zir, &fn->analyzed_executable, &backward_branch_count, &backward_branch_quota, fn_type_id->return_type, return_type_node, nullptr, fn); fn->src_implicit_return_type = block_return_type; if (type_is_invalid(block_return_type) || fn->analyzed_executable.first_err_trace_msg != nullptr) { assert(g->errors.length > 0); fn->anal_state = FnAnalStateInvalid; return; } if (fn_type_id->return_type->id == ZigTypeIdErrorUnion) { ZigType *return_err_set_type = fn_type_id->return_type->data.error_union.err_set_type; if (return_err_set_type->data.error_set.infer_fn != nullptr && return_err_set_type->data.error_set.incomplete) { // The inferred error set type is null if the function doesn't // return any error ZigType *inferred_err_set_type = nullptr; if (fn->src_implicit_return_type->id == ZigTypeIdErrorSet) { inferred_err_set_type = fn->src_implicit_return_type; } else if (fn->src_implicit_return_type->id == ZigTypeIdErrorUnion) { inferred_err_set_type = fn->src_implicit_return_type->data.error_union.err_set_type; } if (inferred_err_set_type != nullptr) { if (inferred_err_set_type->data.error_set.infer_fn != nullptr && inferred_err_set_type->data.error_set.incomplete) { if (!resolve_inferred_error_set(g, inferred_err_set_type, return_type_node)) { fn->anal_state = FnAnalStateInvalid; return; } } return_err_set_type->data.error_set.incomplete = false; if (type_is_global_error_set(inferred_err_set_type)) { return_err_set_type->data.error_set.err_count = UINT32_MAX; } else { return_err_set_type->data.error_set.err_count = inferred_err_set_type->data.error_set.err_count; if (inferred_err_set_type->data.error_set.err_count > 0) { return_err_set_type->data.error_set.errors = heap::c_allocator.allocate<ErrorTableEntry *>(inferred_err_set_type->data.error_set.err_count); for (uint32_t i = 0; i < inferred_err_set_type->data.error_set.err_count; i += 1) { return_err_set_type->data.error_set.errors[i] = inferred_err_set_type->data.error_set.errors[i]; } } } } else { return_err_set_type->data.error_set.incomplete = false; return_err_set_type->data.error_set.err_count = 0; } } } CallingConvention cc = fn->type_entry->data.fn.fn_type_id.cc; if (cc != CallingConventionUnspecified && cc != CallingConventionAsync && fn->inferred_async_node != nullptr && fn->inferred_async_node != inferred_async_checking && fn->inferred_async_node != inferred_async_none) { ErrorMsg *msg = add_node_error(g, fn->proto_node, buf_sprintf("function with calling convention '%s' cannot be async", calling_convention_name(cc))); add_async_error_notes(g, msg, fn); fn->anal_state = FnAnalStateInvalid; } if (g->verbose_ir) { fprintf(stderr, "fn %s() { // (analyzed)\n", buf_ptr(&fn->symbol_name)); ir_print_gen(g, stderr, &fn->analyzed_executable, 4); fprintf(stderr, "}\n"); } fn->anal_state = FnAnalStateComplete; } static void analyze_fn_body(CodeGen *g, ZigFn *fn_table_entry) { assert(fn_table_entry->anal_state != FnAnalStateProbing); if (fn_table_entry->anal_state != FnAnalStateReady) return; fn_table_entry->anal_state = FnAnalStateProbing; update_progress_display(g); AstNode *return_type_node = (fn_table_entry->proto_node != nullptr) ? fn_table_entry->proto_node->data.fn_proto.return_type : fn_table_entry->fndef_scope->base.source_node; assert(fn_table_entry->fndef_scope); if (!fn_table_entry->child_scope) fn_table_entry->child_scope = &fn_table_entry->fndef_scope->base; if (define_local_param_variables(g, fn_table_entry) != ErrorNone) { fn_table_entry->anal_state = FnAnalStateInvalid; return; } ZigType *fn_type = fn_table_entry->type_entry; assert(!fn_type->data.fn.is_generic); if (!stage1_astgen_fn(g, fn_table_entry)) { fn_table_entry->anal_state = FnAnalStateInvalid; return; } if (fn_table_entry->stage1_zir->first_err_trace_msg != nullptr) { fn_table_entry->anal_state = FnAnalStateInvalid; return; } if (g->verbose_ir) { fprintf(stderr, "\nfn %s() { // (IR)\n", buf_ptr(&fn_table_entry->symbol_name)); ir_print_src(g, stderr, fn_table_entry->stage1_zir, 4); fprintf(stderr, "}\n"); } analyze_fn_ir(g, fn_table_entry, return_type_node); } ZigType *add_source_file(CodeGen *g, ZigPackage *package, Buf *resolved_path, Buf *source_code, SourceKind source_kind) { Tokenization tokenization = {0}; tokenize(buf_ptr(source_code), &tokenization); if (tokenization.err) { ErrorMsg *err = err_msg_create_with_offset(resolved_path, tokenization.err_byte_offset, buf_ptr(source_code), tokenization.err); print_err_msg(err, g->err_color); exit(1); } Buf *src_dirname = buf_alloc(); Buf *src_basename = buf_alloc(); os_path_split(resolved_path, src_dirname, src_basename); Buf noextname = BUF_INIT; os_path_extname(resolved_path, &noextname, nullptr); Buf *pkg_root_src_dir = &package->root_src_dir; Buf resolved_root_src_dir = os_path_resolve(&pkg_root_src_dir, 1); Buf *namespace_name = buf_create_from_buf(&package->pkg_path); if (source_kind == SourceKindNonRoot) { assert(buf_starts_with_buf(resolved_path, &resolved_root_src_dir)); if (buf_len(namespace_name) != 0) { buf_append_char(namespace_name, NAMESPACE_SEP_CHAR); } // The namespace components are obtained from the relative path to the // source directory if (buf_len(&noextname) > buf_len(&resolved_root_src_dir)) { // Skip the trailing separator buf_append_mem(namespace_name, buf_ptr(&noextname) + buf_len(&resolved_root_src_dir) + 1, buf_len(&noextname) - buf_len(&resolved_root_src_dir) - 1); } buf_replace(namespace_name, ZIG_OS_SEP_CHAR, NAMESPACE_SEP_CHAR); } Buf *bare_name = buf_alloc(); os_path_extname(src_basename, bare_name, nullptr); RootStruct *root_struct = heap::c_allocator.create<RootStruct>(); root_struct->package = package; root_struct->source_code = source_code; root_struct->path = resolved_path; root_struct->di_file = ZigLLVMCreateFile(g->dbuilder, buf_ptr(src_basename), buf_ptr(src_dirname)); assert(tokenization.ids.length == tokenization.locs.length); size_t token_count = tokenization.ids.length; root_struct->token_count = token_count; root_struct->token_ids = g->pass1_arena->allocate<TokenId>(token_count); memcpy(root_struct->token_ids, tokenization.ids.items, token_count * sizeof(TokenId)); root_struct->token_locs = g->pass1_arena->allocate<TokenLoc>(token_count); memcpy(root_struct->token_locs, tokenization.locs.items, token_count * sizeof(TokenLoc)); tokenization.ids.deinit(); tokenization.locs.deinit(); ZigType *import_entry = get_root_container_type(g, buf_ptr(namespace_name), bare_name, root_struct); if (source_kind == SourceKindRoot) { assert(g->root_import == nullptr); g->root_import = import_entry; } g->import_table.put(resolved_path, import_entry); AstNode *root_node = ast_parse(source_code, import_entry, g->err_color); assert(root_node != nullptr); assert(root_node->type == NodeTypeContainerDecl); import_entry->data.structure.decl_node = root_node; import_entry->data.structure.decls_scope->base.source_node = root_node; for (size_t decl_i = 0; decl_i < root_node->data.container_decl.decls.length; decl_i += 1) { AstNode *top_level_decl = root_node->data.container_decl.decls.at(decl_i); scan_decls(g, import_entry->data.structure.decls_scope, top_level_decl); } TldContainer *tld_container = heap::c_allocator.create<TldContainer>(); init_tld(&tld_container->base, TldIdContainer, namespace_name, VisibModPub, root_node, nullptr); tld_container->type_entry = import_entry; tld_container->decls_scope = import_entry->data.structure.decls_scope; g->resolve_queue.append(&tld_container->base); return import_entry; } void semantic_analyze(CodeGen *g) { while (g->resolve_queue_index < g->resolve_queue.length || g->fn_defs_index < g->fn_defs.length) { for (; g->resolve_queue_index < g->resolve_queue.length; g->resolve_queue_index += 1) { Tld *tld = g->resolve_queue.at(g->resolve_queue_index); g->trace_err = nullptr; AstNode *source_node = nullptr; resolve_top_level_decl(g, tld, source_node, false); } for (; g->fn_defs_index < g->fn_defs.length; g->fn_defs_index += 1) { ZigFn *fn_entry = g->fn_defs.at(g->fn_defs_index); g->trace_err = nullptr; analyze_fn_body(g, fn_entry); } } if (g->errors.length != 0) { return; } // second pass over functions for detecting async for (g->fn_defs_index = 0; g->fn_defs_index < g->fn_defs.length; g->fn_defs_index += 1) { ZigFn *fn = g->fn_defs.at(g->fn_defs_index); g->trace_err = nullptr; analyze_fn_async(g, fn, true); if (fn->anal_state == FnAnalStateInvalid) continue; if (fn_is_async(fn) && fn->non_async_node != nullptr) { ErrorMsg *msg = add_node_error(g, fn->proto_node, buf_sprintf("'%s' cannot be async", buf_ptr(&fn->symbol_name))); add_error_note(g, msg, fn->non_async_node, buf_sprintf("required to be non-async here")); add_async_error_notes(g, msg, fn); } } } ZigType *get_int_type(CodeGen *g, bool is_signed, uint32_t size_in_bits) { assert(size_in_bits <= 65535); TypeId type_id = {}; type_id.id = ZigTypeIdInt; type_id.data.integer.is_signed = is_signed; type_id.data.integer.bit_count = size_in_bits; { auto entry = g->type_table.maybe_get(type_id); if (entry) return entry->value; } ZigType *new_entry = make_int_type(g, is_signed, size_in_bits); g->type_table.put(type_id, new_entry); return new_entry; } Error is_valid_vector_elem_type(CodeGen *g, ZigType *elem_type, bool *result) { if (elem_type->id == ZigTypeIdInt || elem_type->id == ZigTypeIdFloat || elem_type->id == ZigTypeIdBool) { *result = true; return ErrorNone; } Error err; ZigType *ptr_type; if ((err = get_codegen_ptr_type(g, elem_type, &ptr_type))) return err; if (ptr_type != nullptr) { *result = true; return ErrorNone; } *result = false; return ErrorNone; } ZigType *get_vector_type(CodeGen *g, uint32_t len, ZigType *elem_type) { Error err; bool valid_vector_elem; if ((err = is_valid_vector_elem_type(g, elem_type, &valid_vector_elem))) { codegen_report_errors_and_exit(g); } assert(valid_vector_elem); TypeId type_id = {}; type_id.id = ZigTypeIdVector; type_id.data.vector.len = len; type_id.data.vector.elem_type = elem_type; { auto entry = g->type_table.maybe_get(type_id); if (entry) return entry->value; } ZigType *entry = new_type_table_entry(ZigTypeIdVector); if ((len != 0) && type_has_bits(g, elem_type)) { // Vectors can only be ints, floats, bools, or pointers. ints (inc. bools) and floats have trivially resolvable // llvm type refs. pointers we will use usize instead. LLVMTypeRef example_vector_llvm_type; if (elem_type->id == ZigTypeIdPointer) { example_vector_llvm_type = LLVMVectorType(g->builtin_types.entry_usize->llvm_type, len); } else { example_vector_llvm_type = LLVMVectorType(elem_type->llvm_type, len); } assert(example_vector_llvm_type != nullptr); entry->size_in_bits = elem_type->size_in_bits * len; entry->abi_size = LLVMABISizeOfType(g->target_data_ref, example_vector_llvm_type); entry->abi_align = LLVMABIAlignmentOfType(g->target_data_ref, example_vector_llvm_type); } entry->data.vector.len = len; entry->data.vector.elem_type = elem_type; entry->data.vector.padding = 0; buf_resize(&entry->name, 0); buf_appendf(&entry->name, "@Vector(%u, %s)", len, buf_ptr(&elem_type->name)); g->type_table.put(type_id, entry); return entry; } ZigType **get_c_int_type_ptr(CodeGen *g, CIntType c_int_type) { return &g->builtin_types.entry_c_int[c_int_type]; } ZigType *get_c_int_type(CodeGen *g, CIntType c_int_type) { return *get_c_int_type_ptr(g, c_int_type); } bool handle_is_ptr(CodeGen *g, ZigType *type_entry) { switch (type_entry->id) { case ZigTypeIdInvalid: case ZigTypeIdMetaType: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdBoundFn: case ZigTypeIdOpaque: zig_unreachable(); case ZigTypeIdUnreachable: case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdInt: case ZigTypeIdFloat: case ZigTypeIdPointer: case ZigTypeIdErrorSet: case ZigTypeIdFn: case ZigTypeIdEnum: case ZigTypeIdVector: case ZigTypeIdAnyFrame: return false; case ZigTypeIdArray: case ZigTypeIdStruct: case ZigTypeIdFnFrame: return type_has_bits(g, type_entry); case ZigTypeIdErrorUnion: return type_has_bits(g, type_entry->data.error_union.payload_type); case ZigTypeIdOptional: return type_has_bits(g, type_entry->data.maybe.child_type) && !type_is_nonnull_ptr(g, type_entry->data.maybe.child_type) && type_entry->data.maybe.child_type->id != ZigTypeIdErrorSet; case ZigTypeIdUnion: return type_has_bits(g, type_entry) && type_entry->data.unionation.gen_field_count != 0; } zig_unreachable(); } static const uint32_t HASH_INIT = 0x811c9dc5U; template<typename T> static uint32_t hash_combine(uint32_t hash, const T *value, size_t count = 1) { // Simple FNV32 hash size_t len = sizeof(T) * count; const unsigned char *char_bytes = (const unsigned char*)value; for (size_t c = 0; c < len; ++c) { hash ^= char_bytes[c]; hash *= 0x01000193U; } return hash; } static uint32_t hash_combine_bigint(uint32_t hash, const BigInt *value) { return hash_combine(hash, bigint_ptr(value), value->digit_count); } static uint32_t hash_combine_buf(uint32_t hash, const Buf *buf) { return hash_combine(hash, buf_ptr(buf), buf_len(buf)); } uint32_t fn_table_entry_hash(ZigFn* value) { return hash_combine(HASH_INIT, &value); } bool fn_table_entry_eql(ZigFn *a, ZigFn *b) { return a == b; } uint32_t fn_type_id_hash(FnTypeId *id) { uint32_t hash = HASH_INIT; hash = hash_combine(hash, &id->cc); hash = hash_combine(hash, &id->is_var_args); hash = hash_combine(hash, &id->return_type); hash = hash_combine(hash, &id->alignment); for (size_t i = 0; i < id->param_count; i += 1) { FnTypeParamInfo *info = &id->param_info[i]; hash = hash_combine(hash, &info->is_noalias); hash = hash_combine(hash, &info->type); } return hash; } bool fn_type_id_eql(FnTypeId *a, FnTypeId *b) { if (a->cc != b->cc || a->return_type != b->return_type || a->is_var_args != b->is_var_args || a->param_count != b->param_count || a->alignment != b->alignment) { return false; } for (size_t i = 0; i < a->param_count; i += 1) { FnTypeParamInfo *a_param_info = &a->param_info[i]; FnTypeParamInfo *b_param_info = &b->param_info[i]; if (a_param_info->type != b_param_info->type || a_param_info->is_noalias != b_param_info->is_noalias) { return false; } } return true; } static uint32_t hash_combine_const_val_error_set(uint32_t hash_val, ZigValue *const_val) { assert(const_val->data.x_err_set != nullptr); return hash_combine(hash_val, &const_val->data.x_err_set->value); } static uint32_t hash_combine_const_val_ptr(uint32_t hash_val, ZigValue *const_val) { hash_val = hash_combine(hash_val, &const_val->data.x_ptr.special); switch (const_val->data.x_ptr.special) { case ConstPtrSpecialInvalid: zig_unreachable(); case ConstPtrSpecialRef: hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.ref.pointee); return hash_val; case ConstPtrSpecialBaseArray: hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.base_array.array_val); hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.base_array.elem_index); return hash_val; case ConstPtrSpecialSubArray: hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.base_array.array_val); hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.base_array.elem_index); return hash_val; case ConstPtrSpecialBaseStruct: hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.base_struct.struct_val); hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.base_struct.field_index); return hash_val; case ConstPtrSpecialBaseErrorUnionCode: hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.base_err_union_code.err_union_val); return hash_val; case ConstPtrSpecialBaseErrorUnionPayload: hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.base_err_union_payload.err_union_val); return hash_val; case ConstPtrSpecialBaseOptionalPayload: hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.base_optional_payload.optional_val); return hash_val; case ConstPtrSpecialHardCodedAddr: hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.hard_coded_addr.addr); return hash_val; case ConstPtrSpecialFunction: hash_val = hash_combine(hash_val, &const_val->data.x_ptr.data.fn.fn_entry); return hash_val; case ConstPtrSpecialDiscard: case ConstPtrSpecialNull: // No fields to hash return hash_val; } zig_unreachable(); } static uint32_t hash_combine_const_val(uint32_t hash_val, ZigValue *const_val); static uint32_t hash_combine_const_val_array(uint32_t hash_val, ZigValue *array, size_t len) { if (array->data.x_array.special == ConstArraySpecialUndef) { char undef_tag = 56; return hash_combine(hash_val, &undef_tag); } else if (array->data.x_array.special == ConstArraySpecialBuf) { // Hash in a way that is compatible with standard byte arrays // If any of these asserts fails, the if after this needs to be modified // to handle the new type in SpecialBuf. assert(array->type->data.array.child_type->id == ZigTypeIdInt); assert(array->type->data.array.child_type->data.integral.bit_count == 8); assert(array->type->data.array.child_type->data.integral.is_signed == false); const char *buf_pos = buf_ptr(array->data.x_array.data.s_buf); const char *buf_end = buf_pos + buf_len(array->data.x_array.data.s_buf); while (buf_pos < buf_end) { hash_val = hash_combine(hash_val, buf_pos); buf_pos++; } return hash_val; } else if (array->type->data.array.child_type->id == ZigTypeIdInt && array->type->data.array.child_type->data.integral.bit_count == 8 && array->type->data.array.child_type->data.integral.is_signed == false) { // If the type is u8, we hash it as if it's a ConstArraySpecialBuf, // to maintain compatibility. ZigValue *elems = array->data.x_array.data.s_none.elements; for (size_t i = 0; i < len; i += 1) { ZigValue *value = &elems[i]; assert(value->type == array->type->data.array.child_type); // N.B. Using char here instead of uint8_t to match the const char* // returned by buf_ptr. const char byte_value = (char) bigint_as_u8(&value->data.x_bigint); hash_val = hash_combine(hash_val, &byte_value); } return hash_val; } else { ZigValue *elems = array->data.x_array.data.s_none.elements; for (size_t i = 0; i < len; i += 1) { hash_val = hash_combine_const_val(hash_val, &elems[i]); } return hash_val; } } static uint32_t hash_combine_const_val(uint32_t hash_val, ZigValue *const_val) { hash_val = hash_combine(hash_val, &const_val->special); if (const_val->special == ConstValSpecialUndef) { return hash_val; } assert(const_val->special == ConstValSpecialStatic); hash_val = hash_combine(hash_val, &const_val->type->id); switch (const_val->type->id) { case ZigTypeIdOpaque: zig_unreachable(); case ZigTypeIdBool: return hash_combine(hash_val, &const_val->data.x_bool); case ZigTypeIdMetaType: return hash_combine(hash_val, &const_val->data.x_type); case ZigTypeIdInt: case ZigTypeIdComptimeInt: return hash_combine_bigint(hash_val, &const_val->data.x_bigint); case ZigTypeIdEnumLiteral: return hash_combine_buf(hash_val, const_val->data.x_enum_literal); case ZigTypeIdEnum: return hash_combine_bigint(hash_val, &const_val->data.x_enum_tag); case ZigTypeIdFloat: hash_val = hash_combine(hash_val, &const_val->type->data.floating.bit_count); switch (const_val->type->data.floating.bit_count) { case 16: return hash_combine(hash_val, &const_val->data.x_f16); case 32: return hash_combine(hash_val, &const_val->data.x_f32); case 64: return hash_combine(hash_val, &const_val->data.x_f64); case 128: return hash_combine(hash_val, &const_val->data.x_f128); default: zig_unreachable(); } case ZigTypeIdComptimeFloat: return hash_combine(hash_val, &const_val->data.x_bigfloat.value); case ZigTypeIdFn: assert(const_val->data.x_ptr.mut == ConstPtrMutComptimeConst); assert(const_val->data.x_ptr.special == ConstPtrSpecialFunction); return hash_combine(hash_val, &const_val->data.x_ptr.data.fn.fn_entry); case ZigTypeIdPointer: return hash_combine_const_val_ptr(hash_val, const_val); case ZigTypeIdVoid: case ZigTypeIdUndefined: case ZigTypeIdNull: return hash_val; case ZigTypeIdArray: return hash_combine_const_val_array(hash_val, const_val, const_val->type->data.array.len); case ZigTypeIdStruct: { size_t field_count = const_val->type->data.structure.src_field_count; for (size_t i = 0; i < field_count; i += 1) { if (const_val->type->data.structure.fields[i]->is_comptime) { // The values of comptime struct fields are part of the // type, not the value, so they do not participate in equality // or hash of comptime values. continue; } ZigValue *field = const_val->data.x_struct.fields[i]; hash_val = hash_combine_const_val(hash_val, field); } return hash_val; } case ZigTypeIdUnion: { ConstUnionValue *union_value = &const_val->data.x_union; hash_val = hash_combine_bigint(hash_val, &union_value->tag); return hash_combine_const_val(hash_val, union_value->payload); } case ZigTypeIdOptional: if (get_src_ptr_type(const_val->type) != nullptr) { char tag = 1; hash_val = hash_combine(hash_val, &tag); return hash_combine_const_val_ptr(hash_val, const_val); } else if (const_val->type->data.maybe.child_type->id == ZigTypeIdErrorSet) { char tag = 2; hash_val = hash_combine(hash_val, &tag); return hash_combine_const_val_error_set(hash_val, const_val); } else if (const_val->data.x_optional) { char tag = 3; hash_val = hash_combine(hash_val, &tag); return hash_combine_const_val(hash_val, const_val->data.x_optional); } else { char tag = 4; hash_val = hash_combine(hash_val, &tag); return hash_val; } case ZigTypeIdErrorUnion: { bool is_err = const_val->data.x_err_union.error_set->data.x_err_set != nullptr; hash_val = hash_combine(hash_val, &is_err); if (is_err) { hash_val = hash_combine_const_val(hash_val, const_val->data.x_err_union.error_set); } else { hash_val = hash_combine_const_val(hash_val, const_val->data.x_err_union.payload); } return hash_val; } case ZigTypeIdErrorSet: return hash_combine_const_val_error_set(hash_val, const_val); case ZigTypeIdVector: return hash_combine_const_val_array(hash_val, const_val, const_val->type->data.vector.len); case ZigTypeIdFnFrame: // TODO better hashing algorithm return hash_val; case ZigTypeIdAnyFrame: // TODO better hashing algorithm return hash_val; case ZigTypeIdBoundFn: { assert(const_val->data.x_bound_fn.fn != nullptr); return hash_combine(hash_val, &const_val->data.x_bound_fn.fn); } case ZigTypeIdInvalid: case ZigTypeIdUnreachable: zig_unreachable(); } zig_unreachable(); } uint32_t generic_fn_type_id_hash(GenericFnTypeId *id) { uint32_t result = HASH_INIT; result = hash_combine(result, &id->fn_entry); for (size_t i = 0; i < id->param_count; i += 1) { ZigValue *generic_param = &id->params[i]; if (generic_param->special != ConstValSpecialRuntime) { result = hash_combine_const_val(result, generic_param); result = hash_combine(result, &generic_param->type); } } return result; } bool generic_fn_type_id_eql(GenericFnTypeId *a, GenericFnTypeId *b) { assert(a->fn_entry); if (a->fn_entry != b->fn_entry) return false; if (a->param_count != b->param_count) return false; for (size_t i = 0; i < a->param_count; i += 1) { ZigValue *a_val = &a->params[i]; ZigValue *b_val = &b->params[i]; if (a_val->type != b_val->type) return false; if (a_val->special != ConstValSpecialRuntime && b_val->special != ConstValSpecialRuntime) { assert(a_val->special == ConstValSpecialStatic); assert(b_val->special == ConstValSpecialStatic); if (!const_values_equal(a->codegen, a_val, b_val)) { return false; } } else { assert(a_val->special == ConstValSpecialRuntime && b_val->special == ConstValSpecialRuntime); } } return true; } static bool can_mutate_comptime_var_state(ZigValue *value) { assert(value != nullptr); if (value->special == ConstValSpecialUndef) return false; if (value->special == ConstValSpecialLazy) { // No lazy value has side effects. // Use a switch here to get a compile error whenever a new kind of lazy // value is added. switch (value->data.x_lazy->id) { case LazyValueIdInvalid: zig_unreachable(); case LazyValueIdAlignOf: case LazyValueIdSizeOf: case LazyValueIdPtrType: case LazyValueIdPtrTypeSimple: case LazyValueIdPtrTypeSimpleConst: case LazyValueIdOptType: case LazyValueIdSliceType: case LazyValueIdFnType: case LazyValueIdErrUnionType: case LazyValueIdArrayType: case LazyValueIdTypeInfoDecls: return false; } } switch (value->type->id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdMetaType: case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdUnreachable: case ZigTypeIdInt: case ZigTypeIdVector: case ZigTypeIdFloat: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdBoundFn: case ZigTypeIdFn: case ZigTypeIdOpaque: case ZigTypeIdErrorSet: case ZigTypeIdEnum: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: return false; case ZigTypeIdPointer: return value->data.x_ptr.mut == ConstPtrMutComptimeVar; case ZigTypeIdArray: if (value->special == ConstValSpecialUndef) return false; if (value->type->data.array.len == 0) return false; switch (value->data.x_array.special) { case ConstArraySpecialUndef: case ConstArraySpecialBuf: return false; case ConstArraySpecialNone: for (uint32_t i = 0; i < value->type->data.array.len; i += 1) { if (can_mutate_comptime_var_state(&value->data.x_array.data.s_none.elements[i])) return true; } return false; } zig_unreachable(); case ZigTypeIdStruct: for (uint32_t i = 0; i < value->type->data.structure.src_field_count; i += 1) { TypeStructField *type_struct_field = value->type->data.structure.fields[i]; ZigValue *field_value = type_struct_field->is_comptime ? type_struct_field->init_val : value->data.x_struct.fields[i]; if (can_mutate_comptime_var_state(field_value)) return true; } return false; case ZigTypeIdOptional: if (get_src_ptr_type(value->type) != nullptr) return value->data.x_ptr.mut == ConstPtrMutComptimeVar; if (value->data.x_optional == nullptr) return false; return can_mutate_comptime_var_state(value->data.x_optional); case ZigTypeIdErrorUnion: if (value->data.x_err_union.error_set->data.x_err_set != nullptr) return false; assert(value->data.x_err_union.payload != nullptr); return can_mutate_comptime_var_state(value->data.x_err_union.payload); case ZigTypeIdUnion: return can_mutate_comptime_var_state(value->data.x_union.payload); } zig_unreachable(); } bool fn_eval_cacheable(Scope *scope, ZigType *return_type) { while (scope) { if (scope->id == ScopeIdVarDecl) { ScopeVarDecl *var_scope = (ScopeVarDecl *)scope; if (type_is_invalid(var_scope->var->var_type)) return false; if (var_scope->var->const_value->special == ConstValSpecialUndef) return false; if (can_mutate_comptime_var_state(var_scope->var->const_value)) return false; } else if (scope->id == ScopeIdFnDef) { return true; } else { zig_unreachable(); } scope = scope->parent; } zig_unreachable(); } uint32_t fn_eval_hash(Scope* scope) { uint32_t hash = HASH_INIT; while (scope) { if (scope->id == ScopeIdVarDecl) { ScopeVarDecl *var_scope = (ScopeVarDecl *)scope; hash = hash_combine_const_val(hash, var_scope->var->const_value); } else if (scope->id == ScopeIdFnDef) { ScopeFnDef *fn_scope = (ScopeFnDef *)scope; hash = hash_combine(hash, &fn_scope->fn_entry); return hash; } else { zig_unreachable(); } scope = scope->parent; } zig_unreachable(); } bool fn_eval_eql(Scope *a, Scope *b) { assert(a->codegen != nullptr); assert(b->codegen != nullptr); while (a && b) { if (a->id != b->id) return false; if (a->id == ScopeIdVarDecl) { ScopeVarDecl *a_var_scope = (ScopeVarDecl *)a; ScopeVarDecl *b_var_scope = (ScopeVarDecl *)b; if (a_var_scope->var->var_type != b_var_scope->var->var_type) return false; if (a_var_scope->var->var_type == a_var_scope->var->const_value->type && b_var_scope->var->var_type == b_var_scope->var->const_value->type) { if (!const_values_equal(a->codegen, a_var_scope->var->const_value, b_var_scope->var->const_value)) return false; } else { zig_panic("TODO comptime ptr reinterpret for fn_eval_eql"); } } else if (a->id == ScopeIdFnDef) { ScopeFnDef *a_fn_scope = (ScopeFnDef *)a; ScopeFnDef *b_fn_scope = (ScopeFnDef *)b; if (a_fn_scope->fn_entry != b_fn_scope->fn_entry) return false; return true; } else { zig_unreachable(); } a = a->parent; b = b->parent; } return false; } // Deprecated. Use type_has_bits2. bool type_has_bits(CodeGen *g, ZigType *type_entry) { Error err; bool result; if ((err = type_has_bits2(g, type_entry, &result))) { codegen_report_errors_and_exit(g); } return result; } // Whether the type has bits at runtime. Error type_has_bits2(CodeGen *g, ZigType *type_entry, bool *result) { Error err; if (type_is_invalid(type_entry)) return ErrorSemanticAnalyzeFail; if (type_entry->id == ZigTypeIdStruct && type_entry->data.structure.resolve_status == ResolveStatusBeingInferred) { *result = true; return ErrorNone; } if ((err = type_resolve(g, type_entry, ResolveStatusZeroBitsKnown))) return err; *result = type_entry->abi_size != 0; return ErrorNone; } bool fn_returns_c_abi_small_struct(FnTypeId *fn_type_id) { ZigType *type = fn_type_id->return_type; return !calling_convention_allows_zig_types(fn_type_id->cc) && type->id == ZigTypeIdStruct && type->abi_size <= 16; } // Whether you can infer the value based solely on the type. OnePossibleValue type_has_one_possible_value(CodeGen *g, ZigType *type_entry) { assert(type_entry != nullptr); if (type_entry->one_possible_value != OnePossibleValueInvalid) return type_entry->one_possible_value; if (type_entry->id == ZigTypeIdStruct && type_entry->data.structure.resolve_status == ResolveStatusBeingInferred) { return OnePossibleValueNo; } Error err; if ((err = type_resolve(g, type_entry, ResolveStatusZeroBitsKnown))) return OnePossibleValueInvalid; switch (type_entry->id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdOpaque: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdMetaType: case ZigTypeIdBoundFn: case ZigTypeIdOptional: case ZigTypeIdFn: case ZigTypeIdBool: case ZigTypeIdFloat: case ZigTypeIdErrorUnion: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: return OnePossibleValueNo; case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdVoid: case ZigTypeIdUnreachable: return OnePossibleValueYes; case ZigTypeIdArray: if (type_entry->data.array.len == 0) return OnePossibleValueYes; return type_has_one_possible_value(g, type_entry->data.array.child_type); case ZigTypeIdStruct: // If the recursive function call asks, then we are not one possible value. type_entry->one_possible_value = OnePossibleValueNo; for (size_t i = 0; i < type_entry->data.structure.src_field_count; i += 1) { TypeStructField *field = type_entry->data.structure.fields[i]; if (field->is_comptime) { // If this field is comptime then the field can only be one possible value continue; } OnePossibleValue opv = (field->type_entry != nullptr) ? type_has_one_possible_value(g, field->type_entry) : type_val_resolve_has_one_possible_value(g, field->type_val); switch (opv) { case OnePossibleValueInvalid: type_entry->one_possible_value = OnePossibleValueInvalid; return OnePossibleValueInvalid; case OnePossibleValueNo: return OnePossibleValueNo; case OnePossibleValueYes: continue; } } type_entry->one_possible_value = OnePossibleValueYes; return OnePossibleValueYes; case ZigTypeIdErrorSet: case ZigTypeIdEnum: case ZigTypeIdInt: case ZigTypeIdVector: return type_has_bits(g, type_entry) ? OnePossibleValueNo : OnePossibleValueYes; case ZigTypeIdPointer: { ZigType *elem_type = type_entry->data.pointer.child_type; // If the recursive function call asks, then we are not one possible value. type_entry->one_possible_value = OnePossibleValueNo; // Now update it to be the value of the recursive call. type_entry->one_possible_value = type_has_one_possible_value(g, elem_type); return type_entry->one_possible_value; } case ZigTypeIdUnion: if (type_entry->data.unionation.src_field_count > 1) return OnePossibleValueNo; TypeUnionField *only_field = &type_entry->data.unionation.fields[0]; if (only_field->type_entry != nullptr) { return type_has_one_possible_value(g, only_field->type_entry); } return type_val_resolve_has_one_possible_value(g, only_field->type_val); } zig_unreachable(); } ZigValue *get_the_one_possible_value(CodeGen *g, ZigType *type_entry) { auto entry = g->one_possible_values.maybe_get(type_entry); if (entry != nullptr) { return entry->value; } ZigValue *result = g->pass1_arena->create<ZigValue>(); result->type = type_entry; result->special = ConstValSpecialStatic; if (result->type->id == ZigTypeIdStruct) { // The fields array cannot be left unpopulated const ZigType *struct_type = result->type; const size_t field_count = struct_type->data.structure.src_field_count; result->data.x_struct.fields = alloc_const_vals_ptrs(g, field_count); for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = struct_type->data.structure.fields[i]; if (field->is_comptime) { // Comptime fields are part of the type, and do not need to // be initialized. continue; } ZigType *field_type = resolve_struct_field_type(g, field); assert(field_type != nullptr); copy_const_val(g, result->data.x_struct.fields[i], get_the_one_possible_value(g, field_type)); } } else if (result->type->id == ZigTypeIdArray) { // The elements array cannot be left unpopulated ZigType *array_type = result->type; ZigType *elem_type = array_type->data.array.child_type; const size_t elem_count = array_type->data.array.len; result->data.x_array.data.s_none.elements = g->pass1_arena->allocate<ZigValue>(elem_count); for (size_t i = 0; i < elem_count; i += 1) { ZigValue *elem_val = &result->data.x_array.data.s_none.elements[i]; copy_const_val(g, elem_val, get_the_one_possible_value(g, elem_type)); } } else if (result->type->id == ZigTypeIdUnion) { // The payload/tag fields cannot be left unpopulated ZigType *union_type = result->type; assert(union_type->data.unionation.src_field_count == 1); TypeUnionField *only_field = &union_type->data.unionation.fields[0]; ZigType *field_type = resolve_union_field_type(g, only_field); assert(field_type); bigint_init_bigint(&result->data.x_union.tag, &only_field->enum_field->value); result->data.x_union.payload = g->pass1_arena->create<ZigValue>(); copy_const_val(g, result->data.x_union.payload, get_the_one_possible_value(g, field_type)); } else if (result->type->id == ZigTypeIdPointer) { // Make sure nobody can modify the constant value result->data.x_ptr.mut = ConstPtrMutComptimeConst; result->data.x_ptr.special = ConstPtrSpecialRef; result->data.x_ptr.data.ref.pointee = get_the_one_possible_value(g, result->type->data.pointer.child_type); } else if (result->type->id == ZigTypeIdEnum) { ZigType *enum_type = result->type; assert(enum_type->data.enumeration.src_field_count == 1); TypeEnumField *only_field = &result->type->data.enumeration.fields[0]; bigint_init_bigint(&result->data.x_enum_tag, &only_field->value); } g->one_possible_values.put(type_entry, result); return result; } ReqCompTime type_requires_comptime(CodeGen *g, ZigType *ty) { Error err; if (ty == g->builtin_types.entry_anytype) { return ReqCompTimeYes; } switch (ty->id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdMetaType: case ZigTypeIdBoundFn: return ReqCompTimeYes; case ZigTypeIdArray: return type_requires_comptime(g, ty->data.array.child_type); case ZigTypeIdStruct: if (ty->data.structure.resolve_loop_flag_zero_bits) { // Does a struct which contains a pointer field to itself require comptime? No. return ReqCompTimeNo; } if ((err = type_resolve(g, ty, ResolveStatusZeroBitsKnown))) return ReqCompTimeInvalid; return ty->data.structure.requires_comptime ? ReqCompTimeYes : ReqCompTimeNo; case ZigTypeIdUnion: if (ty->data.unionation.resolve_loop_flag_zero_bits) { // Does a union which contains a pointer field to itself require comptime? No. return ReqCompTimeNo; } if ((err = type_resolve(g, ty, ResolveStatusZeroBitsKnown))) return ReqCompTimeInvalid; return ty->data.unionation.requires_comptime ? ReqCompTimeYes : ReqCompTimeNo; case ZigTypeIdOptional: return type_requires_comptime(g, ty->data.maybe.child_type); case ZigTypeIdErrorUnion: return type_requires_comptime(g, ty->data.error_union.payload_type); case ZigTypeIdPointer: if (ty->data.pointer.child_type->id == ZigTypeIdOpaque) { return ReqCompTimeNo; } else { return type_requires_comptime(g, ty->data.pointer.child_type); } case ZigTypeIdFn: return ty->data.fn.is_generic ? ReqCompTimeYes : ReqCompTimeNo; case ZigTypeIdOpaque: case ZigTypeIdEnum: case ZigTypeIdErrorSet: case ZigTypeIdBool: case ZigTypeIdInt: case ZigTypeIdVector: case ZigTypeIdFloat: case ZigTypeIdVoid: case ZigTypeIdUnreachable: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: return ReqCompTimeNo; } zig_unreachable(); } void init_const_str_lit(CodeGen *g, ZigValue *const_val, Buf *str, bool move_str) { auto entry = g->string_literals_table.maybe_get(str); if (entry != nullptr) { if (move_str) { buf_destroy(str); } memcpy(const_val, entry->value, sizeof(ZigValue)); return; } // first we build the underlying array ZigValue *array_val = g->pass1_arena->create<ZigValue>(); array_val->special = ConstValSpecialStatic; array_val->type = get_array_type(g, g->builtin_types.entry_u8, buf_len(str), g->intern.for_zero_byte()); array_val->data.x_array.special = ConstArraySpecialBuf; array_val->data.x_array.data.s_buf = str; // then make the pointer point to it const_val->special = ConstValSpecialStatic; const_val->type = get_pointer_to_type_extra2(g, array_val->type, true, false, PtrLenSingle, 0, 0, 0, false, VECTOR_INDEX_NONE, nullptr, nullptr); const_val->data.x_ptr.special = ConstPtrSpecialRef; const_val->data.x_ptr.data.ref.pointee = array_val; g->string_literals_table.put(str, const_val); } ZigValue *create_const_str_lit(CodeGen *g, Buf *str) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_str_lit(g, const_val, str, false); return const_val; } ZigValue *create_sentineled_str_lit(CodeGen *g, Buf *str, ZigValue *sentinel) { ZigValue *array_val = create_const_str_lit(g, str)->data.x_ptr.data.ref.pointee; return create_const_slice(g, array_val, 0, buf_len(str), true, sentinel); } void init_const_bigint(ZigValue *const_val, ZigType *type, const BigInt *bigint) { const_val->special = ConstValSpecialStatic; const_val->type = type; bigint_init_bigint(&const_val->data.x_bigint, bigint); } ZigValue *create_const_bigint(CodeGen *g, ZigType *type, const BigInt *bigint) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_bigint(const_val, type, bigint); return const_val; } void init_const_unsigned_negative(ZigValue *const_val, ZigType *type, uint64_t x, bool negative) { const_val->special = ConstValSpecialStatic; const_val->type = type; bigint_init_unsigned(&const_val->data.x_bigint, x); const_val->data.x_bigint.is_negative = negative; } ZigValue *create_const_unsigned_negative(CodeGen *g, ZigType *type, uint64_t x, bool negative) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_unsigned_negative(const_val, type, x, negative); return const_val; } void init_const_usize(CodeGen *g, ZigValue *const_val, uint64_t x) { return init_const_unsigned_negative(const_val, g->builtin_types.entry_usize, x, false); } ZigValue *create_const_usize(CodeGen *g, uint64_t x) { return create_const_unsigned_negative(g, g->builtin_types.entry_usize, x, false); } void init_const_signed(ZigValue *const_val, ZigType *type, int64_t x) { const_val->special = ConstValSpecialStatic; const_val->type = type; bigint_init_signed(&const_val->data.x_bigint, x); } ZigValue *create_const_signed(CodeGen *g, ZigType *type, int64_t x) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_signed(const_val, type, x); return const_val; } void init_const_null(ZigValue *const_val, ZigType *type) { const_val->special = ConstValSpecialStatic; const_val->type = type; const_val->data.x_optional = nullptr; } ZigValue *create_const_null(CodeGen *g, ZigType *type) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_null(const_val, type); return const_val; } void init_const_fn(ZigValue *const_val, ZigFn *fn) { const_val->special = ConstValSpecialStatic; const_val->type = fn->type_entry; const_val->data.x_ptr.special = ConstPtrSpecialFunction; const_val->data.x_ptr.data.fn.fn_entry = fn; } ZigValue *create_const_fn(CodeGen *g, ZigFn *fn) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_fn(const_val, fn); return const_val; } void init_const_float(ZigValue *const_val, ZigType *type, double value) { const_val->special = ConstValSpecialStatic; const_val->type = type; if (type->id == ZigTypeIdComptimeFloat) { bigfloat_init_64(&const_val->data.x_bigfloat, value); } else if (type->id == ZigTypeIdFloat) { switch (type->data.floating.bit_count) { case 16: const_val->data.x_f16 = zig_double_to_f16(value); break; case 32: const_val->data.x_f32 = value; break; case 64: const_val->data.x_f64 = value; break; case 128: // if we need this, we should add a function that accepts a float128_t param zig_unreachable(); default: zig_unreachable(); } } else { zig_unreachable(); } } ZigValue *create_const_float(CodeGen *g, ZigType *type, double value) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_float(const_val, type, value); return const_val; } void init_const_enum(ZigValue *const_val, ZigType *type, const BigInt *tag) { const_val->special = ConstValSpecialStatic; const_val->type = type; bigint_init_bigint(&const_val->data.x_enum_tag, tag); } ZigValue *create_const_enum(CodeGen *g, ZigType *type, const BigInt *tag) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_enum(const_val, type, tag); return const_val; } void init_const_bool(CodeGen *g, ZigValue *const_val, bool value) { const_val->special = ConstValSpecialStatic; const_val->type = g->builtin_types.entry_bool; const_val->data.x_bool = value; } ZigValue *create_const_bool(CodeGen *g, bool value) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_bool(g, const_val, value); return const_val; } void init_const_runtime(ZigValue *const_val, ZigType *type) { const_val->special = ConstValSpecialRuntime; const_val->type = type; } ZigValue *create_const_runtime(CodeGen *g, ZigType *type) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_runtime(const_val, type); return const_val; } void init_const_type(CodeGen *g, ZigValue *const_val, ZigType *type_value) { const_val->special = ConstValSpecialStatic; const_val->type = g->builtin_types.entry_type; const_val->data.x_type = type_value; } ZigValue *create_const_type(CodeGen *g, ZigType *type_value) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_type(g, const_val, type_value); return const_val; } void init_const_slice(CodeGen *g, ZigValue *const_val, ZigValue *array_val, size_t start, size_t len, bool is_const, ZigValue *sentinel) { assert(array_val->type->id == ZigTypeIdArray); ZigType *ptr_type = get_pointer_to_type_extra2(g, array_val->type->data.array.child_type, is_const, false, PtrLenUnknown, 0, 0, 0, false, VECTOR_INDEX_NONE, nullptr, sentinel); const_val->special = ConstValSpecialStatic; const_val->type = get_slice_type(g, ptr_type); const_val->data.x_struct.fields = alloc_const_vals_ptrs(g, 2); init_const_ptr_array(g, const_val->data.x_struct.fields[slice_ptr_index], array_val, start, is_const, PtrLenUnknown); init_const_usize(g, const_val->data.x_struct.fields[slice_len_index], len); } ZigValue *create_const_slice(CodeGen *g, ZigValue *array_val, size_t start, size_t len, bool is_const, ZigValue *sentinel) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_slice(g, const_val, array_val, start, len, is_const, sentinel); return const_val; } void init_const_ptr_array(CodeGen *g, ZigValue *const_val, ZigValue *array_val, size_t elem_index, bool is_const, PtrLen ptr_len) { assert(array_val->type->id == ZigTypeIdArray); ZigType *child_type = array_val->type->data.array.child_type; const_val->special = ConstValSpecialStatic; const_val->type = get_pointer_to_type_extra(g, child_type, is_const, false, ptr_len, 0, 0, 0, false); const_val->data.x_ptr.special = ConstPtrSpecialBaseArray; const_val->data.x_ptr.data.base_array.array_val = array_val; const_val->data.x_ptr.data.base_array.elem_index = elem_index; } ZigValue *create_const_ptr_array(CodeGen *g, ZigValue *array_val, size_t elem_index, bool is_const, PtrLen ptr_len) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_ptr_array(g, const_val, array_val, elem_index, is_const, ptr_len); return const_val; } void init_const_ptr_ref(CodeGen *g, ZigValue *const_val, ZigValue *pointee_val, bool is_const) { const_val->special = ConstValSpecialStatic; const_val->type = get_pointer_to_type(g, pointee_val->type, is_const); const_val->data.x_ptr.special = ConstPtrSpecialRef; const_val->data.x_ptr.data.ref.pointee = pointee_val; } ZigValue *create_const_ptr_ref(CodeGen *g, ZigValue *pointee_val, bool is_const) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_ptr_ref(g, const_val, pointee_val, is_const); return const_val; } void init_const_ptr_hard_coded_addr(CodeGen *g, ZigValue *const_val, ZigType *pointee_type, size_t addr, bool is_const) { const_val->special = ConstValSpecialStatic; const_val->type = get_pointer_to_type(g, pointee_type, is_const); const_val->data.x_ptr.special = ConstPtrSpecialHardCodedAddr; const_val->data.x_ptr.data.hard_coded_addr.addr = addr; } ZigValue *create_const_ptr_hard_coded_addr(CodeGen *g, ZigType *pointee_type, size_t addr, bool is_const) { ZigValue *const_val = g->pass1_arena->create<ZigValue>(); init_const_ptr_hard_coded_addr(g, const_val, pointee_type, addr, is_const); return const_val; } ZigValue **alloc_const_vals_ptrs(CodeGen *g, size_t count) { return realloc_const_vals_ptrs(g, nullptr, 0, count); } ZigValue **realloc_const_vals_ptrs(CodeGen *g, ZigValue **ptr, size_t old_count, size_t new_count) { assert(new_count >= old_count); size_t new_item_count = new_count - old_count; ZigValue **result = heap::c_allocator.reallocate(ptr, old_count, new_count); ZigValue *vals = g->pass1_arena->allocate<ZigValue>(new_item_count); for (size_t i = old_count; i < new_count; i += 1) { result[i] = &vals[i - old_count]; } return result; } TypeStructField **alloc_type_struct_fields(size_t count) { return realloc_type_struct_fields(nullptr, 0, count); } TypeStructField **realloc_type_struct_fields(TypeStructField **ptr, size_t old_count, size_t new_count) { assert(new_count >= old_count); size_t new_item_count = new_count - old_count; TypeStructField **result = heap::c_allocator.reallocate(ptr, old_count, new_count); TypeStructField *vals = heap::c_allocator.allocate<TypeStructField>(new_item_count); for (size_t i = old_count; i < new_count; i += 1) { result[i] = &vals[i - old_count]; } return result; } static ZigType *get_async_fn_type(CodeGen *g, ZigType *orig_fn_type) { if (orig_fn_type->data.fn.fn_type_id.cc == CallingConventionAsync) return orig_fn_type; ZigType *fn_type = heap::c_allocator.allocate_nonzero<ZigType>(1); *fn_type = *orig_fn_type; fn_type->data.fn.fn_type_id.cc = CallingConventionAsync; fn_type->llvm_type = nullptr; fn_type->llvm_di_type = nullptr; return fn_type; } // Traverse up to the very top ExprScope, which has children. // We have just arrived at the top from a child. That child, // and its next siblings, do not need to be marked. But the previous // siblings do. // x + (await y) // vs // (await y) + x static void mark_suspension_point(Scope *scope) { ScopeExpr *child_expr_scope = (scope->id == ScopeIdExpr) ? reinterpret_cast<ScopeExpr *>(scope) : nullptr; bool looking_for_exprs = true; for (;;) { scope = scope->parent; switch (scope->id) { case ScopeIdDeferExpr: case ScopeIdDecls: case ScopeIdFnDef: case ScopeIdCompTime: case ScopeIdNoSuspend: case ScopeIdCImport: case ScopeIdSuspend: case ScopeIdTypeOf: return; case ScopeIdVarDecl: case ScopeIdDefer: case ScopeIdBlock: looking_for_exprs = false; continue; case ScopeIdRuntime: continue; case ScopeIdLoop: { ScopeLoop *loop_scope = reinterpret_cast<ScopeLoop *>(scope); if (loop_scope->spill_scope != nullptr) { loop_scope->spill_scope->need_spill = MemoizedBoolTrue; } looking_for_exprs = false; continue; } case ScopeIdExpr: { ScopeExpr *parent_expr_scope = reinterpret_cast<ScopeExpr *>(scope); if (!looking_for_exprs) { if (parent_expr_scope->spill_harder) { parent_expr_scope->need_spill = MemoizedBoolTrue; } // Now we're only looking for a block, to see if it's in a loop (see the case ScopeIdBlock) continue; } if (child_expr_scope != nullptr) { for (size_t i = 0; parent_expr_scope->children_ptr[i] != child_expr_scope; i += 1) { assert(i < parent_expr_scope->children_len); parent_expr_scope->children_ptr[i]->need_spill = MemoizedBoolTrue; } } parent_expr_scope->need_spill = MemoizedBoolTrue; child_expr_scope = parent_expr_scope; continue; } } } } static bool scope_needs_spill(Scope *scope) { ScopeExpr *scope_expr = find_expr_scope(scope); if (scope_expr == nullptr) return false; switch (scope_expr->need_spill) { case MemoizedBoolUnknown: if (scope_needs_spill(scope_expr->base.parent)) { scope_expr->need_spill = MemoizedBoolTrue; return true; } else { scope_expr->need_spill = MemoizedBoolFalse; return false; } case MemoizedBoolFalse: return false; case MemoizedBoolTrue: return true; } zig_unreachable(); } static ZigType *resolve_type_isf(ZigType *ty) { if (ty->id != ZigTypeIdPointer) return ty; InferredStructField *isf = ty->data.pointer.inferred_struct_field; if (isf == nullptr) return ty; TypeStructField *field = find_struct_type_field(isf->inferred_struct_type, isf->field_name); assert(field != nullptr); return field->type_entry; } static Error resolve_async_frame(CodeGen *g, ZigType *frame_type) { Error err; if (frame_type->data.frame.locals_struct != nullptr) return ErrorNone; ZigFn *fn = frame_type->data.frame.fn; assert(!fn->type_entry->data.fn.is_generic); if (frame_type->data.frame.resolve_loop_type != nullptr) { if (!frame_type->data.frame.reported_loop_err) { add_node_error(g, fn->proto_node, buf_sprintf("'%s' depends on itself", buf_ptr(&frame_type->name))); } return ErrorSemanticAnalyzeFail; } switch (fn->anal_state) { case FnAnalStateInvalid: return ErrorSemanticAnalyzeFail; case FnAnalStateComplete: break; case FnAnalStateReady: analyze_fn_body(g, fn); if (fn->anal_state == FnAnalStateInvalid) return ErrorSemanticAnalyzeFail; break; case FnAnalStateProbing: { add_node_error(g, fn->proto_node, buf_sprintf("cannot resolve '%s': function not fully analyzed yet", buf_ptr(&frame_type->name))); return ErrorSemanticAnalyzeFail; } } analyze_fn_async(g, fn, false); if (fn->anal_state == FnAnalStateInvalid) return ErrorSemanticAnalyzeFail; if (!fn_is_async(fn)) { ZigType *fn_type = fn->type_entry; FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id; ZigType *ptr_return_type = get_pointer_to_type(g, fn_type_id->return_type, false); // label (grep this): [fn_frame_struct_layout] ZigList<SrcField> fields = {}; fields.append({"@fn_ptr", g->builtin_types.entry_usize, 0}); fields.append({"@resume_index", g->builtin_types.entry_usize, 0}); fields.append({"@awaiter", g->builtin_types.entry_usize, 0}); fields.append({"@result_ptr_callee", ptr_return_type, 0}); fields.append({"@result_ptr_awaiter", ptr_return_type, 0}); fields.append({"@result", fn_type_id->return_type, 0}); if (codegen_fn_has_err_ret_tracing_arg(g, fn_type_id->return_type)) { ZigType *ptr_to_stack_trace_type = get_pointer_to_type(g, get_stack_trace_type(g), false); fields.append({"@ptr_stack_trace_callee", ptr_to_stack_trace_type, 0}); fields.append({"@ptr_stack_trace_awaiter", ptr_to_stack_trace_type, 0}); fields.append({"@stack_trace", get_stack_trace_type(g), 0}); fields.append({"@instruction_addresses", get_array_type(g, g->builtin_types.entry_usize, stack_trace_ptr_count, nullptr), 0}); } frame_type->data.frame.locals_struct = get_struct_type(g, buf_ptr(&frame_type->name), fields.items, fields.length, target_fn_align(g->zig_target)); frame_type->abi_size = frame_type->data.frame.locals_struct->abi_size; frame_type->abi_align = frame_type->data.frame.locals_struct->abi_align; frame_type->size_in_bits = frame_type->data.frame.locals_struct->size_in_bits; return ErrorNone; } ZigType *fn_type = get_async_fn_type(g, fn->type_entry); if (fn->analyzed_executable.need_err_code_spill) { Stage1AirInstAlloca *alloca_gen = heap::c_allocator.create<Stage1AirInstAlloca>(); alloca_gen->base.id = Stage1AirInstIdAlloca; alloca_gen->base.source_node = fn->proto_node; alloca_gen->base.scope = fn->child_scope; alloca_gen->base.value = g->pass1_arena->create<ZigValue>(); alloca_gen->base.value->type = get_pointer_to_type(g, g->builtin_types.entry_global_error_set, false); alloca_gen->base.ref_count = 1; alloca_gen->name_hint = ""; fn->alloca_gen_list.append(alloca_gen); fn->err_code_spill = &alloca_gen->base; } ZigType *largest_call_frame_type = nullptr; // Later we'll change this to be largest_call_frame_type instead of void. Stage1AirInst *all_calls_alloca = ir_create_alloca(g, &fn->fndef_scope->base, fn->body_node, fn, g->builtin_types.entry_void, "@async_call_frame"); for (size_t i = 0; i < fn->call_list.length; i += 1) { Stage1AirInstCall *call = fn->call_list.at(i); if (call->new_stack != nullptr) { // don't need to allocate a frame for this continue; } ZigFn *callee = call->fn_entry; if (callee == nullptr) { if (call->fn_ref->value->type->data.fn.fn_type_id.cc != CallingConventionAsync) { continue; } add_node_error(g, call->base.source_node, buf_sprintf("function is not comptime-known; @asyncCall required")); return ErrorSemanticAnalyzeFail; } if (callee->body_node == nullptr) { continue; } if (callee->anal_state == FnAnalStateProbing) { ErrorMsg *msg = add_node_error(g, fn->proto_node, buf_sprintf("unable to determine async function frame of '%s'", buf_ptr(&fn->symbol_name))); g->trace_err = add_error_note(g, msg, call->base.source_node, buf_sprintf("analysis of function '%s' depends on the frame", buf_ptr(&callee->symbol_name))); return ErrorSemanticAnalyzeFail; } ZigType *callee_frame_type = get_fn_frame_type(g, callee); frame_type->data.frame.resolve_loop_type = callee_frame_type; frame_type->data.frame.resolve_loop_src_node = call->base.source_node; analyze_fn_body(g, callee); if (callee->anal_state == FnAnalStateInvalid) { frame_type->data.frame.locals_struct = g->builtin_types.entry_invalid; return ErrorSemanticAnalyzeFail; } analyze_fn_async(g, callee, true); if (callee->inferred_async_node == inferred_async_checking) { assert(g->errors.length != 0); frame_type->data.frame.locals_struct = g->builtin_types.entry_invalid; return ErrorSemanticAnalyzeFail; } if (!fn_is_async(callee)) continue; mark_suspension_point(call->base.scope); if ((err = type_resolve(g, callee_frame_type, ResolveStatusSizeKnown))) { return err; } if (largest_call_frame_type == nullptr || callee_frame_type->abi_size > largest_call_frame_type->abi_size) { largest_call_frame_type = callee_frame_type; } call->frame_result_loc = all_calls_alloca; } if (largest_call_frame_type != nullptr) { all_calls_alloca->value->type = get_pointer_to_type(g, largest_call_frame_type, false); } // Since this frame is async, an await might represent a suspend point, and // therefore need to spill. It also needs to mark expr scopes as having to spill. // For example: foo() + await z // The function call result of foo() must be spilled. for (size_t i = 0; i < fn->await_list.length; i += 1) { Stage1AirInstAwait *await = fn->await_list.at(i); if (await->is_nosuspend) { continue; } if (await->base.value->special != ConstValSpecialRuntime) { // Known at comptime. No spill, no suspend. continue; } if (await->target_fn != nullptr) { // we might not need to suspend analyze_fn_async(g, await->target_fn, false); if (await->target_fn->anal_state == FnAnalStateInvalid) { frame_type->data.frame.locals_struct = g->builtin_types.entry_invalid; return ErrorSemanticAnalyzeFail; } if (!fn_is_async(await->target_fn)) { // This await does not represent a suspend point. No spill needed, // and no need to mark ExprScope. continue; } } // This await is a suspend point, but it might not need a spill. // We do need to mark the ExprScope as having a suspend point in it. mark_suspension_point(await->base.scope); if (await->result_loc != nullptr) { // If there's a result location, that is the spill continue; } if (await->base.ref_count == 0) continue; if (!type_has_bits(g, await->base.value->type)) continue; await->result_loc = ir_create_alloca(g, await->base.scope, await->base.source_node, fn, await->base.value->type, ""); } for (size_t block_i = 0; block_i < fn->analyzed_executable.basic_block_list.length; block_i += 1) { Stage1AirBasicBlock *block = fn->analyzed_executable.basic_block_list.at(block_i); for (size_t instr_i = 0; instr_i < block->instruction_list.length; instr_i += 1) { Stage1AirInst *instruction = block->instruction_list.at(instr_i); if (instruction->id == Stage1AirInstIdSuspendFinish) { mark_suspension_point(instruction->scope); } } } // Now that we've marked all the expr scopes that have to spill, we go over the instructions // and spill the relevant ones. for (size_t block_i = 0; block_i < fn->analyzed_executable.basic_block_list.length; block_i += 1) { Stage1AirBasicBlock *block = fn->analyzed_executable.basic_block_list.at(block_i); for (size_t instr_i = 0; instr_i < block->instruction_list.length; instr_i += 1) { Stage1AirInst *instruction = block->instruction_list.at(instr_i); if (instruction->id == Stage1AirInstIdAwait || instruction->id == Stage1AirInstIdVarPtr || instruction->id == Stage1AirInstIdAlloca || instruction->id == Stage1AirInstIdSpillBegin || instruction->id == Stage1AirInstIdSpillEnd) { // This instruction does its own spilling specially, or otherwise doesn't need it. continue; } if (instruction->id == Stage1AirInstIdCast && reinterpret_cast<Stage1AirInstCast *>(instruction)->cast_op == CastOpNoop) { // The IR instruction exists only to change the type according to Zig. No spill needed. continue; } if (instruction->value->special != ConstValSpecialRuntime) continue; if (instruction->ref_count == 0) continue; if ((err = type_resolve(g, instruction->value->type, ResolveStatusZeroBitsKnown))) return ErrorSemanticAnalyzeFail; if (!type_has_bits(g, instruction->value->type)) continue; if (scope_needs_spill(instruction->scope)) { instruction->spill = ir_create_alloca(g, instruction->scope, instruction->source_node, fn, instruction->value->type, ""); } } } FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id; ZigType *ptr_return_type = get_pointer_to_type(g, fn_type_id->return_type, false); // label (grep this): [fn_frame_struct_layout] ZigList<SrcField> fields = {}; fields.append({"@fn_ptr", fn_type, 0}); fields.append({"@resume_index", g->builtin_types.entry_usize, 0}); fields.append({"@awaiter", g->builtin_types.entry_usize, 0}); fields.append({"@result_ptr_callee", ptr_return_type, 0}); fields.append({"@result_ptr_awaiter", ptr_return_type, 0}); fields.append({"@result", fn_type_id->return_type, 0}); if (codegen_fn_has_err_ret_tracing_arg(g, fn_type_id->return_type)) { ZigType *ptr_stack_trace_type = get_pointer_to_type(g, get_stack_trace_type(g), false); fields.append({"@ptr_stack_trace_callee", ptr_stack_trace_type, 0}); fields.append({"@ptr_stack_trace_awaiter", ptr_stack_trace_type, 0}); } for (size_t arg_i = 0; arg_i < fn_type_id->param_count; arg_i += 1) { FnTypeParamInfo *param_info = &fn_type_id->param_info[arg_i]; AstNode *param_decl_node = get_param_decl_node(fn, arg_i); Buf *param_name; bool is_var_args = param_decl_node && param_decl_node->data.param_decl.is_var_args; if (param_decl_node && !is_var_args) { param_name = param_decl_node->data.param_decl.name; } else { param_name = buf_sprintf("@arg%" ZIG_PRI_usize, arg_i); } ZigType *param_type = resolve_type_isf(param_info->type); if ((err = type_resolve(g, param_type, ResolveStatusSizeKnown))) { return err; } fields.append({buf_ptr(param_name), param_type, 0}); } if (codegen_fn_has_err_ret_tracing_stack(g, fn, true)) { fields.append({"@stack_trace", get_stack_trace_type(g), 0}); fields.append({"@instruction_addresses", get_array_type(g, g->builtin_types.entry_usize, stack_trace_ptr_count, nullptr), 0}); } for (size_t alloca_i = 0; alloca_i < fn->alloca_gen_list.length; alloca_i += 1) { Stage1AirInstAlloca *instruction = fn->alloca_gen_list.at(alloca_i); instruction->field_index = SIZE_MAX; ZigType *ptr_type = instruction->base.value->type; assert(ptr_type->id == ZigTypeIdPointer); ZigType *child_type = resolve_type_isf(ptr_type->data.pointer.child_type); if (!type_has_bits(g, child_type)) continue; if (instruction->base.ref_count == 0) continue; if (instruction->base.value->special != ConstValSpecialRuntime) { if (const_ptr_pointee(nullptr, g, instruction->base.value, nullptr)->special != ConstValSpecialRuntime) { continue; } } frame_type->data.frame.resolve_loop_type = child_type; frame_type->data.frame.resolve_loop_src_node = instruction->base.source_node; if ((err = type_resolve(g, child_type, ResolveStatusSizeKnown))) { return err; } const char *name; if (*instruction->name_hint == 0) { name = buf_ptr(buf_sprintf("@local%" ZIG_PRI_usize, alloca_i)); } else { name = buf_ptr(buf_sprintf("%s.%" ZIG_PRI_usize, instruction->name_hint, alloca_i)); } instruction->field_index = fields.length; fields.append({name, child_type, instruction->align}); } frame_type->data.frame.locals_struct = get_struct_type(g, buf_ptr(&frame_type->name), fields.items, fields.length, target_fn_align(g->zig_target)); frame_type->abi_size = frame_type->data.frame.locals_struct->abi_size; frame_type->abi_align = frame_type->data.frame.locals_struct->abi_align; frame_type->size_in_bits = frame_type->data.frame.locals_struct->size_in_bits; if (g->largest_frame_fn == nullptr || frame_type->abi_size > g->largest_frame_fn->frame_type->abi_size) { g->largest_frame_fn = fn; } return ErrorNone; } static Error resolve_pointer_zero_bits(CodeGen *g, ZigType *ty) { Error err; if (ty->abi_size != SIZE_MAX) return ErrorNone; if (ty->data.pointer.resolve_loop_flag_zero_bits) { ty->abi_size = g->builtin_types.entry_usize->abi_size; ty->size_in_bits = g->builtin_types.entry_usize->size_in_bits; ty->abi_align = g->builtin_types.entry_usize->abi_align; return ErrorNone; } ty->data.pointer.resolve_loop_flag_zero_bits = true; ZigType *elem_type; InferredStructField *isf = ty->data.pointer.inferred_struct_field; if (isf != nullptr) { TypeStructField *field = find_struct_type_field(isf->inferred_struct_type, isf->field_name); assert(field != nullptr); if (field->is_comptime) { ty->data.pointer.resolve_loop_flag_zero_bits = false; ty->abi_size = 0; ty->size_in_bits = 0; ty->abi_align = 0; return ErrorNone; } elem_type = field->type_entry; } else { elem_type = ty->data.pointer.child_type; } bool has_bits; if ((err = type_has_bits2(g, elem_type, &has_bits))) return err; ty->data.pointer.resolve_loop_flag_zero_bits = false; if (has_bits) { ty->abi_size = g->builtin_types.entry_usize->abi_size; ty->size_in_bits = g->builtin_types.entry_usize->size_in_bits; ty->abi_align = g->builtin_types.entry_usize->abi_align; } else { ty->abi_size = 0; ty->size_in_bits = 0; ty->abi_align = 0; } return ErrorNone; } Error type_resolve(CodeGen *g, ZigType *ty, ResolveStatus status) { if (type_is_invalid(ty)) return ErrorSemanticAnalyzeFail; switch (status) { case ResolveStatusUnstarted: return ErrorNone; case ResolveStatusBeingInferred: zig_unreachable(); case ResolveStatusInvalid: zig_unreachable(); case ResolveStatusZeroBitsKnown: switch (ty->id) { case ZigTypeIdStruct: return resolve_struct_zero_bits(g, ty); case ZigTypeIdEnum: return resolve_enum_zero_bits(g, ty); case ZigTypeIdUnion: return resolve_union_zero_bits(g, ty); case ZigTypeIdPointer: return resolve_pointer_zero_bits(g, ty); default: return ErrorNone; } case ResolveStatusAlignmentKnown: switch (ty->id) { case ZigTypeIdStruct: return resolve_struct_alignment(g, ty); case ZigTypeIdEnum: return resolve_enum_zero_bits(g, ty); case ZigTypeIdUnion: return resolve_union_alignment(g, ty); case ZigTypeIdFnFrame: return resolve_async_frame(g, ty); case ZigTypeIdPointer: return resolve_pointer_zero_bits(g, ty); default: return ErrorNone; } case ResolveStatusSizeKnown: switch (ty->id) { case ZigTypeIdStruct: return resolve_struct_type(g, ty); case ZigTypeIdEnum: return resolve_enum_zero_bits(g, ty); case ZigTypeIdUnion: return resolve_union_type(g, ty); case ZigTypeIdFnFrame: return resolve_async_frame(g, ty); case ZigTypeIdPointer: return resolve_pointer_zero_bits(g, ty); default: return ErrorNone; } case ResolveStatusLLVMFwdDecl: case ResolveStatusLLVMFull: resolve_llvm_types(g, ty, status); return ErrorNone; } zig_unreachable(); } bool ir_get_var_is_comptime(ZigVar *var) { if (var->is_comptime_memoized) return var->is_comptime_memoized_value; var->is_comptime_memoized = true; // The is_comptime field can be left null, which means not comptime. if (var->is_comptime == nullptr) { var->is_comptime_memoized_value = false; return var->is_comptime_memoized_value; } // When the is_comptime field references an instruction that has to get analyzed, this // is the value. if (var->is_comptime->child != nullptr) { assert(var->is_comptime->child->value->type->id == ZigTypeIdBool); var->is_comptime_memoized_value = var->is_comptime->child->value->data.x_bool; var->is_comptime = nullptr; return var->is_comptime_memoized_value; } // As an optimization, is_comptime values which are constant are allowed // to be omitted from analysis. In this case, there is no child instruction // and we simply look at the unanalyzed const parent instruction. assert(var->is_comptime->id == Stage1ZirInstIdConst); Stage1ZirInstConst *const_inst = reinterpret_cast<Stage1ZirInstConst *>(var->is_comptime); assert(const_inst->value->type->id == ZigTypeIdBool); var->is_comptime_memoized_value = const_inst->value->data.x_bool; var->is_comptime = nullptr; return var->is_comptime_memoized_value; } bool const_values_equal_ptr(ZigValue *a, ZigValue *b) { if (a->data.x_ptr.special != b->data.x_ptr.special) return false; switch (a->data.x_ptr.special) { case ConstPtrSpecialInvalid: zig_unreachable(); case ConstPtrSpecialRef: if (a->data.x_ptr.data.ref.pointee != b->data.x_ptr.data.ref.pointee) return false; return true; case ConstPtrSpecialBaseArray: case ConstPtrSpecialSubArray: if (a->data.x_ptr.data.base_array.array_val != b->data.x_ptr.data.base_array.array_val) { return false; } if (a->data.x_ptr.data.base_array.elem_index != b->data.x_ptr.data.base_array.elem_index) return false; return true; case ConstPtrSpecialBaseStruct: if (a->data.x_ptr.data.base_struct.struct_val != b->data.x_ptr.data.base_struct.struct_val) { return false; } if (a->data.x_ptr.data.base_struct.field_index != b->data.x_ptr.data.base_struct.field_index) return false; return true; case ConstPtrSpecialBaseErrorUnionCode: if (a->data.x_ptr.data.base_err_union_code.err_union_val != b->data.x_ptr.data.base_err_union_code.err_union_val) { return false; } return true; case ConstPtrSpecialBaseErrorUnionPayload: if (a->data.x_ptr.data.base_err_union_payload.err_union_val != b->data.x_ptr.data.base_err_union_payload.err_union_val) { return false; } return true; case ConstPtrSpecialBaseOptionalPayload: if (a->data.x_ptr.data.base_optional_payload.optional_val != b->data.x_ptr.data.base_optional_payload.optional_val) { return false; } return true; case ConstPtrSpecialHardCodedAddr: if (a->data.x_ptr.data.hard_coded_addr.addr != b->data.x_ptr.data.hard_coded_addr.addr) return false; return true; case ConstPtrSpecialDiscard: return true; case ConstPtrSpecialFunction: return a->data.x_ptr.data.fn.fn_entry == b->data.x_ptr.data.fn.fn_entry; case ConstPtrSpecialNull: return true; } zig_unreachable(); } static bool const_values_equal_array(CodeGen *g, ZigValue *a, ZigValue *b, size_t len) { if (a->data.x_array.special == ConstArraySpecialUndef && b->data.x_array.special == ConstArraySpecialUndef) { return true; } if (a->data.x_array.special == ConstArraySpecialUndef || b->data.x_array.special == ConstArraySpecialUndef) { return false; } if (a->data.x_array.special == ConstArraySpecialBuf && b->data.x_array.special == ConstArraySpecialBuf) { return buf_eql_buf(a->data.x_array.data.s_buf, b->data.x_array.data.s_buf); } expand_undef_array(g, a); expand_undef_array(g, b); ZigValue *a_elems = a->data.x_array.data.s_none.elements; ZigValue *b_elems = b->data.x_array.data.s_none.elements; for (size_t i = 0; i < len; i += 1) { if (!const_values_equal(g, &a_elems[i], &b_elems[i])) return false; } return true; } bool const_values_equal(CodeGen *g, ZigValue *a, ZigValue *b) { if (a->type->id != b->type->id) return false; if (a->type == b->type) { switch (type_has_one_possible_value(g, a->type)) { case OnePossibleValueInvalid: zig_unreachable(); case OnePossibleValueNo: break; case OnePossibleValueYes: return true; } } if (a->special == ConstValSpecialUndef || b->special == ConstValSpecialUndef) { return a->special == b->special; } assert(a->special == ConstValSpecialStatic); assert(b->special == ConstValSpecialStatic); switch (a->type->id) { case ZigTypeIdOpaque: zig_unreachable(); case ZigTypeIdEnum: return bigint_cmp(&a->data.x_enum_tag, &b->data.x_enum_tag) == CmpEQ; case ZigTypeIdUnion: { ConstUnionValue *union1 = &a->data.x_union; ConstUnionValue *union2 = &b->data.x_union; if (bigint_cmp(&union1->tag, &union2->tag) == CmpEQ) { TypeUnionField *field = find_union_field_by_tag(a->type, &union1->tag); assert(field != nullptr); assert(find_union_field_by_tag(a->type, &union2->tag) != nullptr); return const_values_equal(g, union1->payload, union2->payload); } return false; } case ZigTypeIdMetaType: return a->data.x_type == b->data.x_type; case ZigTypeIdVoid: case ZigTypeIdUndefined: case ZigTypeIdNull: return true; case ZigTypeIdErrorSet: return a->data.x_err_set->value == b->data.x_err_set->value; case ZigTypeIdBool: return a->data.x_bool == b->data.x_bool; case ZigTypeIdFloat: assert(a->type->data.floating.bit_count == b->type->data.floating.bit_count); switch (a->type->data.floating.bit_count) { case 16: return f16_eq(a->data.x_f16, b->data.x_f16); case 32: return a->data.x_f32 == b->data.x_f32; case 64: return a->data.x_f64 == b->data.x_f64; case 128: return f128M_eq(&a->data.x_f128, &b->data.x_f128); default: zig_unreachable(); } case ZigTypeIdComptimeFloat: return bigfloat_cmp(&a->data.x_bigfloat, &b->data.x_bigfloat) == CmpEQ; case ZigTypeIdInt: case ZigTypeIdComptimeInt: return bigint_cmp(&a->data.x_bigint, &b->data.x_bigint) == CmpEQ; case ZigTypeIdEnumLiteral: return buf_eql_buf(a->data.x_enum_literal, b->data.x_enum_literal); case ZigTypeIdPointer: case ZigTypeIdFn: return const_values_equal_ptr(a, b); case ZigTypeIdVector: assert(a->type->data.vector.len == b->type->data.vector.len); return const_values_equal_array(g, a, b, a->type->data.vector.len); case ZigTypeIdArray: assert(a->type->data.array.len == b->type->data.array.len); return const_values_equal_array(g, a, b, a->type->data.array.len); case ZigTypeIdStruct: for (size_t i = 0; i < a->type->data.structure.src_field_count; i += 1) { if (a->type->data.structure.fields[i]->is_comptime) { // The values of comptime struct fields are part of the // type, not the value, so they do not participate in equality // or hash of comptime values. continue; } ZigValue *field_a = a->data.x_struct.fields[i]; ZigValue *field_b = b->data.x_struct.fields[i]; if (!const_values_equal(g, field_a, field_b)) return false; } return true; case ZigTypeIdFnFrame: zig_panic("TODO: const_values_equal ZigTypeIdFnFrame"); case ZigTypeIdAnyFrame: zig_panic("TODO: const_values_equal ZigTypeIdAnyFrame"); case ZigTypeIdOptional: if (get_src_ptr_type(a->type) != nullptr) return const_values_equal_ptr(a, b); if (a->data.x_optional == nullptr || b->data.x_optional == nullptr) { return (a->data.x_optional == nullptr && b->data.x_optional == nullptr); } else { return const_values_equal(g, a->data.x_optional, b->data.x_optional); } case ZigTypeIdErrorUnion: { bool a_is_err = a->data.x_err_union.error_set->data.x_err_set != nullptr; bool b_is_err = b->data.x_err_union.error_set->data.x_err_set != nullptr; if (a_is_err != b_is_err) return false; if (a_is_err) { return const_values_equal(g, a->data.x_err_union.error_set, b->data.x_err_union.error_set); } else { return const_values_equal(g, a->data.x_err_union.payload, b->data.x_err_union.payload); } } case ZigTypeIdBoundFn: case ZigTypeIdInvalid: case ZigTypeIdUnreachable: zig_unreachable(); } zig_unreachable(); } void eval_min_max_value_int(CodeGen *g, ZigType *int_type, BigInt *bigint, bool is_max) { assert(int_type->id == ZigTypeIdInt); if (int_type->data.integral.bit_count == 0) { bigint_init_unsigned(bigint, 0); return; } if (is_max) { // is_signed=true (1 << (bit_count - 1)) - 1 // is_signed=false (1 << (bit_count - 0)) - 1 BigInt one = {0}; bigint_init_unsigned(&one, 1); size_t shift_amt = int_type->data.integral.bit_count - (int_type->data.integral.is_signed ? 1 : 0); BigInt bit_count_bi = {0}; bigint_init_unsigned(&bit_count_bi, shift_amt); BigInt shifted_bi = {0}; bigint_shl(&shifted_bi, &one, &bit_count_bi); bigint_sub(bigint, &shifted_bi, &one); } else if (int_type->data.integral.is_signed) { // - (1 << (bit_count - 1)) BigInt one = {0}; bigint_init_unsigned(&one, 1); BigInt bit_count_bi = {0}; bigint_init_unsigned(&bit_count_bi, int_type->data.integral.bit_count - 1); BigInt shifted_bi = {0}; bigint_shl(&shifted_bi, &one, &bit_count_bi); bigint_negate(bigint, &shifted_bi); } else { bigint_init_unsigned(bigint, 0); } } void eval_min_max_value(CodeGen *g, ZigType *type_entry, ZigValue *const_val, bool is_max) { if (type_entry->id == ZigTypeIdInt) { const_val->special = ConstValSpecialStatic; eval_min_max_value_int(g, type_entry, &const_val->data.x_bigint, is_max); } else if (type_entry->id == ZigTypeIdBool) { const_val->special = ConstValSpecialStatic; const_val->data.x_bool = is_max; } else if (type_entry->id == ZigTypeIdVoid) { // nothing to do } else { zig_unreachable(); } } static void render_const_val_ptr(CodeGen *g, Buf *buf, ZigValue *const_val, ZigType *type_entry) { if (type_entry->id == ZigTypeIdPointer && type_entry->data.pointer.child_type->id == ZigTypeIdOpaque) { buf_append_buf(buf, &type_entry->name); return; } switch (const_val->data.x_ptr.special) { case ConstPtrSpecialInvalid: zig_unreachable(); case ConstPtrSpecialRef: case ConstPtrSpecialBaseStruct: case ConstPtrSpecialBaseErrorUnionCode: case ConstPtrSpecialBaseErrorUnionPayload: case ConstPtrSpecialBaseOptionalPayload: buf_appendf(buf, "*"); // TODO we need a source node for const_ptr_pointee because it can generate compile errors render_const_value(g, buf, const_ptr_pointee(nullptr, g, const_val, nullptr)); return; case ConstPtrSpecialBaseArray: case ConstPtrSpecialSubArray: buf_appendf(buf, "*"); // TODO we need a source node for const_ptr_pointee because it can generate compile errors render_const_value(g, buf, const_ptr_pointee(nullptr, g, const_val, nullptr)); return; case ConstPtrSpecialHardCodedAddr: buf_appendf(buf, "(%s)(%" ZIG_PRI_x64 ")", buf_ptr(&type_entry->name), const_val->data.x_ptr.data.hard_coded_addr.addr); return; case ConstPtrSpecialDiscard: buf_append_str(buf, "*_"); return; case ConstPtrSpecialFunction: { ZigFn *fn_entry = const_val->data.x_ptr.data.fn.fn_entry; buf_appendf(buf, "@ptrCast(%s, %s)", buf_ptr(&const_val->type->name), buf_ptr(&fn_entry->symbol_name)); return; } case ConstPtrSpecialNull: buf_append_str(buf, "null"); return; } zig_unreachable(); } static void render_const_val_err_set(CodeGen *g, Buf *buf, ZigValue *const_val, ZigType *type_entry) { if (const_val->data.x_err_set == nullptr) { buf_append_str(buf, "null"); } else { buf_appendf(buf, "%s.%s", buf_ptr(&type_entry->name), buf_ptr(&const_val->data.x_err_set->name)); } } static void render_const_val_array(CodeGen *g, Buf *buf, Buf *type_name, ZigValue *const_val, uint64_t start, uint64_t len) { ConstArrayValue *array = &const_val->data.x_array; switch (array->special) { case ConstArraySpecialUndef: buf_append_str(buf, "undefined"); return; case ConstArraySpecialBuf: { Buf *array_buf = array->data.s_buf; const char *base = &buf_ptr(array_buf)[start]; assert(start + len <= buf_len(array_buf)); buf_append_char(buf, '"'); for (size_t i = 0; i < len; i += 1) { uint8_t c = base[i]; if (c == '"') { buf_append_str(buf, "\\\""); } else { buf_append_char(buf, c); } } buf_append_char(buf, '"'); return; } case ConstArraySpecialNone: { assert(start + len <= const_val->type->data.array.len); ZigValue *base = &array->data.s_none.elements[start]; assert(len == 0 || base != nullptr); buf_appendf(buf, "%s{", buf_ptr(type_name)); for (uint64_t i = 0; i < len; i += 1) { if (i != 0) buf_appendf(buf, ","); render_const_value(g, buf, &base[i]); } buf_appendf(buf, "}"); return; } } zig_unreachable(); } void render_const_value(CodeGen *g, Buf *buf, ZigValue *const_val) { if (const_val == nullptr) { buf_appendf(buf, "(invalid nullptr value)"); return; } switch (const_val->special) { case ConstValSpecialRuntime: buf_appendf(buf, "(runtime value)"); return; case ConstValSpecialLazy: buf_appendf(buf, "(lazy value)"); return; case ConstValSpecialUndef: buf_appendf(buf, "undefined"); return; case ConstValSpecialStatic: break; } assert(const_val->type); ZigType *type_entry = const_val->type; switch (type_entry->id) { case ZigTypeIdOpaque: zig_unreachable(); case ZigTypeIdInvalid: buf_appendf(buf, "(invalid)"); return; case ZigTypeIdVoid: buf_appendf(buf, "{}"); return; case ZigTypeIdComptimeFloat: bigfloat_append_buf(buf, &const_val->data.x_bigfloat); return; case ZigTypeIdFloat: switch (type_entry->data.floating.bit_count) { case 16: buf_appendf(buf, "%f", zig_f16_to_double(const_val->data.x_f16)); return; case 32: buf_appendf(buf, "%f", const_val->data.x_f32); return; case 64: buf_appendf(buf, "%f", const_val->data.x_f64); return; case 128: { const size_t extra_len = 100; size_t old_len = buf_len(buf); buf_resize(buf, old_len + extra_len); float64_t f64_value = f128M_to_f64(&const_val->data.x_f128); double double_value; memcpy(&double_value, &f64_value, sizeof(double)); // TODO actual f128 printing to decimal int len = snprintf(buf_ptr(buf) + old_len, extra_len, "%f", double_value); assert(len > 0); buf_resize(buf, old_len + len); return; } default: zig_unreachable(); } case ZigTypeIdComptimeInt: case ZigTypeIdInt: bigint_append_buf(buf, &const_val->data.x_bigint, 10); return; case ZigTypeIdEnumLiteral: buf_append_buf(buf, const_val->data.x_enum_literal); return; case ZigTypeIdMetaType: buf_appendf(buf, "%s", buf_ptr(&const_val->data.x_type->name)); return; case ZigTypeIdUnreachable: buf_appendf(buf, "unreachable"); return; case ZigTypeIdBool: { const char *value = const_val->data.x_bool ? "true" : "false"; buf_appendf(buf, "%s", value); return; } case ZigTypeIdFn: { assert(const_val->data.x_ptr.mut == ConstPtrMutComptimeConst); assert(const_val->data.x_ptr.special == ConstPtrSpecialFunction); ZigFn *fn_entry = const_val->data.x_ptr.data.fn.fn_entry; buf_appendf(buf, "%s", buf_ptr(&fn_entry->symbol_name)); return; } case ZigTypeIdPointer: return render_const_val_ptr(g, buf, const_val, type_entry); case ZigTypeIdArray: { uint64_t len = type_entry->data.array.len; render_const_val_array(g, buf, &type_entry->name, const_val, 0, len); return; } case ZigTypeIdVector: { uint32_t len = type_entry->data.vector.len; render_const_val_array(g, buf, &type_entry->name, const_val, 0, len); return; } case ZigTypeIdNull: { buf_appendf(buf, "null"); return; } case ZigTypeIdUndefined: { buf_appendf(buf, "undefined"); return; } case ZigTypeIdOptional: { ZigType *src_ptr_type = get_src_ptr_type(const_val->type); if (src_ptr_type != nullptr) { if (src_ptr_type->id == ZigTypeIdPointer && !optional_value_is_null(const_val)) { ZigValue tmp = {}; copy_const_val(g, &tmp, const_val); tmp.type = type_entry->data.maybe.child_type; return render_const_val_ptr(g, buf, &tmp, tmp.type); } return render_const_val_ptr(g, buf, const_val, type_entry->data.maybe.child_type); } if (type_entry->data.maybe.child_type->id == ZigTypeIdErrorSet) return render_const_val_err_set(g, buf, const_val, type_entry->data.maybe.child_type); if (const_val->data.x_optional) { render_const_value(g, buf, const_val->data.x_optional); } else { buf_appendf(buf, "null"); } return; } case ZigTypeIdBoundFn: { ZigFn *fn_entry = const_val->data.x_bound_fn.fn; buf_appendf(buf, "(bound fn %s)", buf_ptr(&fn_entry->symbol_name)); return; } case ZigTypeIdStruct: { if (is_slice(type_entry)) { ZigValue *len_val = const_val->data.x_struct.fields[slice_len_index]; size_t len = bigint_as_usize(&len_val->data.x_bigint); ZigValue *ptr_val = const_val->data.x_struct.fields[slice_ptr_index]; if (ptr_val->special == ConstValSpecialUndef) { assert(len == 0); buf_appendf(buf, "((%s)(undefined))[0..0]", buf_ptr(&type_entry->name)); return; } assert(ptr_val->data.x_ptr.special == ConstPtrSpecialBaseArray); ZigValue *array = ptr_val->data.x_ptr.data.base_array.array_val; size_t start = ptr_val->data.x_ptr.data.base_array.elem_index; if (array->special == ConstValSpecialUndef) buf_append_str(buf, "undefined"); else render_const_val_array(g, buf, &type_entry->name, array, start, len); } else { buf_appendf(buf, "(struct %s constant)", buf_ptr(&type_entry->name)); } return; } case ZigTypeIdEnum: { TypeEnumField *field = find_enum_field_by_tag(type_entry, &const_val->data.x_enum_tag); if(field != nullptr){ buf_appendf(buf, "%s.%s", buf_ptr(&type_entry->name), buf_ptr(field->name)); } else { // untagged value in a non-exhaustive enum buf_appendf(buf, "%s.(", buf_ptr(&type_entry->name)); bigint_append_buf(buf, &const_val->data.x_enum_tag, 10); buf_appendf(buf, ")"); } return; } case ZigTypeIdErrorUnion: { buf_appendf(buf, "%s(", buf_ptr(&type_entry->name)); ErrorTableEntry *err_set = const_val->data.x_err_union.error_set->data.x_err_set; if (err_set == nullptr) { render_const_value(g, buf, const_val->data.x_err_union.payload); } else { buf_appendf(buf, "%s.%s", buf_ptr(&type_entry->data.error_union.err_set_type->name), buf_ptr(&err_set->name)); } buf_appendf(buf, ")"); return; } case ZigTypeIdUnion: { const BigInt *tag = &const_val->data.x_union.tag; TypeUnionField *field = find_union_field_by_tag(type_entry, tag); buf_appendf(buf, "%s { .%s = ", buf_ptr(&type_entry->name), buf_ptr(field->name)); render_const_value(g, buf, const_val->data.x_union.payload); buf_append_str(buf, "}"); return; } case ZigTypeIdErrorSet: return render_const_val_err_set(g, buf, const_val, type_entry); case ZigTypeIdFnFrame: buf_appendf(buf, "(TODO: async function frame value)"); return; case ZigTypeIdAnyFrame: buf_appendf(buf, "(TODO: anyframe value)"); return; } zig_unreachable(); } ZigType *make_int_type(CodeGen *g, bool is_signed, uint32_t size_in_bits) { assert(size_in_bits <= 65535); ZigType *entry = new_type_table_entry(ZigTypeIdInt); entry->size_in_bits = size_in_bits; if (size_in_bits != 0) { entry->llvm_type = LLVMIntType(size_in_bits); entry->abi_size = LLVMABISizeOfType(g->target_data_ref, entry->llvm_type); entry->abi_align = LLVMABIAlignmentOfType(g->target_data_ref, entry->llvm_type); if (size_in_bits >= 128 && entry->abi_align < 16) { // Override the incorrect alignment reported by LLVM. Clang does this as well. // On x86_64 there are some instructions like CMPXCHG16B which require this. // On all targets, integers 128 bits and above have ABI alignment of 16. // However for some targets, LLVM incorrectly reports this as 8. // See: https://github.com/ziglang/zig/issues/2987 entry->abi_align = 16; } } const char u_or_i = is_signed ? 'i' : 'u'; buf_resize(&entry->name, 0); buf_appendf(&entry->name, "%c%" PRIu32, u_or_i, size_in_bits); entry->data.integral.is_signed = is_signed; entry->data.integral.bit_count = size_in_bits; return entry; } uint32_t type_id_hash(TypeId const *x) { uint32_t hash = hash_combine(HASH_INIT, &x->id); switch (x->id) { case ZigTypeIdInvalid: case ZigTypeIdOpaque: case ZigTypeIdMetaType: case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdUnreachable: case ZigTypeIdFloat: case ZigTypeIdStruct: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdOptional: case ZigTypeIdErrorSet: case ZigTypeIdEnum: case ZigTypeIdUnion: case ZigTypeIdFn: case ZigTypeIdBoundFn: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: zig_unreachable(); case ZigTypeIdErrorUnion: hash = hash_combine(hash, &x->data.error_union.err_set_type); hash = hash_combine(hash, &x->data.error_union.payload_type); return hash; case ZigTypeIdPointer: hash = hash_combine(hash, &x->data.pointer.child_type); hash = hash_combine(hash, &x->data.pointer.ptr_len); hash = hash_combine(hash, &x->data.pointer.is_const); hash = hash_combine(hash, &x->data.pointer.is_volatile); hash = hash_combine(hash, &x->data.pointer.allow_zero); hash = hash_combine(hash, &x->data.pointer.alignment); hash = hash_combine(hash, &x->data.pointer.bit_offset_in_host); hash = hash_combine(hash, &x->data.pointer.vector_index); hash = hash_combine(hash, &x->data.pointer.host_int_bytes); if (x->data.pointer.sentinel != nullptr) { hash = hash_combine_const_val(hash, x->data.pointer.sentinel); } if (x->data.pointer.inferred_struct_field) { hash = hash_combine(hash, &x->data.pointer.inferred_struct_field->inferred_struct_type); hash = hash_combine_buf(hash, x->data.pointer.inferred_struct_field->field_name); } return hash; case ZigTypeIdArray: hash = hash_combine(hash, &x->data.array.child_type); hash = hash_combine(hash, &x->data.array.size); if (x->data.array.sentinel != nullptr) { hash = hash_combine_const_val(hash, x->data.array.sentinel); } return hash; case ZigTypeIdInt: hash = hash_combine(hash, &x->data.integer.is_signed); hash = hash_combine(hash, &x->data.integer.bit_count); return hash; case ZigTypeIdVector: hash = hash_combine(hash, &x->data.vector.elem_type); hash = hash_combine(hash, &x->data.vector.len); return hash; } zig_unreachable(); } bool type_id_eql(TypeId const *a, TypeId const *b) { if (a->id != b->id) return false; switch (a->id) { case ZigTypeIdInvalid: case ZigTypeIdMetaType: case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdUnreachable: case ZigTypeIdFloat: case ZigTypeIdStruct: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdOptional: case ZigTypeIdErrorSet: case ZigTypeIdEnum: case ZigTypeIdUnion: case ZigTypeIdFn: case ZigTypeIdBoundFn: case ZigTypeIdOpaque: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: zig_unreachable(); case ZigTypeIdErrorUnion: return a->data.error_union.err_set_type == b->data.error_union.err_set_type && a->data.error_union.payload_type == b->data.error_union.payload_type; case ZigTypeIdPointer: return a->data.pointer.child_type == b->data.pointer.child_type && a->data.pointer.ptr_len == b->data.pointer.ptr_len && a->data.pointer.is_const == b->data.pointer.is_const && a->data.pointer.is_volatile == b->data.pointer.is_volatile && a->data.pointer.allow_zero == b->data.pointer.allow_zero && a->data.pointer.alignment == b->data.pointer.alignment && a->data.pointer.bit_offset_in_host == b->data.pointer.bit_offset_in_host && a->data.pointer.vector_index == b->data.pointer.vector_index && a->data.pointer.host_int_bytes == b->data.pointer.host_int_bytes && ( a->data.pointer.sentinel == b->data.pointer.sentinel || (a->data.pointer.sentinel != nullptr && b->data.pointer.sentinel != nullptr && const_values_equal(a->data.pointer.codegen, a->data.pointer.sentinel, b->data.pointer.sentinel)) ) && ( a->data.pointer.inferred_struct_field == b->data.pointer.inferred_struct_field || (a->data.pointer.inferred_struct_field != nullptr && b->data.pointer.inferred_struct_field != nullptr && a->data.pointer.inferred_struct_field->inferred_struct_type == b->data.pointer.inferred_struct_field->inferred_struct_type && buf_eql_buf(a->data.pointer.inferred_struct_field->field_name, b->data.pointer.inferred_struct_field->field_name)) ); case ZigTypeIdArray: return a->data.array.child_type == b->data.array.child_type && a->data.array.size == b->data.array.size && ( a->data.array.sentinel == b->data.array.sentinel || (a->data.array.sentinel != nullptr && b->data.array.sentinel != nullptr && const_values_equal(a->data.array.codegen, a->data.array.sentinel, b->data.array.sentinel)) ); case ZigTypeIdInt: return a->data.integer.is_signed == b->data.integer.is_signed && a->data.integer.bit_count == b->data.integer.bit_count; case ZigTypeIdVector: return a->data.vector.elem_type == b->data.vector.elem_type && a->data.vector.len == b->data.vector.len; } zig_unreachable(); } uint32_t zig_llvm_fn_key_hash(ZigLLVMFnKey const *x) { switch (x->id) { case ZigLLVMFnIdCtz: return (uint32_t)(x->data.ctz.bit_count) * (uint32_t)810453934 + (uint32_t)(x->data.ctz.vector_len) * (((uint32_t)x->id << 5) + 1025); case ZigLLVMFnIdClz: return (uint32_t)(x->data.clz.bit_count) * (uint32_t)2428952817 + (uint32_t)(x->data.clz.vector_len) * (((uint32_t)x->id << 5) + 1025); case ZigLLVMFnIdPopCount: return (uint32_t)(x->data.pop_count.bit_count) * (uint32_t)101195049 + (uint32_t)(x->data.pop_count.vector_len) * (((uint32_t)x->id << 5) + 1025); case ZigLLVMFnIdFloatOp: return (uint32_t)(x->data.floating.bit_count) * ((uint32_t)x->id + 1025) + (uint32_t)(x->data.floating.vector_len) * (((uint32_t)x->id << 5) + 1025) + (uint32_t)(x->data.floating.op) * (uint32_t)43789879; case ZigLLVMFnIdFMA: return (uint32_t)(x->data.floating.bit_count) * ((uint32_t)x->id + 1025) + (uint32_t)(x->data.floating.vector_len) * (((uint32_t)x->id << 5) + 1025); case ZigLLVMFnIdBswap: return (uint32_t)(x->data.bswap.bit_count) * ((uint32_t)3661994335) + (uint32_t)(x->data.bswap.vector_len) * (((uint32_t)x->id << 5) + 1025); case ZigLLVMFnIdBitReverse: return (uint32_t)(x->data.bit_reverse.bit_count) * (uint32_t)2621398431; case ZigLLVMFnIdOverflowArithmetic: return ((uint32_t)(x->data.overflow_arithmetic.bit_count) * 87135777) + ((uint32_t)(x->data.overflow_arithmetic.add_sub_mul) * 31640542) + ((uint32_t)(x->data.overflow_arithmetic.is_signed) ? 1062315172 : 314955820) + x->data.overflow_arithmetic.vector_len * 1435156945; } zig_unreachable(); } bool zig_llvm_fn_key_eql(ZigLLVMFnKey const *a, ZigLLVMFnKey const *b) { if (a->id != b->id) return false; switch (a->id) { case ZigLLVMFnIdCtz: return a->data.ctz.bit_count == b->data.ctz.bit_count; case ZigLLVMFnIdClz: return a->data.clz.bit_count == b->data.clz.bit_count; case ZigLLVMFnIdPopCount: return a->data.pop_count.bit_count == b->data.pop_count.bit_count; case ZigLLVMFnIdBswap: return a->data.bswap.bit_count == b->data.bswap.bit_count && a->data.bswap.vector_len == b->data.bswap.vector_len; case ZigLLVMFnIdBitReverse: return a->data.bit_reverse.bit_count == b->data.bit_reverse.bit_count; case ZigLLVMFnIdFloatOp: return a->data.floating.bit_count == b->data.floating.bit_count && a->data.floating.vector_len == b->data.floating.vector_len && a->data.floating.op == b->data.floating.op; case ZigLLVMFnIdFMA: return a->data.floating.bit_count == b->data.floating.bit_count && a->data.floating.vector_len == b->data.floating.vector_len; case ZigLLVMFnIdOverflowArithmetic: return (a->data.overflow_arithmetic.bit_count == b->data.overflow_arithmetic.bit_count) && (a->data.overflow_arithmetic.add_sub_mul == b->data.overflow_arithmetic.add_sub_mul) && (a->data.overflow_arithmetic.is_signed == b->data.overflow_arithmetic.is_signed) && (a->data.overflow_arithmetic.vector_len == b->data.overflow_arithmetic.vector_len); } zig_unreachable(); } static void init_const_undefined(CodeGen *g, ZigValue *const_val) { Error err; ZigType *wanted_type = const_val->type; if (wanted_type->id == ZigTypeIdArray) { const_val->special = ConstValSpecialStatic; const_val->data.x_array.special = ConstArraySpecialUndef; } else if (wanted_type->id == ZigTypeIdStruct) { if ((err = type_resolve(g, wanted_type, ResolveStatusZeroBitsKnown))) { return; } const_val->special = ConstValSpecialStatic; size_t field_count = wanted_type->data.structure.src_field_count; const_val->data.x_struct.fields = alloc_const_vals_ptrs(g, field_count); for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = wanted_type->data.structure.fields[i]; if (field->is_comptime) { // Comptime fields are part of the type, and do not need to // be initialized. continue; } ZigValue *field_val = const_val->data.x_struct.fields[i]; field_val->type = resolve_struct_field_type(g, wanted_type->data.structure.fields[i]); assert(field_val->type); init_const_undefined(g, field_val); field_val->parent.id = ConstParentIdStruct; field_val->parent.data.p_struct.struct_val = const_val; field_val->parent.data.p_struct.field_index = i; } } else { const_val->special = ConstValSpecialUndef; } } void expand_undef_struct(CodeGen *g, ZigValue *const_val) { if (const_val->special == ConstValSpecialUndef) { init_const_undefined(g, const_val); } } // Canonicalize the array value as ConstArraySpecialNone void expand_undef_array(CodeGen *g, ZigValue *const_val) { size_t elem_count; ZigType *elem_type; if (const_val->type->id == ZigTypeIdArray) { elem_count = const_val->type->data.array.len; elem_type = const_val->type->data.array.child_type; } else if (const_val->type->id == ZigTypeIdVector) { elem_count = const_val->type->data.vector.len; elem_type = const_val->type->data.vector.elem_type; } else { zig_unreachable(); } if (const_val->special == ConstValSpecialUndef) { const_val->special = ConstValSpecialStatic; const_val->data.x_array.special = ConstArraySpecialUndef; } switch (const_val->data.x_array.special) { case ConstArraySpecialNone: return; case ConstArraySpecialUndef: { const_val->data.x_array.special = ConstArraySpecialNone; const_val->data.x_array.data.s_none.elements = g->pass1_arena->allocate<ZigValue>(elem_count); for (size_t i = 0; i < elem_count; i += 1) { ZigValue *element_val = &const_val->data.x_array.data.s_none.elements[i]; element_val->type = elem_type; init_const_undefined(g, element_val); element_val->parent.id = ConstParentIdArray; element_val->parent.data.p_array.array_val = const_val; element_val->parent.data.p_array.elem_index = i; } return; } case ConstArraySpecialBuf: { Buf *buf = const_val->data.x_array.data.s_buf; // If we're doing this it means that we are potentially modifying the data, // so we can't have it be in the string literals table g->string_literals_table.maybe_remove(buf); const_val->data.x_array.special = ConstArraySpecialNone; assert(elem_count == buf_len(buf)); const_val->data.x_array.data.s_none.elements = g->pass1_arena->allocate<ZigValue>(elem_count); for (size_t i = 0; i < elem_count; i += 1) { ZigValue *this_char = &const_val->data.x_array.data.s_none.elements[i]; this_char->special = ConstValSpecialStatic; this_char->type = g->builtin_types.entry_u8; bigint_init_unsigned(&this_char->data.x_bigint, (uint8_t)buf_ptr(buf)[i]); this_char->parent.id = ConstParentIdArray; this_char->parent.data.p_array.array_val = const_val; this_char->parent.data.p_array.elem_index = i; } return; } } zig_unreachable(); } static const ZigTypeId all_type_ids[] = { ZigTypeIdMetaType, ZigTypeIdVoid, ZigTypeIdBool, ZigTypeIdUnreachable, ZigTypeIdInt, ZigTypeIdFloat, ZigTypeIdPointer, ZigTypeIdArray, ZigTypeIdStruct, ZigTypeIdComptimeFloat, ZigTypeIdComptimeInt, ZigTypeIdUndefined, ZigTypeIdNull, ZigTypeIdOptional, ZigTypeIdErrorUnion, ZigTypeIdErrorSet, ZigTypeIdEnum, ZigTypeIdUnion, ZigTypeIdFn, ZigTypeIdBoundFn, ZigTypeIdOpaque, ZigTypeIdFnFrame, ZigTypeIdAnyFrame, ZigTypeIdVector, ZigTypeIdEnumLiteral, }; ZigTypeId type_id_at_index(size_t index) { assert(index < array_length(all_type_ids)); return all_type_ids[index]; } size_t type_id_len() { return array_length(all_type_ids); } size_t type_id_index(ZigType *entry) { switch (entry->id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdMetaType: return 0; case ZigTypeIdVoid: return 1; case ZigTypeIdBool: return 2; case ZigTypeIdUnreachable: return 3; case ZigTypeIdInt: return 4; case ZigTypeIdFloat: return 5; case ZigTypeIdPointer: return 6; case ZigTypeIdArray: return 7; case ZigTypeIdStruct: if (entry->data.structure.special == StructSpecialSlice) return 6; return 8; case ZigTypeIdComptimeFloat: return 9; case ZigTypeIdComptimeInt: return 10; case ZigTypeIdUndefined: return 11; case ZigTypeIdNull: return 12; case ZigTypeIdOptional: return 13; case ZigTypeIdErrorUnion: return 14; case ZigTypeIdErrorSet: return 15; case ZigTypeIdEnum: return 16; case ZigTypeIdUnion: return 17; case ZigTypeIdFn: return 18; case ZigTypeIdBoundFn: return 19; case ZigTypeIdOpaque: return 20; case ZigTypeIdFnFrame: return 21; case ZigTypeIdAnyFrame: return 22; case ZigTypeIdVector: return 23; case ZigTypeIdEnumLiteral: return 24; } zig_unreachable(); } const char *type_id_name(ZigTypeId id) { switch (id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdMetaType: return "Type"; case ZigTypeIdVoid: return "Void"; case ZigTypeIdBool: return "Bool"; case ZigTypeIdUnreachable: return "NoReturn"; case ZigTypeIdInt: return "Int"; case ZigTypeIdFloat: return "Float"; case ZigTypeIdPointer: return "Pointer"; case ZigTypeIdArray: return "Array"; case ZigTypeIdStruct: return "Struct"; case ZigTypeIdComptimeFloat: return "ComptimeFloat"; case ZigTypeIdComptimeInt: return "ComptimeInt"; case ZigTypeIdEnumLiteral: return "EnumLiteral"; case ZigTypeIdUndefined: return "Undefined"; case ZigTypeIdNull: return "Null"; case ZigTypeIdOptional: return "Optional"; case ZigTypeIdErrorUnion: return "ErrorUnion"; case ZigTypeIdErrorSet: return "ErrorSet"; case ZigTypeIdEnum: return "Enum"; case ZigTypeIdUnion: return "Union"; case ZigTypeIdFn: return "Fn"; case ZigTypeIdBoundFn: return "BoundFn"; case ZigTypeIdOpaque: return "Opaque"; case ZigTypeIdVector: return "Vector"; case ZigTypeIdFnFrame: return "Frame"; case ZigTypeIdAnyFrame: return "AnyFrame"; } zig_unreachable(); } ZigType *get_align_amt_type(CodeGen *g) { if (g->align_amt_type == nullptr) { // according to LLVM the maximum alignment is 1 << 29. g->align_amt_type = get_int_type(g, false, 29); } return g->align_amt_type; } uint32_t type_ptr_hash(const ZigType *ptr) { return hash_combine(HASH_INIT, &ptr); } bool type_ptr_eql(const ZigType *a, const ZigType *b) { return a == b; } uint32_t pkg_ptr_hash(const ZigPackage *ptr) { return hash_combine(HASH_INIT, &ptr); } bool pkg_ptr_eql(const ZigPackage *a, const ZigPackage *b) { return a == b; } uint32_t tld_ptr_hash(const Tld *ptr) { return hash_combine(HASH_INIT, &ptr); } bool tld_ptr_eql(const Tld *a, const Tld *b) { return a == b; } uint32_t node_ptr_hash(const AstNode *ptr) { return hash_combine(HASH_INIT, &ptr); } bool node_ptr_eql(const AstNode *a, const AstNode *b) { return a == b; } uint32_t fn_ptr_hash(const ZigFn *ptr) { return hash_combine(HASH_INIT, &ptr); } bool fn_ptr_eql(const ZigFn *a, const ZigFn *b) { return a == b; } uint32_t err_ptr_hash(const ErrorTableEntry *ptr) { return hash_combine(HASH_INIT, &ptr); } bool err_ptr_eql(const ErrorTableEntry *a, const ErrorTableEntry *b) { return a == b; } ZigValue *get_builtin_value(CodeGen *codegen, const char *name) { Buf *buf_name = buf_create_from_str(name); ScopeDecls *builtin_scope = get_container_scope(codegen->std_builtin_import); Tld *tld = find_container_decl(codegen, builtin_scope, buf_name); assert(tld != nullptr); resolve_top_level_decl(codegen, tld, nullptr, false); assert(tld->id == TldIdVar && tld->resolution == TldResolutionOk); TldVar *tld_var = (TldVar *)tld; ZigValue *var_value = tld_var->var->const_value; assert(var_value != nullptr); buf_destroy(buf_name); return var_value; } ZigType *get_builtin_type(CodeGen *codegen, const char *name) { ZigValue *type_val = get_builtin_value(codegen, name); assert(type_val->type->id == ZigTypeIdMetaType); return type_val->data.x_type; } bool type_is_global_error_set(ZigType *err_set_type) { assert(err_set_type->id == ZigTypeIdErrorSet); assert(!err_set_type->data.error_set.incomplete); return err_set_type->data.error_set.err_count == UINT32_MAX; } bool type_can_fail(ZigType *type_entry) { return type_entry->id == ZigTypeIdErrorUnion || type_entry->id == ZigTypeIdErrorSet; } bool fn_type_can_fail(FnTypeId *fn_type_id) { return type_can_fail(fn_type_id->return_type); } // ErrorNone - result pointer has the type // ErrorOverflow - an integer primitive type has too large a bit width // ErrorPrimitiveTypeNotFound - result pointer unchanged Error get_primitive_type(CodeGen *g, Buf *name, ZigType **result) { if (buf_len(name) >= 2) { uint8_t first_c = buf_ptr(name)[0]; if (first_c == 'i' || first_c == 'u') { for (size_t i = 1; i < buf_len(name); i += 1) { uint8_t c = buf_ptr(name)[i]; if (c < '0' || c > '9') { goto not_integer; } } bool is_signed = (first_c == 'i'); unsigned long int bit_count = strtoul(buf_ptr(name) + 1, nullptr, 10); // strtoul returns ULONG_MAX on errors, so this comparison catches that as well. if (bit_count >= 65536) return ErrorOverflow; *result = get_int_type(g, is_signed, bit_count); return ErrorNone; } } not_integer: auto primitive_table_entry = g->primitive_type_table.maybe_get(name); if (primitive_table_entry == nullptr) return ErrorPrimitiveTypeNotFound; *result = primitive_table_entry->value; return ErrorNone; } Error file_fetch(CodeGen *g, Buf *resolved_path, Buf *contents_buf) { size_t len; const char *contents = stage2_fetch_file(&g->stage1, buf_ptr(resolved_path), buf_len(resolved_path), &len); if (contents == nullptr) return ErrorFileNotFound; buf_init_from_mem(contents_buf, contents, len); return ErrorNone; } static X64CABIClass type_windows_abi_x86_64_class(CodeGen *g, ZigType *ty, size_t ty_size) { // https://docs.microsoft.com/en-gb/cpp/build/x64-calling-convention?view=vs-2017 switch (ty->id) { case ZigTypeIdEnum: case ZigTypeIdInt: case ZigTypeIdBool: return X64CABIClass_INTEGER; case ZigTypeIdFloat: case ZigTypeIdVector: return X64CABIClass_SSE; case ZigTypeIdStruct: case ZigTypeIdUnion: { if (ty_size <= 8) return X64CABIClass_INTEGER; return X64CABIClass_MEMORY; } default: return X64CABIClass_Unknown; } } static X64CABIClass type_system_V_abi_x86_64_class(CodeGen *g, ZigType *ty, size_t ty_size) { switch (ty->id) { case ZigTypeIdEnum: case ZigTypeIdInt: case ZigTypeIdBool: return X64CABIClass_INTEGER; case ZigTypeIdFloat: case ZigTypeIdVector: return X64CABIClass_SSE; case ZigTypeIdStruct: { // "If the size of an object is larger than four eightbytes, or it contains unaligned // fields, it has class MEMORY" if (ty_size > 32) return X64CABIClass_MEMORY; if (ty->data.structure.layout != ContainerLayoutExtern) { // TODO determine whether packed structs have any unaligned fields return X64CABIClass_Unknown; } // "If the size of the aggregate exceeds two eightbytes and the first eight- // byte isn’t SSE or any other eightbyte isn’t SSEUP, the whole argument // is passed in memory." if (ty_size > 16) { // Zig doesn't support vectors and large fp registers yet, so this will always // be memory. return X64CABIClass_MEMORY; } // "If the size of the aggregate exceeds a single eightbyte, each is classified // separately.". // "If one of the classes is MEMORY, the whole argument is passed in memory" X64CABIClass working_class = X64CABIClass_Unknown; for (uint32_t i = 0; i < ty->data.structure.src_field_count; i += 1) { X64CABIClass field_class = type_c_abi_x86_64_class(g, ty->data.structure.fields[0]->type_entry); if (field_class == X64CABIClass_Unknown) return X64CABIClass_Unknown; if (i == 0 || field_class == X64CABIClass_MEMORY || working_class == X64CABIClass_SSE) { working_class = field_class; } } if (working_class == X64CABIClass_MEMORY) { return X64CABIClass_MEMORY; } return X64CABIClass_AGG; } case ZigTypeIdUnion: { // "If the size of an object is larger than four eightbytes, or it contains unaligned // fields, it has class MEMORY" if (ty_size > 32) return X64CABIClass_MEMORY; if (ty->data.unionation.layout != ContainerLayoutExtern) return X64CABIClass_MEMORY; // "If the size of the aggregate exceeds two eightbytes and the first eight- // byte isn’t SSE or any other eightbyte isn’t SSEUP, the whole argument // is passed in memory." if (ty_size > 16) { // Zig doesn't support vectors and large fp registers yet, so this will always // be memory. return X64CABIClass_MEMORY; } X64CABIClass working_class = X64CABIClass_Unknown; for (uint32_t i = 0; i < ty->data.unionation.src_field_count; i += 1) { X64CABIClass field_class = type_c_abi_x86_64_class(g, ty->data.unionation.fields->type_entry); if (field_class == X64CABIClass_Unknown) return X64CABIClass_Unknown; if (i == 0 || field_class == X64CABIClass_MEMORY || field_class == X64CABIClass_INTEGER || working_class == X64CABIClass_SSE) { working_class = field_class; } } return working_class; } default: return X64CABIClass_Unknown; } } X64CABIClass type_c_abi_x86_64_class(CodeGen *g, ZigType *ty) { Error err; const size_t ty_size = type_size(g, ty); ZigType *ptr_type; if ((err = get_codegen_ptr_type(g, ty, &ptr_type))) return X64CABIClass_Unknown; if (ptr_type != nullptr) return X64CABIClass_INTEGER; if (g->zig_target->os == OsWindows || g->zig_target->os == OsUefi) { return type_windows_abi_x86_64_class(g, ty, ty_size); } else if (g->zig_target->arch == ZigLLVM_aarch64 || g->zig_target->arch == ZigLLVM_aarch64_be) { X64CABIClass result = type_system_V_abi_x86_64_class(g, ty, ty_size); return (result == X64CABIClass_MEMORY) ? X64CABIClass_MEMORY_nobyval : result; } else { return type_system_V_abi_x86_64_class(g, ty, ty_size); } } // NOTE this does not depend on x86_64 Error type_is_c_abi_int(CodeGen *g, ZigType *ty, bool *result) { if (ty->id == ZigTypeIdInt || ty->id == ZigTypeIdFloat || ty->id == ZigTypeIdBool || ty->id == ZigTypeIdEnum || ty->id == ZigTypeIdVoid || ty->id == ZigTypeIdUnreachable) { *result = true; return ErrorNone; } Error err; ZigType *ptr_type; if ((err = get_codegen_ptr_type(g, ty, &ptr_type))) return err; *result = ptr_type != nullptr; return ErrorNone; } bool type_is_c_abi_int_bail(CodeGen *g, ZigType *ty) { Error err; bool result; if ((err = type_is_c_abi_int(g, ty, &result))) codegen_report_errors_and_exit(g); return result; } uint32_t get_host_int_bytes(CodeGen *g, ZigType *struct_type, TypeStructField *field) { assert(struct_type->id == ZigTypeIdStruct); if (struct_type->data.structure.layout != ContainerLayoutAuto) { assert(type_is_resolved(struct_type, ResolveStatusSizeKnown)); } if (struct_type->data.structure.host_int_bytes == nullptr) return 0; return struct_type->data.structure.host_int_bytes[field->gen_index]; } Error ensure_const_val_repr(IrAnalyze *ira, CodeGen *codegen, AstNode *source_node, ZigValue *const_val, ZigType *wanted_type) { ZigValue ptr_val = {}; ptr_val.special = ConstValSpecialStatic; ptr_val.type = get_pointer_to_type(codegen, wanted_type, true); ptr_val.data.x_ptr.mut = ConstPtrMutComptimeConst; ptr_val.data.x_ptr.special = ConstPtrSpecialRef; ptr_val.data.x_ptr.data.ref.pointee = const_val; if (const_ptr_pointee(ira, codegen, &ptr_val, source_node) == nullptr) return ErrorSemanticAnalyzeFail; return ErrorNone; } const char *container_string(ContainerKind kind) { switch (kind) { case ContainerKindEnum: return "enum"; case ContainerKindStruct: return "struct"; case ContainerKindUnion: return "union"; case ContainerKindOpaque: return "opaque"; } zig_unreachable(); } bool ptr_allows_addr_zero(ZigType *ptr_type) { if (ptr_type->id == ZigTypeIdPointer) { return ptr_type->data.pointer.allow_zero; } else if (ptr_type->id == ZigTypeIdOptional) { return true; } return false; } Buf *type_bare_name(ZigType *type_entry) { if (is_slice(type_entry)) { return &type_entry->name; } else if (is_container(type_entry)) { return get_container_scope(type_entry)->bare_name; } else { return &type_entry->name; } } // TODO this will have to be more clever, probably using the full name // and replacing '.' with '_' or something like that Buf *type_h_name(ZigType *t) { return type_bare_name(t); } static void resolve_llvm_types_slice(CodeGen *g, ZigType *type, ResolveStatus wanted_resolve_status) { if (type->data.structure.resolve_status >= wanted_resolve_status) return; ZigType *ptr_type = type->data.structure.fields[slice_ptr_index]->type_entry; ZigType *child_type = ptr_type->data.pointer.child_type; ZigType *usize_type = g->builtin_types.entry_usize; bool done = false; if (ptr_type->data.pointer.is_const || ptr_type->data.pointer.is_volatile || ptr_type->data.pointer.explicit_alignment != 0 || ptr_type->data.pointer.allow_zero || ptr_type->data.pointer.sentinel != nullptr) { ZigType *peer_ptr_type = get_pointer_to_type_extra(g, child_type, false, false, PtrLenUnknown, 0, 0, 0, false); ZigType *peer_slice_type = get_slice_type(g, peer_ptr_type); assertNoError(type_resolve(g, peer_slice_type, wanted_resolve_status)); type->llvm_type = peer_slice_type->llvm_type; type->llvm_di_type = peer_slice_type->llvm_di_type; type->data.structure.resolve_status = peer_slice_type->data.structure.resolve_status; done = true; } // If the child type is []const T then we need to make sure the type ref // and debug info is the same as if the child type were []T. if (is_slice(child_type)) { ZigType *child_ptr_type = child_type->data.structure.fields[slice_ptr_index]->type_entry; assert(child_ptr_type->id == ZigTypeIdPointer); if (child_ptr_type->data.pointer.is_const || child_ptr_type->data.pointer.is_volatile || child_ptr_type->data.pointer.explicit_alignment != 0 || child_ptr_type->data.pointer.allow_zero || child_ptr_type->data.pointer.sentinel != nullptr) { ZigType *grand_child_type = child_ptr_type->data.pointer.child_type; ZigType *bland_child_ptr_type = get_pointer_to_type_extra(g, grand_child_type, false, false, PtrLenUnknown, 0, 0, 0, false); ZigType *bland_child_slice = get_slice_type(g, bland_child_ptr_type); ZigType *peer_ptr_type = get_pointer_to_type_extra(g, bland_child_slice, false, false, PtrLenUnknown, 0, 0, 0, false); ZigType *peer_slice_type = get_slice_type(g, peer_ptr_type); assertNoError(type_resolve(g, peer_slice_type, wanted_resolve_status)); type->llvm_type = peer_slice_type->llvm_type; type->llvm_di_type = peer_slice_type->llvm_di_type; type->data.structure.resolve_status = peer_slice_type->data.structure.resolve_status; done = true; } } if (done) return; LLVMTypeRef usize_llvm_type = get_llvm_type(g, usize_type); ZigLLVMDIType *usize_llvm_di_type = get_llvm_di_type(g, usize_type); ZigLLVMDIScope *compile_unit_scope = ZigLLVMCompileUnitToScope(g->compile_unit); ZigLLVMDIFile *di_file = nullptr; unsigned line = 0; if (type->data.structure.resolve_status < ResolveStatusLLVMFwdDecl) { type->llvm_type = LLVMStructCreateNamed(LLVMGetGlobalContext(), buf_ptr(&type->name)); type->llvm_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder, ZigLLVMTag_DW_structure_type(), buf_ptr(&type->name), compile_unit_scope, di_file, line); type->data.structure.resolve_status = ResolveStatusLLVMFwdDecl; if (ResolveStatusLLVMFwdDecl >= wanted_resolve_status) return; } if (!type_has_bits(g, child_type)) { LLVMTypeRef element_types[] = { usize_llvm_type, }; LLVMStructSetBody(type->llvm_type, element_types, 1, false); uint64_t len_debug_size_in_bits = usize_type->size_in_bits; uint64_t len_debug_align_in_bits = 8*usize_type->abi_align; uint64_t len_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, 0); uint64_t debug_size_in_bits = type->size_in_bits; uint64_t debug_align_in_bits = 8*type->abi_align; ZigLLVMDIType *di_element_types[] = { ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type), "len", di_file, line, len_debug_size_in_bits, len_debug_align_in_bits, len_offset_in_bits, ZigLLVM_DIFlags_Zero, usize_llvm_di_type), }; ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder, compile_unit_scope, buf_ptr(&type->name), di_file, line, debug_size_in_bits, debug_align_in_bits, ZigLLVM_DIFlags_Zero, nullptr, di_element_types, 1, 0, nullptr, ""); ZigLLVMReplaceTemporary(g->dbuilder, type->llvm_di_type, replacement_di_type); type->llvm_di_type = replacement_di_type; type->data.structure.resolve_status = ResolveStatusLLVMFull; return; } LLVMTypeRef element_types[2]; element_types[slice_ptr_index] = get_llvm_type(g, ptr_type); element_types[slice_len_index] = get_llvm_type(g, g->builtin_types.entry_usize); if (type->data.structure.resolve_status >= wanted_resolve_status) return; LLVMStructSetBody(type->llvm_type, element_types, 2, false); uint64_t ptr_debug_size_in_bits = ptr_type->size_in_bits; uint64_t ptr_debug_align_in_bits = 8*ptr_type->abi_align; uint64_t ptr_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, 0); uint64_t len_debug_size_in_bits = usize_type->size_in_bits; uint64_t len_debug_align_in_bits = 8*usize_type->abi_align; uint64_t len_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, 1); uint64_t debug_size_in_bits = type->size_in_bits; uint64_t debug_align_in_bits = 8*type->abi_align; ZigLLVMDIType *di_element_types[] = { ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type), "ptr", di_file, line, ptr_debug_size_in_bits, ptr_debug_align_in_bits, ptr_offset_in_bits, ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, ptr_type)), ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type), "len", di_file, line, len_debug_size_in_bits, len_debug_align_in_bits, len_offset_in_bits, ZigLLVM_DIFlags_Zero, usize_llvm_di_type), }; ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder, compile_unit_scope, buf_ptr(&type->name), di_file, line, debug_size_in_bits, debug_align_in_bits, ZigLLVM_DIFlags_Zero, nullptr, di_element_types, 2, 0, nullptr, ""); ZigLLVMReplaceTemporary(g->dbuilder, type->llvm_di_type, replacement_di_type); type->llvm_di_type = replacement_di_type; type->data.structure.resolve_status = ResolveStatusLLVMFull; } static LLVMTypeRef get_llvm_type_of_n_bytes(unsigned byte_size) { return byte_size == 1 ? LLVMInt8Type() : LLVMArrayType(LLVMInt8Type(), byte_size); } static LLVMTypeRef llvm_int_for_size(size_t size) { if (size > 4) { return LLVMInt64Type(); } else if (size > 2) { return LLVMInt32Type(); } else if (size == 2) { return LLVMInt16Type(); } else { return LLVMInt8Type(); } } static LLVMTypeRef llvm_sse_for_size(size_t size) { if (size > 4) return LLVMDoubleType(); else return LLVMFloatType(); } // Since it's not possible to control calling convention or register // allocation in LLVM, clang seems to use intermediate types to manipulate // LLVM into doing the right thing. It uses a float to force SSE registers, // and a struct when 2 registers must be used. Some examples: // { f32 } -> float // { f32, i32 } -> { float, i32 } // { i32, i32, f32 } -> { i64, float } // // The implementation below does not match clang 1:1. For instance, clang // uses `<2x float>` while we generate `double`. There's a lot more edge // cases and complexity when converting back and forth in clang though, // so below is the simplest implementation that passes all tests. static Error resolve_llvm_c_abi_type(CodeGen *g, ZigType *ty) { size_t ty_size = type_size(g, ty); LLVMTypeRef abi_type; switch (ty->id) { case ZigTypeIdEnum: case ZigTypeIdInt: case ZigTypeIdBool: abi_type = llvm_int_for_size(ty_size); break; case ZigTypeIdFloat: case ZigTypeIdVector: abi_type = llvm_sse_for_size(ty_size); break; case ZigTypeIdStruct: { uint32_t eightbyte_index = 0; size_t type_sizes[] = {0, 0}; X64CABIClass type_classes[] = {X64CABIClass_Unknown, X64CABIClass_Unknown}; for (uint32_t i = 0; i < ty->data.structure.src_field_count; i += 1) { if (ty->data.structure.fields[i]->offset >= 8) { eightbyte_index = 1; } X64CABIClass field_class = type_c_abi_x86_64_class(g, ty->data.structure.fields[i]->type_entry); if (field_class == X64CABIClass_INTEGER) { type_classes[eightbyte_index] = X64CABIClass_INTEGER; } else if (type_classes[eightbyte_index] == X64CABIClass_Unknown) { type_classes[eightbyte_index] = field_class; } type_sizes[eightbyte_index] += ty->data.structure.fields[i]->type_entry->abi_size; } LLVMTypeRef return_elem_types[] = { LLVMVoidType(), LLVMVoidType(), }; for (uint32_t i = 0; i <= eightbyte_index; i += 1) { if (type_classes[i] == X64CABIClass_INTEGER) { return_elem_types[i] = llvm_int_for_size(type_sizes[i]); } else { return_elem_types[i] = llvm_sse_for_size(type_sizes[i]); } } if (eightbyte_index == 0) { abi_type = return_elem_types[0]; } else { abi_type = LLVMStructType(return_elem_types, 2, false); } break; } case ZigTypeIdUnion: default: // currently unreachable zig_panic("TODO: support C ABI unions"); } ty->llvm_c_abi_type = abi_type; return ErrorNone; } static void resolve_llvm_types_struct(CodeGen *g, ZigType *struct_type, ResolveStatus wanted_resolve_status, ZigType *async_frame_type) { assert(struct_type->id == ZigTypeIdStruct); assert(struct_type->data.structure.resolve_status != ResolveStatusInvalid); assert(struct_type->data.structure.resolve_status >= ResolveStatusSizeKnown); assert(struct_type->data.structure.fields || struct_type->data.structure.src_field_count == 0); if (struct_type->data.structure.resolve_status >= wanted_resolve_status) return; AstNode *decl_node = struct_type->data.structure.decl_node; ZigLLVMDIFile *di_file; ZigLLVMDIScope *di_scope; unsigned line; if (decl_node != nullptr) { Scope *scope = &struct_type->data.structure.decls_scope->base; ZigType *import = get_scope_import(scope); di_file = import->data.structure.root_struct->di_file; di_scope = ZigLLVMFileToScope(di_file); line = node_line_onebased(decl_node); } else { di_file = nullptr; di_scope = ZigLLVMCompileUnitToScope(g->compile_unit); line = 0; } if (struct_type->data.structure.resolve_status < ResolveStatusLLVMFwdDecl) { struct_type->llvm_type = type_has_bits(g, struct_type) ? LLVMStructCreateNamed(LLVMGetGlobalContext(), buf_ptr(&struct_type->name)) : LLVMVoidType(); unsigned dwarf_kind = ZigLLVMTag_DW_structure_type(); struct_type->llvm_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder, dwarf_kind, buf_ptr(&struct_type->name), di_scope, di_file, line); struct_type->data.structure.resolve_status = ResolveStatusLLVMFwdDecl; if (ResolveStatusLLVMFwdDecl >= wanted_resolve_status) { struct_type->data.structure.llvm_full_type_queue_index = g->type_resolve_stack.length; g->type_resolve_stack.append(struct_type); return; } else { struct_type->data.structure.llvm_full_type_queue_index = SIZE_MAX; } } size_t field_count = struct_type->data.structure.src_field_count; // Every field could potentially have a generated padding field after it. LLVMTypeRef *element_types = heap::c_allocator.allocate<LLVMTypeRef>(field_count * 2); bool packed = (struct_type->data.structure.layout == ContainerLayoutPacked); size_t packed_bits_offset = 0; size_t first_packed_bits_offset_misalign = SIZE_MAX; size_t debug_field_count = 0; // trigger all the recursive get_llvm_type calls for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = struct_type->data.structure.fields[i]; ZigType *field_type = field->type_entry; if (!type_has_bits(g, field_type)) continue; (void)get_llvm_type(g, field_type); if (struct_type->data.structure.resolve_status >= wanted_resolve_status) return; } size_t gen_field_index = 0; // Calculate what LLVM thinks the ABI align of the struct will be. We do this to avoid // inserting padding bytes where LLVM would do it automatically. size_t llvm_struct_abi_align = 0; for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = struct_type->data.structure.fields[i]; ZigType *field_type = field->type_entry; if (field->is_comptime || !type_has_bits(g, field_type)) continue; LLVMTypeRef field_llvm_type = get_llvm_type(g, field_type); size_t llvm_field_abi_align = LLVMABIAlignmentOfType(g->target_data_ref, field_llvm_type); llvm_struct_abi_align = max(llvm_struct_abi_align, llvm_field_abi_align); } for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = struct_type->data.structure.fields[i]; ZigType *field_type = field->type_entry; if (field->is_comptime || !type_has_bits(g, field_type)) { field->gen_index = SIZE_MAX; continue; } if (packed) { size_t field_size_in_bits = type_size_bits(g, field_type); size_t next_packed_bits_offset = packed_bits_offset + field_size_in_bits; if (first_packed_bits_offset_misalign != SIZE_MAX) { // this field is not byte-aligned; it is part of the previous field with a bit offset size_t full_bit_count = next_packed_bits_offset - first_packed_bits_offset_misalign; size_t full_abi_size = get_abi_size_bytes(full_bit_count, g->pointer_size_bytes); if (full_abi_size * 8 == full_bit_count) { // next field recovers ABI alignment element_types[gen_field_index] = get_llvm_type_of_n_bytes(full_abi_size); gen_field_index += 1; first_packed_bits_offset_misalign = SIZE_MAX; } } else if (get_abi_size_bytes(field_type->size_in_bits, g->pointer_size_bytes) * 8 != field_size_in_bits) { first_packed_bits_offset_misalign = packed_bits_offset; } else { // This is a byte-aligned field (both start and end) in a packed struct. element_types[gen_field_index] = get_llvm_type(g, field_type); assert(get_abi_size_bytes(field_type->size_in_bits, g->pointer_size_bytes) == LLVMStoreSizeOfType(g->target_data_ref, element_types[gen_field_index])); gen_field_index += 1; } packed_bits_offset = next_packed_bits_offset; } else { LLVMTypeRef llvm_type; if (i == 0 && async_frame_type != nullptr) { assert(async_frame_type->id == ZigTypeIdFnFrame); assert(field_type->id == ZigTypeIdFn); resolve_llvm_types_fn(g, async_frame_type->data.frame.fn); const unsigned addrspace = ZigLLVMDataLayoutGetProgramAddressSpace(g->target_data_ref); llvm_type = LLVMPointerType(async_frame_type->data.frame.fn->raw_type_ref, addrspace); } else { llvm_type = get_llvm_type(g, field_type); } element_types[gen_field_index] = llvm_type; field->gen_index = gen_field_index; gen_field_index += 1; // find the next non-zero-byte field for offset calculations size_t next_src_field_index = i + 1; for (; next_src_field_index < field_count; next_src_field_index += 1) { if (type_has_bits(g, struct_type->data.structure.fields[next_src_field_index]->type_entry)) break; } size_t next_abi_align; if (next_src_field_index == field_count) { next_abi_align = struct_type->abi_align; } else { if (struct_type->data.structure.fields[next_src_field_index]->align == 0) { next_abi_align = struct_type->data.structure.fields[next_src_field_index]->type_entry->abi_align; } else { next_abi_align = struct_type->data.structure.fields[next_src_field_index]->align; } } size_t llvm_next_abi_align = (next_src_field_index == field_count) ? llvm_struct_abi_align : LLVMABIAlignmentOfType(g->target_data_ref, get_llvm_type(g, struct_type->data.structure.fields[next_src_field_index]->type_entry)); size_t next_offset = next_field_offset(field->offset, struct_type->abi_align, field_type->abi_size, next_abi_align); size_t llvm_next_offset = next_field_offset(field->offset, llvm_struct_abi_align, LLVMABISizeOfType(g->target_data_ref, llvm_type), llvm_next_abi_align); assert(next_offset >= llvm_next_offset); if (next_offset > llvm_next_offset) { size_t pad_bytes = next_offset - (field->offset + LLVMStoreSizeOfType(g->target_data_ref, llvm_type)); if (pad_bytes != 0) { LLVMTypeRef pad_llvm_type = LLVMArrayType(LLVMInt8Type(), pad_bytes); element_types[gen_field_index] = pad_llvm_type; gen_field_index += 1; } } } debug_field_count += 1; } if (!packed) { struct_type->data.structure.gen_field_count = gen_field_index; } if (first_packed_bits_offset_misalign != SIZE_MAX) { size_t full_bit_count = packed_bits_offset - first_packed_bits_offset_misalign; size_t full_abi_size = get_abi_size_bytes(full_bit_count, g->pointer_size_bytes); element_types[gen_field_index] = get_llvm_type_of_n_bytes(full_abi_size); gen_field_index += 1; } if (type_has_bits(g, struct_type)) { assert(struct_type->data.structure.gen_field_count == gen_field_index); LLVMStructSetBody(struct_type->llvm_type, element_types, (unsigned)struct_type->data.structure.gen_field_count, packed); } ZigLLVMDIType **di_element_types = heap::c_allocator.allocate<ZigLLVMDIType*>(debug_field_count); size_t debug_field_index = 0; for (size_t i = 0; i < field_count; i += 1) { TypeStructField *field = struct_type->data.structure.fields[i]; //fprintf(stderr, "%s at gen index %zu\n", buf_ptr(field->name), field->gen_index); size_t gen_field_index = field->gen_index; if (gen_field_index == SIZE_MAX) { continue; } ZigType *field_type = field->type_entry; // if the field is a function, actually the debug info should be a pointer. ZigLLVMDIType *field_di_type; if (field_type->id == ZigTypeIdFn) { ZigType *field_ptr_type = get_pointer_to_type(g, field_type, true); uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, get_llvm_type(g, field_ptr_type)); uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, get_llvm_type(g, field_ptr_type)); field_di_type = ZigLLVMCreateDebugPointerType(g->dbuilder, get_llvm_di_type(g, field_type), debug_size_in_bits, debug_align_in_bits, buf_ptr(&field_ptr_type->name)); } else { field_di_type = get_llvm_di_type(g, field_type); } uint64_t debug_size_in_bits; uint64_t debug_align_in_bits; uint64_t debug_offset_in_bits; if (packed) { debug_size_in_bits = field->type_entry->size_in_bits; debug_align_in_bits = 8 * field->type_entry->abi_align; debug_offset_in_bits = 8 * field->offset + field->bit_offset_in_host; } else { debug_size_in_bits = 8 * get_store_size_bytes(field_type->size_in_bits); debug_align_in_bits = 8 * field_type->abi_align; debug_offset_in_bits = 8 * field->offset; } unsigned line; if (decl_node != nullptr) { AstNode *field_node = field->decl_node; line = node_line_onebased(field_node); } else { line = 0; } di_element_types[debug_field_index] = ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(struct_type->llvm_di_type), buf_ptr(field->name), di_file, line, debug_size_in_bits, debug_align_in_bits, debug_offset_in_bits, ZigLLVM_DIFlags_Zero, field_di_type); assert(di_element_types[debug_field_index]); debug_field_index += 1; } uint64_t debug_size_in_bits = 8*get_store_size_bytes(struct_type->size_in_bits); uint64_t debug_align_in_bits = 8*struct_type->abi_align; ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder, di_scope, buf_ptr(&struct_type->name), di_file, line, debug_size_in_bits, debug_align_in_bits, ZigLLVM_DIFlags_Zero, nullptr, di_element_types, (int)debug_field_count, 0, nullptr, ""); ZigLLVMReplaceTemporary(g->dbuilder, struct_type->llvm_di_type, replacement_di_type); struct_type->llvm_di_type = replacement_di_type; struct_type->data.structure.resolve_status = ResolveStatusLLVMFull; if (struct_type->data.structure.llvm_full_type_queue_index != SIZE_MAX) { ZigType *last = g->type_resolve_stack.last(); assert(last->id == ZigTypeIdStruct); last->data.structure.llvm_full_type_queue_index = struct_type->data.structure.llvm_full_type_queue_index; g->type_resolve_stack.swap_remove(struct_type->data.structure.llvm_full_type_queue_index); struct_type->data.structure.llvm_full_type_queue_index = SIZE_MAX; } if (struct_type->abi_size <= 16 && (struct_type->data.structure.layout == ContainerLayoutExtern || struct_type->data.structure.layout == ContainerLayoutPacked)) resolve_llvm_c_abi_type(g, struct_type); } // This is to be used instead of void for debug info types, to avoid tripping // Assertion `!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type"' // when targeting CodeView (Windows). static ZigLLVMDIType *make_empty_namespace_llvm_di_type(CodeGen *g, ZigType *import, const char *name, AstNode *decl_node) { uint64_t debug_size_in_bits = 0; uint64_t debug_align_in_bits = 0; ZigLLVMDIType **di_element_types = nullptr; size_t debug_field_count = 0; return ZigLLVMCreateDebugStructType(g->dbuilder, ZigLLVMFileToScope(import->data.structure.root_struct->di_file), name, import->data.structure.root_struct->di_file, node_line_onebased(decl_node), debug_size_in_bits, debug_align_in_bits, ZigLLVM_DIFlags_Zero, nullptr, di_element_types, (int)debug_field_count, 0, nullptr, ""); } static void resolve_llvm_types_enum(CodeGen *g, ZigType *enum_type, ResolveStatus wanted_resolve_status) { assert(enum_type->data.enumeration.resolve_status >= ResolveStatusSizeKnown); if (enum_type->data.enumeration.resolve_status >= wanted_resolve_status) return; Scope *scope = &enum_type->data.enumeration.decls_scope->base; ZigType *import = get_scope_import(scope); AstNode *decl_node = enum_type->data.enumeration.decl_node; if (!type_has_bits(g, enum_type)) { enum_type->llvm_type = g->builtin_types.entry_void->llvm_type; enum_type->llvm_di_type = make_empty_namespace_llvm_di_type(g, import, buf_ptr(&enum_type->name), decl_node); enum_type->data.enumeration.resolve_status = ResolveStatusLLVMFull; return; } uint32_t field_count = enum_type->data.enumeration.src_field_count; assert(field_count == 0 || enum_type->data.enumeration.fields != nullptr); ZigLLVMDIEnumerator **di_enumerators = heap::c_allocator.allocate<ZigLLVMDIEnumerator*>(field_count); for (uint32_t i = 0; i < field_count; i += 1) { TypeEnumField *enum_field = &enum_type->data.enumeration.fields[i]; // TODO send patch to LLVM to support APInt in createEnumerator instead of int64_t // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119456.html di_enumerators[i] = ZigLLVMCreateDebugEnumerator(g->dbuilder, buf_ptr(enum_field->name), bigint_as_signed(&enum_field->value)); } ZigType *tag_int_type = enum_type->data.enumeration.tag_int_type; enum_type->llvm_type = get_llvm_type(g, tag_int_type); // create debug type for tag uint64_t tag_debug_size_in_bits = 8*tag_int_type->abi_size; uint64_t tag_debug_align_in_bits = 8*tag_int_type->abi_align; ZigLLVMDIType *tag_di_type = ZigLLVMCreateDebugEnumerationType(g->dbuilder, ZigLLVMFileToScope(import->data.structure.root_struct->di_file), buf_ptr(&enum_type->name), import->data.structure.root_struct->di_file, node_line_onebased(decl_node), tag_debug_size_in_bits, tag_debug_align_in_bits, di_enumerators, field_count, get_llvm_di_type(g, tag_int_type), ""); enum_type->llvm_di_type = tag_di_type; enum_type->data.enumeration.resolve_status = ResolveStatusLLVMFull; } static void resolve_llvm_types_union(CodeGen *g, ZigType *union_type, ResolveStatus wanted_resolve_status) { if (union_type->data.unionation.resolve_status >= wanted_resolve_status) return; bool packed = (union_type->data.unionation.layout == ContainerLayoutPacked); Scope *scope = &union_type->data.unionation.decls_scope->base; ZigType *import = get_scope_import(scope); TypeUnionField *most_aligned_union_member = union_type->data.unionation.most_aligned_union_member; ZigType *tag_type = union_type->data.unionation.tag_type; uint32_t gen_field_count = union_type->data.unionation.gen_field_count; if (gen_field_count == 0) { if (tag_type == nullptr) { union_type->llvm_type = g->builtin_types.entry_void->llvm_type; union_type->llvm_di_type = make_empty_namespace_llvm_di_type(g, import, buf_ptr(&union_type->name), union_type->data.unionation.decl_node); } else { union_type->llvm_type = get_llvm_type(g, tag_type); union_type->llvm_di_type = get_llvm_di_type(g, tag_type); } union_type->data.unionation.gen_union_index = SIZE_MAX; union_type->data.unionation.gen_tag_index = SIZE_MAX; union_type->data.unionation.resolve_status = ResolveStatusLLVMFull; return; } AstNode *decl_node = union_type->data.unionation.decl_node; if (union_type->data.unionation.resolve_status < ResolveStatusLLVMFwdDecl) { union_type->llvm_type = LLVMStructCreateNamed(LLVMGetGlobalContext(), buf_ptr(&union_type->name)); unsigned line = decl_node ? node_line_onebased(decl_node) : 0; unsigned dwarf_kind = ZigLLVMTag_DW_structure_type(); union_type->llvm_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder, dwarf_kind, buf_ptr(&union_type->name), ZigLLVMFileToScope(import->data.structure.root_struct->di_file), import->data.structure.root_struct->di_file, line); union_type->data.unionation.resolve_status = ResolveStatusLLVMFwdDecl; if (ResolveStatusLLVMFwdDecl >= wanted_resolve_status) return; } ZigLLVMDIType **union_inner_di_types = heap::c_allocator.allocate<ZigLLVMDIType*>(gen_field_count); uint32_t field_count = union_type->data.unionation.src_field_count; for (uint32_t i = 0; i < field_count; i += 1) { TypeUnionField *union_field = &union_type->data.unionation.fields[i]; if (!type_has_bits(g, union_field->type_entry)) continue; ZigLLVMDIType *field_di_type = get_llvm_di_type(g, union_field->type_entry); if (union_type->data.unionation.resolve_status >= wanted_resolve_status) return; uint64_t store_size_in_bits = union_field->type_entry->size_in_bits; uint64_t abi_align_in_bits = 8*union_field->type_entry->abi_align; AstNode *field_node = union_field->decl_node; union_inner_di_types[union_field->gen_index] = ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(union_type->llvm_di_type), buf_ptr(union_field->enum_field->name), import->data.structure.root_struct->di_file, node_line_onebased(field_node), store_size_in_bits, abi_align_in_bits, 0, ZigLLVM_DIFlags_Zero, field_di_type); } if (tag_type == nullptr || !type_has_bits(g, tag_type)) { assert(most_aligned_union_member != nullptr); size_t padding_bytes = union_type->data.unionation.union_abi_size - most_aligned_union_member->type_entry->abi_size; if (padding_bytes > 0) { ZigType *u8_type = get_int_type(g, false, 8); ZigType *padding_array = get_array_type(g, u8_type, padding_bytes, nullptr); LLVMTypeRef union_element_types[] = { most_aligned_union_member->type_entry->llvm_type, get_llvm_type(g, padding_array), }; LLVMStructSetBody(union_type->llvm_type, union_element_types, 2, packed); } else { LLVMStructSetBody(union_type->llvm_type, &most_aligned_union_member->type_entry->llvm_type, 1, packed); } union_type->data.unionation.union_llvm_type = union_type->llvm_type; union_type->data.unionation.gen_tag_index = SIZE_MAX; union_type->data.unionation.gen_union_index = SIZE_MAX; // create debug type for union ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugUnionType(g->dbuilder, ZigLLVMFileToScope(import->data.structure.root_struct->di_file), buf_ptr(&union_type->name), import->data.structure.root_struct->di_file, node_line_onebased(decl_node), union_type->data.unionation.union_abi_size * 8, most_aligned_union_member->align * 8, ZigLLVM_DIFlags_Zero, union_inner_di_types, gen_field_count, 0, ""); ZigLLVMReplaceTemporary(g->dbuilder, union_type->llvm_di_type, replacement_di_type); union_type->llvm_di_type = replacement_di_type; union_type->data.unionation.resolve_status = ResolveStatusLLVMFull; return; } LLVMTypeRef union_type_ref; size_t padding_bytes = union_type->data.unionation.union_abi_size - most_aligned_union_member->type_entry->abi_size; if (padding_bytes == 0) { union_type_ref = get_llvm_type(g, most_aligned_union_member->type_entry); } else { ZigType *u8_type = get_int_type(g, false, 8); ZigType *padding_array = get_array_type(g, u8_type, padding_bytes, nullptr); LLVMTypeRef union_element_types[] = { get_llvm_type(g, most_aligned_union_member->type_entry), get_llvm_type(g, padding_array), }; union_type_ref = LLVMStructType(union_element_types, 2, false); } union_type->data.unionation.union_llvm_type = union_type_ref; LLVMTypeRef root_struct_element_types[2]; root_struct_element_types[union_type->data.unionation.gen_tag_index] = get_llvm_type(g, tag_type); root_struct_element_types[union_type->data.unionation.gen_union_index] = union_type_ref; LLVMStructSetBody(union_type->llvm_type, root_struct_element_types, 2, packed); // create debug type for union ZigLLVMDIType *union_di_type = ZigLLVMCreateDebugUnionType(g->dbuilder, ZigLLVMTypeToScope(union_type->llvm_di_type), "AnonUnion", import->data.structure.root_struct->di_file, node_line_onebased(decl_node), most_aligned_union_member->type_entry->size_in_bits, 8*most_aligned_union_member->align, ZigLLVM_DIFlags_Zero, union_inner_di_types, gen_field_count, 0, ""); uint64_t union_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, union_type->llvm_type, union_type->data.unionation.gen_union_index); uint64_t tag_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, union_type->llvm_type, union_type->data.unionation.gen_tag_index); ZigLLVMDIType *union_member_di_type = ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(union_type->llvm_di_type), "payload", import->data.structure.root_struct->di_file, node_line_onebased(decl_node), most_aligned_union_member->type_entry->size_in_bits, 8*most_aligned_union_member->align, union_offset_in_bits, ZigLLVM_DIFlags_Zero, union_di_type); uint64_t tag_debug_size_in_bits = tag_type->size_in_bits; uint64_t tag_debug_align_in_bits = 8*tag_type->abi_align; ZigLLVMDIType *tag_member_di_type = ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(union_type->llvm_di_type), "tag", import->data.structure.root_struct->di_file, node_line_onebased(decl_node), tag_debug_size_in_bits, tag_debug_align_in_bits, tag_offset_in_bits, ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, tag_type)); ZigLLVMDIType *di_root_members[2]; di_root_members[union_type->data.unionation.gen_tag_index] = tag_member_di_type; di_root_members[union_type->data.unionation.gen_union_index] = union_member_di_type; uint64_t debug_size_in_bits = union_type->size_in_bits; uint64_t debug_align_in_bits = 8*union_type->abi_align; ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder, ZigLLVMFileToScope(import->data.structure.root_struct->di_file), buf_ptr(&union_type->name), import->data.structure.root_struct->di_file, node_line_onebased(decl_node), debug_size_in_bits, debug_align_in_bits, ZigLLVM_DIFlags_Zero, nullptr, di_root_members, 2, 0, nullptr, ""); ZigLLVMReplaceTemporary(g->dbuilder, union_type->llvm_di_type, replacement_di_type); union_type->llvm_di_type = replacement_di_type; union_type->data.unionation.resolve_status = ResolveStatusLLVMFull; } static void resolve_llvm_types_pointer(CodeGen *g, ZigType *type, ResolveStatus wanted_resolve_status) { if (type->llvm_di_type != nullptr) return; if (resolve_pointer_zero_bits(g, type) != ErrorNone) zig_unreachable(); if (!type_has_bits(g, type)) { type->llvm_type = g->builtin_types.entry_void->llvm_type; type->llvm_di_type = g->builtin_types.entry_void->llvm_di_type; return; } ZigType *elem_type = type->data.pointer.child_type; if (type->data.pointer.is_const || type->data.pointer.is_volatile || type->data.pointer.explicit_alignment != 0 || type->data.pointer.ptr_len != PtrLenSingle || type->data.pointer.bit_offset_in_host != 0 || type->data.pointer.allow_zero || type->data.pointer.vector_index != VECTOR_INDEX_NONE || type->data.pointer.sentinel != nullptr) { assertNoError(type_resolve(g, elem_type, ResolveStatusLLVMFwdDecl)); ZigType *peer_type; if (type->data.pointer.vector_index == VECTOR_INDEX_NONE) { peer_type = get_pointer_to_type_extra2(g, elem_type, false, false, PtrLenSingle, 0, 0, type->data.pointer.host_int_bytes, false, VECTOR_INDEX_NONE, nullptr, nullptr); } else { uint32_t host_vec_len = type->data.pointer.host_int_bytes; ZigType *host_vec_type = get_vector_type(g, host_vec_len, elem_type); peer_type = get_pointer_to_type_extra2(g, host_vec_type, false, false, PtrLenSingle, 0, 0, 0, false, VECTOR_INDEX_NONE, nullptr, nullptr); } type->llvm_type = get_llvm_type(g, peer_type); type->llvm_di_type = get_llvm_di_type(g, peer_type); assertNoError(type_resolve(g, elem_type, wanted_resolve_status)); return; } if (type->data.pointer.host_int_bytes == 0) { assertNoError(type_resolve(g, elem_type, ResolveStatusLLVMFwdDecl)); type->llvm_type = LLVMPointerType(elem_type->llvm_type, 0); uint64_t debug_size_in_bits = 8*get_store_size_bytes(type->size_in_bits); uint64_t debug_align_in_bits = 8*type->abi_align; type->llvm_di_type = ZigLLVMCreateDebugPointerType(g->dbuilder, elem_type->llvm_di_type, debug_size_in_bits, debug_align_in_bits, buf_ptr(&type->name)); assertNoError(type_resolve(g, elem_type, wanted_resolve_status)); } else { ZigType *host_int_type = get_int_type(g, false, type->data.pointer.host_int_bytes * 8); LLVMTypeRef host_int_llvm_type = get_llvm_type(g, host_int_type); type->llvm_type = LLVMPointerType(host_int_llvm_type, 0); uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, host_int_llvm_type); uint64_t debug_align_in_bits = 8*LLVMABIAlignmentOfType(g->target_data_ref, host_int_llvm_type); type->llvm_di_type = ZigLLVMCreateDebugPointerType(g->dbuilder, get_llvm_di_type(g, host_int_type), debug_size_in_bits, debug_align_in_bits, buf_ptr(&type->name)); } } static void resolve_llvm_types_integer(CodeGen *g, ZigType *type) { if (type->llvm_di_type != nullptr) return; if (!type_has_bits(g, type)) { type->llvm_type = g->builtin_types.entry_void->llvm_type; type->llvm_di_type = g->builtin_types.entry_void->llvm_di_type; return; } unsigned dwarf_tag; if (type->data.integral.is_signed) { if (type->size_in_bits == 8) { dwarf_tag = ZigLLVMEncoding_DW_ATE_signed_char(); } else { dwarf_tag = ZigLLVMEncoding_DW_ATE_signed(); } } else { if (type->size_in_bits == 8) { dwarf_tag = ZigLLVMEncoding_DW_ATE_unsigned_char(); } else { dwarf_tag = ZigLLVMEncoding_DW_ATE_unsigned(); } } type->llvm_di_type = ZigLLVMCreateDebugBasicType(g->dbuilder, buf_ptr(&type->name), type->abi_size * 8, dwarf_tag); type->llvm_type = LLVMIntType(type->size_in_bits); } static void resolve_llvm_types_optional(CodeGen *g, ZigType *type, ResolveStatus wanted_resolve_status) { assert(type->id == ZigTypeIdOptional); assert(type->data.maybe.resolve_status != ResolveStatusInvalid); assert(type->data.maybe.resolve_status >= ResolveStatusSizeKnown); if (type->data.maybe.resolve_status >= wanted_resolve_status) return; LLVMTypeRef bool_llvm_type = get_llvm_type(g, g->builtin_types.entry_bool); ZigLLVMDIType *bool_llvm_di_type = get_llvm_di_type(g, g->builtin_types.entry_bool); ZigType *child_type = type->data.maybe.child_type; if (!type_has_bits(g, child_type)) { type->llvm_type = bool_llvm_type; type->llvm_di_type = bool_llvm_di_type; type->data.maybe.resolve_status = ResolveStatusLLVMFull; return; } if (type_is_nonnull_ptr(g, child_type) || child_type->id == ZigTypeIdErrorSet) { type->llvm_type = get_llvm_type(g, child_type); type->llvm_di_type = get_llvm_di_type(g, child_type); type->data.maybe.resolve_status = ResolveStatusLLVMFull; return; } ZigLLVMDIScope *compile_unit_scope = ZigLLVMCompileUnitToScope(g->compile_unit); ZigLLVMDIFile *di_file = nullptr; unsigned line = 0; if (type->data.maybe.resolve_status < ResolveStatusLLVMFwdDecl) { type->llvm_type = LLVMStructCreateNamed(LLVMGetGlobalContext(), buf_ptr(&type->name)); unsigned dwarf_kind = ZigLLVMTag_DW_structure_type(); type->llvm_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder, dwarf_kind, buf_ptr(&type->name), compile_unit_scope, di_file, line); type->data.maybe.resolve_status = ResolveStatusLLVMFwdDecl; if (ResolveStatusLLVMFwdDecl >= wanted_resolve_status) return; } ZigLLVMDIType *child_llvm_di_type = get_llvm_di_type(g, child_type); if (type->data.maybe.resolve_status >= wanted_resolve_status) return; LLVMTypeRef elem_types[] = { get_llvm_type(g, child_type), LLVMInt1Type(), }; LLVMStructSetBody(type->llvm_type, elem_types, 2, false); uint64_t val_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, maybe_child_index); uint64_t maybe_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, maybe_null_index); ZigLLVMDIType *di_element_types[2]; di_element_types[maybe_child_index] = ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type), "val", di_file, line, 8 * child_type->abi_size, 8 * child_type->abi_align, val_offset_in_bits, ZigLLVM_DIFlags_Zero, child_llvm_di_type); di_element_types[maybe_null_index] = ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type), "maybe", di_file, line, 8*g->builtin_types.entry_bool->abi_size, 8*g->builtin_types.entry_bool->abi_align, maybe_offset_in_bits, ZigLLVM_DIFlags_Zero, bool_llvm_di_type); ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder, compile_unit_scope, buf_ptr(&type->name), di_file, line, 8 * type->abi_size, 8 * type->abi_align, ZigLLVM_DIFlags_Zero, nullptr, di_element_types, 2, 0, nullptr, ""); ZigLLVMReplaceTemporary(g->dbuilder, type->llvm_di_type, replacement_di_type); type->llvm_di_type = replacement_di_type; type->data.maybe.resolve_status = ResolveStatusLLVMFull; } static void resolve_llvm_types_error_union(CodeGen *g, ZigType *type) { if (type->llvm_di_type != nullptr) return; ZigType *payload_type = type->data.error_union.payload_type; ZigType *err_set_type = type->data.error_union.err_set_type; if (!type_has_bits(g, payload_type)) { assert(type_has_bits(g, err_set_type)); type->llvm_type = get_llvm_type(g, err_set_type); type->llvm_di_type = get_llvm_di_type(g, err_set_type); } else if (!type_has_bits(g, err_set_type)) { type->llvm_type = get_llvm_type(g, payload_type); type->llvm_di_type = get_llvm_di_type(g, payload_type); } else { LLVMTypeRef err_set_llvm_type = get_llvm_type(g, err_set_type); LLVMTypeRef payload_llvm_type = get_llvm_type(g, payload_type); LLVMTypeRef elem_types[3]; elem_types[err_union_err_index] = err_set_llvm_type; elem_types[err_union_payload_index] = payload_llvm_type; type->llvm_type = LLVMStructType(elem_types, 2, false); if (LLVMABISizeOfType(g->target_data_ref, type->llvm_type) != type->abi_size) { // we need to do our own padding type->data.error_union.pad_llvm_type = LLVMArrayType(LLVMInt8Type(), type->data.error_union.pad_bytes); elem_types[2] = type->data.error_union.pad_llvm_type; type->llvm_type = LLVMStructType(elem_types, 3, false); } ZigLLVMDIScope *compile_unit_scope = ZigLLVMCompileUnitToScope(g->compile_unit); ZigLLVMDIFile *di_file = nullptr; unsigned line = 0; type->llvm_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder, ZigLLVMTag_DW_structure_type(), buf_ptr(&type->name), compile_unit_scope, di_file, line); uint64_t tag_debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, err_set_llvm_type); uint64_t tag_debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, err_set_llvm_type); uint64_t tag_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, err_union_err_index); uint64_t value_debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, payload_llvm_type); uint64_t value_debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, payload_llvm_type); uint64_t value_offset_in_bits = 8*LLVMOffsetOfElement(g->target_data_ref, type->llvm_type, err_union_payload_index); uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, type->llvm_type); uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, type->llvm_type); ZigLLVMDIType *di_element_types[2]; di_element_types[err_union_err_index] = ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type), "tag", di_file, line, tag_debug_size_in_bits, tag_debug_align_in_bits, tag_offset_in_bits, ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, err_set_type)); di_element_types[err_union_payload_index] = ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(type->llvm_di_type), "value", di_file, line, value_debug_size_in_bits, value_debug_align_in_bits, value_offset_in_bits, ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, payload_type)); ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder, compile_unit_scope, buf_ptr(&type->name), di_file, line, debug_size_in_bits, debug_align_in_bits, ZigLLVM_DIFlags_Zero, nullptr, di_element_types, 2, 0, nullptr, ""); ZigLLVMReplaceTemporary(g->dbuilder, type->llvm_di_type, replacement_di_type); type->llvm_di_type = replacement_di_type; } } static void resolve_llvm_types_array(CodeGen *g, ZigType *type) { if (type->llvm_di_type != nullptr) return; if (!type_has_bits(g, type)) { type->llvm_type = g->builtin_types.entry_void->llvm_type; type->llvm_di_type = g->builtin_types.entry_void->llvm_di_type; return; } ZigType *elem_type = type->data.array.child_type; uint64_t extra_len_from_sentinel = (type->data.array.sentinel != nullptr) ? 1 : 0; uint64_t full_len = type->data.array.len + extra_len_from_sentinel; // TODO https://github.com/ziglang/zig/issues/1424 type->llvm_type = LLVMArrayType(get_llvm_type(g, elem_type), (unsigned)full_len); uint64_t debug_size_in_bits = 8*LLVMStoreSizeOfType(g->target_data_ref, type->llvm_type); uint64_t debug_align_in_bits = 8*LLVMABISizeOfType(g->target_data_ref, type->llvm_type); type->llvm_di_type = ZigLLVMCreateDebugArrayType(g->dbuilder, debug_size_in_bits, debug_align_in_bits, get_llvm_di_type(g, elem_type), (int)full_len); } static void resolve_llvm_types_fn_type(CodeGen *g, ZigType *fn_type) { if (fn_type->llvm_di_type != nullptr) return; FnTypeId *fn_type_id = &fn_type->data.fn.fn_type_id; bool first_arg_return = want_first_arg_sret(g, fn_type_id); bool is_async = fn_type_id->cc == CallingConventionAsync; bool is_c_abi = !calling_convention_allows_zig_types(fn_type_id->cc); bool prefix_arg_error_return_trace = g->have_err_ret_tracing && fn_type_can_fail(fn_type_id); // +1 for maybe making the first argument the return value // +1 for maybe first argument the error return trace // +2 for maybe arguments async allocator and error code pointer ZigList<LLVMTypeRef> gen_param_types = {}; // +1 because 0 is the return type and // +1 for maybe making first arg ret val and // +1 for maybe first argument the error return trace // +2 for maybe arguments async allocator and error code pointer ZigList<ZigLLVMDIType *> param_di_types = {}; ZigType *gen_return_type; if (is_async) { gen_return_type = g->builtin_types.entry_void; param_di_types.append(nullptr); } else if (!type_has_bits(g, fn_type_id->return_type)) { gen_return_type = g->builtin_types.entry_void; param_di_types.append(nullptr); } else if (first_arg_return) { gen_return_type = g->builtin_types.entry_void; param_di_types.append(nullptr); ZigType *gen_type = get_pointer_to_type(g, fn_type_id->return_type, false); gen_param_types.append(get_llvm_type(g, gen_type)); param_di_types.append(get_llvm_di_type(g, gen_type)); } else { gen_return_type = fn_type_id->return_type; param_di_types.append(get_llvm_di_type(g, gen_return_type)); } fn_type->data.fn.gen_return_type = gen_return_type; if (prefix_arg_error_return_trace && !is_async) { ZigType *gen_type = get_pointer_to_type(g, get_stack_trace_type(g), false); gen_param_types.append(get_llvm_type(g, gen_type)); param_di_types.append(get_llvm_di_type(g, gen_type)); } if (is_async) { fn_type->data.fn.gen_param_info = heap::c_allocator.allocate<FnGenParamInfo>(2); ZigType *frame_type = get_any_frame_type(g, fn_type_id->return_type); gen_param_types.append(get_llvm_type(g, frame_type)); param_di_types.append(get_llvm_di_type(g, frame_type)); fn_type->data.fn.gen_param_info[0].src_index = 0; fn_type->data.fn.gen_param_info[0].gen_index = 0; fn_type->data.fn.gen_param_info[0].type = frame_type; gen_param_types.append(get_llvm_type(g, g->builtin_types.entry_usize)); param_di_types.append(get_llvm_di_type(g, g->builtin_types.entry_usize)); fn_type->data.fn.gen_param_info[1].src_index = 1; fn_type->data.fn.gen_param_info[1].gen_index = 1; fn_type->data.fn.gen_param_info[1].type = g->builtin_types.entry_usize; } else { fn_type->data.fn.gen_param_info = heap::c_allocator.allocate<FnGenParamInfo>(fn_type_id->param_count); for (size_t i = 0; i < fn_type_id->param_count; i += 1) { FnTypeParamInfo *src_param_info = &fn_type->data.fn.fn_type_id.param_info[i]; ZigType *type_entry = src_param_info->type; FnGenParamInfo *gen_param_info = &fn_type->data.fn.gen_param_info[i]; gen_param_info->src_index = i; gen_param_info->gen_index = SIZE_MAX; if (is_c_abi || !type_has_bits(g, type_entry)) continue; ZigType *gen_type; if (handle_is_ptr(g, type_entry)) { gen_type = get_pointer_to_type(g, type_entry, true); gen_param_info->is_byval = true; } else { gen_type = type_entry; } gen_param_info->gen_index = gen_param_types.length; gen_param_info->type = gen_type; gen_param_types.append(get_llvm_type(g, gen_type)); param_di_types.append(get_llvm_di_type(g, gen_type)); } } if (is_c_abi) { FnWalk fn_walk = {}; fn_walk.id = FnWalkIdTypes; fn_walk.data.types.param_di_types = &param_di_types; fn_walk.data.types.gen_param_types = &gen_param_types; walk_function_params(g, fn_type, &fn_walk); } fn_type->data.fn.gen_param_count = gen_param_types.length; for (size_t i = 0; i < gen_param_types.length; i += 1) { assert(gen_param_types.items[i] != nullptr); } if (!first_arg_return && fn_returns_c_abi_small_struct(fn_type_id)) { fn_type->data.fn.raw_type_ref = LLVMFunctionType(get_llvm_c_abi_type(g, gen_return_type), gen_param_types.items, (unsigned int)gen_param_types.length, fn_type_id->is_var_args); } else { fn_type->data.fn.raw_type_ref = LLVMFunctionType(get_llvm_type(g, gen_return_type), gen_param_types.items, (unsigned int)gen_param_types.length, fn_type_id->is_var_args); } const unsigned fn_addrspace = ZigLLVMDataLayoutGetProgramAddressSpace(g->target_data_ref); fn_type->llvm_type = LLVMPointerType(fn_type->data.fn.raw_type_ref, fn_addrspace); fn_type->data.fn.raw_di_type = ZigLLVMCreateSubroutineType(g->dbuilder, param_di_types.items, (int)param_di_types.length, 0); fn_type->llvm_di_type = ZigLLVMCreateDebugPointerType(g->dbuilder, fn_type->data.fn.raw_di_type, LLVMStoreSizeOfType(g->target_data_ref, fn_type->llvm_type), LLVMABIAlignmentOfType(g->target_data_ref, fn_type->llvm_type), ""); gen_param_types.deinit(); param_di_types.deinit(); } void resolve_llvm_types_fn(CodeGen *g, ZigFn *fn) { Error err; if (fn->raw_di_type != nullptr) return; ZigType *fn_type = fn->type_entry; if (!fn_is_async(fn)) { resolve_llvm_types_fn_type(g, fn_type); fn->raw_type_ref = fn_type->data.fn.raw_type_ref; fn->raw_di_type = fn_type->data.fn.raw_di_type; return; } ZigType *gen_return_type = g->builtin_types.entry_void; ZigList<ZigLLVMDIType *> param_di_types = {}; ZigList<LLVMTypeRef> gen_param_types = {}; // first "parameter" is return value param_di_types.append(nullptr); ZigType *frame_type = get_fn_frame_type(g, fn); ZigType *ptr_type = get_pointer_to_type(g, frame_type, false); if ((err = type_resolve(g, ptr_type, ResolveStatusLLVMFwdDecl))) zig_unreachable(); gen_param_types.append(ptr_type->llvm_type); param_di_types.append(ptr_type->llvm_di_type); // this parameter is used to pass the result pointer when await completes gen_param_types.append(get_llvm_type(g, g->builtin_types.entry_usize)); param_di_types.append(get_llvm_di_type(g, g->builtin_types.entry_usize)); fn->raw_type_ref = LLVMFunctionType(get_llvm_type(g, gen_return_type), gen_param_types.items, gen_param_types.length, false); fn->raw_di_type = ZigLLVMCreateSubroutineType(g->dbuilder, param_di_types.items, (int)param_di_types.length, 0); param_di_types.deinit(); gen_param_types.deinit(); } static void resolve_llvm_types_anyerror(CodeGen *g) { ZigType *entry = g->builtin_types.entry_global_error_set; entry->llvm_type = get_llvm_type(g, g->err_tag_type); ZigList<ZigLLVMDIEnumerator *> err_enumerators = {}; // reserve index 0 to indicate no error err_enumerators.append(ZigLLVMCreateDebugEnumerator(g->dbuilder, "(none)", 0)); for (size_t i = 1; i < g->errors_by_index.length; i += 1) { ErrorTableEntry *error_entry = g->errors_by_index.at(i); err_enumerators.append(ZigLLVMCreateDebugEnumerator(g->dbuilder, buf_ptr(&error_entry->name), i)); } // create debug type for error sets uint64_t tag_debug_size_in_bits = g->err_tag_type->size_in_bits; uint64_t tag_debug_align_in_bits = 8*g->err_tag_type->abi_align; ZigLLVMDIFile *err_set_di_file = nullptr; entry->llvm_di_type = ZigLLVMCreateDebugEnumerationType(g->dbuilder, ZigLLVMCompileUnitToScope(g->compile_unit), buf_ptr(&entry->name), err_set_di_file, 0, tag_debug_size_in_bits, tag_debug_align_in_bits, err_enumerators.items, err_enumerators.length, get_llvm_di_type(g, g->err_tag_type), ""); err_enumerators.deinit(); } static void resolve_llvm_types_async_frame(CodeGen *g, ZigType *frame_type, ResolveStatus wanted_resolve_status) { Error err; if ((err = type_resolve(g, frame_type, ResolveStatusSizeKnown))) zig_unreachable(); ZigType *passed_frame_type = fn_is_async(frame_type->data.frame.fn) ? frame_type : nullptr; resolve_llvm_types_struct(g, frame_type->data.frame.locals_struct, wanted_resolve_status, passed_frame_type); frame_type->llvm_type = frame_type->data.frame.locals_struct->llvm_type; frame_type->llvm_di_type = frame_type->data.frame.locals_struct->llvm_di_type; } static void resolve_llvm_types_any_frame(CodeGen *g, ZigType *any_frame_type, ResolveStatus wanted_resolve_status) { if (any_frame_type->llvm_di_type != nullptr) return; Buf *name = buf_sprintf("(%s header)", buf_ptr(&any_frame_type->name)); LLVMTypeRef frame_header_type = LLVMStructCreateNamed(LLVMGetGlobalContext(), buf_ptr(name)); any_frame_type->llvm_type = LLVMPointerType(frame_header_type, 0); unsigned dwarf_kind = ZigLLVMTag_DW_structure_type(); ZigLLVMDIFile *di_file = nullptr; ZigLLVMDIScope *di_scope = ZigLLVMCompileUnitToScope(g->compile_unit); unsigned line = 0; ZigLLVMDIType *frame_header_di_type = ZigLLVMCreateReplaceableCompositeType(g->dbuilder, dwarf_kind, buf_ptr(name), di_scope, di_file, line); any_frame_type->llvm_di_type = ZigLLVMCreateDebugPointerType(g->dbuilder, frame_header_di_type, 8*g->pointer_size_bytes, 8*g->builtin_types.entry_usize->abi_align, buf_ptr(&any_frame_type->name)); LLVMTypeRef llvm_void = LLVMVoidType(); LLVMTypeRef arg_types[] = {any_frame_type->llvm_type, g->builtin_types.entry_usize->llvm_type}; LLVMTypeRef fn_type = LLVMFunctionType(llvm_void, arg_types, 2, false); LLVMTypeRef usize_type_ref = get_llvm_type(g, g->builtin_types.entry_usize); ZigLLVMDIType *usize_di_type = get_llvm_di_type(g, g->builtin_types.entry_usize); ZigLLVMDIScope *compile_unit_scope = ZigLLVMCompileUnitToScope(g->compile_unit); ZigType *result_type = any_frame_type->data.any_frame.result_type; ZigType *ptr_result_type = (result_type == nullptr) ? nullptr : get_pointer_to_type(g, result_type, false); const unsigned fn_addrspace = ZigLLVMDataLayoutGetProgramAddressSpace(g->target_data_ref); LLVMTypeRef ptr_fn_llvm_type = LLVMPointerType(fn_type, fn_addrspace); if (result_type == nullptr) { g->anyframe_fn_type = ptr_fn_llvm_type; } ZigList<LLVMTypeRef> field_types = {}; ZigList<ZigLLVMDIType *> di_element_types = {}; // label (grep this): [fn_frame_struct_layout] field_types.append(ptr_fn_llvm_type); // fn_ptr field_types.append(usize_type_ref); // resume_index field_types.append(usize_type_ref); // awaiter bool have_result_type = result_type != nullptr && type_has_bits(g, result_type); if (have_result_type) { field_types.append(get_llvm_type(g, ptr_result_type)); // result_ptr_callee field_types.append(get_llvm_type(g, ptr_result_type)); // result_ptr_awaiter field_types.append(get_llvm_type(g, result_type)); // result if (codegen_fn_has_err_ret_tracing_arg(g, result_type)) { ZigType *ptr_stack_trace = get_pointer_to_type(g, get_stack_trace_type(g), false); field_types.append(get_llvm_type(g, ptr_stack_trace)); // ptr_stack_trace_callee field_types.append(get_llvm_type(g, ptr_stack_trace)); // ptr_stack_trace_awaiter } } LLVMStructSetBody(frame_header_type, field_types.items, field_types.length, false); di_element_types.append( ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "fn_ptr", di_file, line, 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length), ZigLLVM_DIFlags_Zero, usize_di_type)); di_element_types.append( ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "resume_index", di_file, line, 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length), ZigLLVM_DIFlags_Zero, usize_di_type)); di_element_types.append( ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "awaiter", di_file, line, 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length), ZigLLVM_DIFlags_Zero, usize_di_type)); if (have_result_type) { di_element_types.append( ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "result_ptr_callee", di_file, line, 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length), ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, ptr_result_type))); di_element_types.append( ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "result_ptr_awaiter", di_file, line, 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length), ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, ptr_result_type))); di_element_types.append( ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "result", di_file, line, 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length), ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, result_type))); if (codegen_fn_has_err_ret_tracing_arg(g, result_type)) { ZigType *ptr_stack_trace = get_pointer_to_type(g, get_stack_trace_type(g), false); di_element_types.append( ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "ptr_stack_trace_callee", di_file, line, 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length), ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, ptr_stack_trace))); di_element_types.append( ZigLLVMCreateDebugMemberType(g->dbuilder, ZigLLVMTypeToScope(any_frame_type->llvm_di_type), "ptr_stack_trace_awaiter", di_file, line, 8*LLVMABISizeOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMABIAlignmentOfType(g->target_data_ref, field_types.at(di_element_types.length)), 8*LLVMOffsetOfElement(g->target_data_ref, frame_header_type, di_element_types.length), ZigLLVM_DIFlags_Zero, get_llvm_di_type(g, ptr_stack_trace))); } }; ZigLLVMDIType *replacement_di_type = ZigLLVMCreateDebugStructType(g->dbuilder, compile_unit_scope, buf_ptr(name), di_file, line, 8*LLVMABISizeOfType(g->target_data_ref, frame_header_type), 8*LLVMABIAlignmentOfType(g->target_data_ref, frame_header_type), ZigLLVM_DIFlags_Zero, nullptr, di_element_types.items, di_element_types.length, 0, nullptr, ""); ZigLLVMReplaceTemporary(g->dbuilder, frame_header_di_type, replacement_di_type); field_types.deinit(); di_element_types.deinit(); } static void resolve_llvm_types(CodeGen *g, ZigType *type, ResolveStatus wanted_resolve_status) { assert(wanted_resolve_status > ResolveStatusSizeKnown); switch (type->id) { case ZigTypeIdInvalid: case ZigTypeIdMetaType: case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdEnumLiteral: case ZigTypeIdUndefined: case ZigTypeIdNull: case ZigTypeIdBoundFn: zig_unreachable(); case ZigTypeIdFloat: case ZigTypeIdOpaque: case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdUnreachable: assert(type->llvm_di_type != nullptr); return; case ZigTypeIdStruct: if (type->data.structure.special == StructSpecialSlice) return resolve_llvm_types_slice(g, type, wanted_resolve_status); else return resolve_llvm_types_struct(g, type, wanted_resolve_status, nullptr); case ZigTypeIdEnum: return resolve_llvm_types_enum(g, type, wanted_resolve_status); case ZigTypeIdUnion: return resolve_llvm_types_union(g, type, wanted_resolve_status); case ZigTypeIdPointer: return resolve_llvm_types_pointer(g, type, wanted_resolve_status); case ZigTypeIdInt: return resolve_llvm_types_integer(g, type); case ZigTypeIdOptional: return resolve_llvm_types_optional(g, type, wanted_resolve_status); case ZigTypeIdErrorUnion: return resolve_llvm_types_error_union(g, type); case ZigTypeIdArray: return resolve_llvm_types_array(g, type); case ZigTypeIdFn: return resolve_llvm_types_fn_type(g, type); case ZigTypeIdErrorSet: { if (type->llvm_di_type != nullptr) return; if (g->builtin_types.entry_global_error_set->llvm_type == nullptr) { resolve_llvm_types_anyerror(g); } type->llvm_type = g->builtin_types.entry_global_error_set->llvm_type; type->llvm_di_type = g->builtin_types.entry_global_error_set->llvm_di_type; return; } case ZigTypeIdVector: { if (type->llvm_di_type != nullptr) return; type->llvm_type = LLVMVectorType(get_llvm_type(g, type->data.vector.elem_type), type->data.vector.len); type->llvm_di_type = ZigLLVMDIBuilderCreateVectorType(g->dbuilder, 8 * type->abi_size, type->abi_align, get_llvm_di_type(g, type->data.vector.elem_type), type->data.vector.len); return; } case ZigTypeIdFnFrame: return resolve_llvm_types_async_frame(g, type, wanted_resolve_status); case ZigTypeIdAnyFrame: return resolve_llvm_types_any_frame(g, type, wanted_resolve_status); } zig_unreachable(); } LLVMTypeRef get_llvm_c_abi_type(CodeGen *g, ZigType *type) { assertNoError(type_resolve(g, type, ResolveStatusLLVMFull)); assert(type->abi_size == 0 || type->abi_size >= LLVMABISizeOfType(g->target_data_ref, type->llvm_type)); assert(type->abi_align == 0 || type->abi_align >= LLVMABIAlignmentOfType(g->target_data_ref, type->llvm_type)); return type->llvm_c_abi_type; } LLVMTypeRef get_llvm_type(CodeGen *g, ZigType *type) { assertNoError(type_resolve(g, type, ResolveStatusLLVMFull)); assert(type->abi_size == 0 || type->abi_size >= LLVMABISizeOfType(g->target_data_ref, type->llvm_type)); assert(type->abi_align == 0 || type->abi_align >= LLVMABIAlignmentOfType(g->target_data_ref, type->llvm_type)); return type->llvm_type; } ZigLLVMDIType *get_llvm_di_type(CodeGen *g, ZigType *type) { assertNoError(type_resolve(g, type, ResolveStatusLLVMFull)); return type->llvm_di_type; } void src_assert_impl(bool ok, AstNode *source_node, char const *file, unsigned int line) { if (ok) return; if (source_node == nullptr) { fprintf(stderr, "when analyzing (unknown source location) "); } else { RootStruct *root_struct = source_node->owner->data.structure.root_struct; fprintf(stderr, "when analyzing %s:%u:%u ", buf_ptr(root_struct->path), node_line_onebased(source_node), node_column_onebased(source_node)); } fprintf(stderr, "in compiler source at %s:%u: ", file, line); const char *msg = "assertion failed. This is a bug in the Zig compiler."; stage2_panic(msg, strlen(msg)); } Error analyze_import(CodeGen *g, ZigType *source_import, Buf *import_target_str, ZigType **out_import, Buf **out_import_target_path, Buf *out_full_path) { Error err; Buf *search_dir; ZigPackage *cur_scope_pkg = source_import->data.structure.root_struct->package; assert(cur_scope_pkg); ZigPackage *target_package; auto package_entry = cur_scope_pkg->package_table.maybe_get(import_target_str); SourceKind source_kind; if (package_entry) { target_package = package_entry->value; *out_import_target_path = &target_package->root_src_path; search_dir = &target_package->root_src_dir; source_kind = SourceKindPkgMain; } else { // try it as a filename target_package = cur_scope_pkg; *out_import_target_path = import_target_str; // search relative to importing file search_dir = buf_alloc(); os_path_dirname(source_import->data.structure.root_struct->path, search_dir); source_kind = SourceKindNonRoot; } buf_resize(out_full_path, 0); os_path_join(search_dir, *out_import_target_path, out_full_path); Buf *import_code = buf_alloc(); Buf *resolved_path = buf_alloc(); Buf *resolve_paths[] = { out_full_path, }; *resolved_path = os_path_resolve(resolve_paths, 1); auto import_entry = g->import_table.maybe_get(resolved_path); if (import_entry) { *out_import = import_entry->value; return ErrorNone; } if (source_kind == SourceKindNonRoot) { Buf *pkg_root_src_dir = &cur_scope_pkg->root_src_dir; Buf resolved_root_src_dir = os_path_resolve(&pkg_root_src_dir, 1); if (!buf_starts_with_buf(resolved_path, &resolved_root_src_dir)) { return ErrorImportOutsidePkgPath; } } if ((err = file_fetch(g, resolved_path, import_code))) { return err; } *out_import = add_source_file(g, target_package, resolved_path, import_code, source_kind); return ErrorNone; } void AstNode::src() { RootStruct *root_struct = this->owner->data.structure.root_struct; uint32_t line = root_struct->token_locs[this->main_token].line + 1; uint32_t column = root_struct->token_locs[this->main_token].column + 1; fprintf(stderr, "%s:%" PRIu32 ":%" PRIu32 "\n", buf_ptr(root_struct->path), line, column); } void Stage1Air::src() { Stage1Air *it; for (it = this; it != nullptr && it->source_node != nullptr; it = it->parent_exec) { it->source_node->src(); } } bool is_anon_container(ZigType *ty) { return ty->id == ZigTypeIdStruct && ( ty->data.structure.special == StructSpecialInferredTuple || ty->data.structure.special == StructSpecialInferredStruct); } bool is_opt_err_set(ZigType *ty) { return ty->id == ZigTypeIdErrorSet || (ty->id == ZigTypeIdOptional && ty->data.maybe.child_type->id == ZigTypeIdErrorSet); } // Returns whether the x_optional field of ZigValue is active. bool type_has_optional_repr(ZigType *ty) { if (ty->id != ZigTypeIdOptional) { return false; } else if (get_src_ptr_type(ty) != nullptr) { return false; } else if (is_opt_err_set(ty)) { return false; } else { return true; } } void copy_const_val(CodeGen *g, ZigValue *dest, ZigValue *src) { uint32_t prev_align = dest->llvm_align; ConstParent prev_parent = dest->parent; memcpy(dest, src, sizeof(ZigValue)); dest->llvm_align = prev_align; if (src->special != ConstValSpecialStatic) return; dest->parent = prev_parent; if (dest->type->id == ZigTypeIdStruct) { dest->data.x_struct.fields = alloc_const_vals_ptrs(g, dest->type->data.structure.src_field_count); for (size_t i = 0; i < dest->type->data.structure.src_field_count; i += 1) { TypeStructField *type_struct_field = dest->type->data.structure.fields[i]; if (type_struct_field->is_comptime) { // comptime-known values are stored in the field init_val inside // the struct type. The data stored here is not supposed to be read // at all; the code should look at the type system and notice the field // is comptime and look at the type to learn the value. continue; } copy_const_val(g, dest->data.x_struct.fields[i], src->data.x_struct.fields[i]); dest->data.x_struct.fields[i]->parent.id = ConstParentIdStruct; dest->data.x_struct.fields[i]->parent.data.p_struct.struct_val = dest; dest->data.x_struct.fields[i]->parent.data.p_struct.field_index = i; } } else if (dest->type->id == ZigTypeIdArray) { switch (dest->data.x_array.special) { case ConstArraySpecialNone: { dest->data.x_array.data.s_none.elements = g->pass1_arena->allocate<ZigValue>(dest->type->data.array.len); for (uint64_t i = 0; i < dest->type->data.array.len; i += 1) { copy_const_val(g, &dest->data.x_array.data.s_none.elements[i], &src->data.x_array.data.s_none.elements[i]); dest->data.x_array.data.s_none.elements[i].parent.id = ConstParentIdArray; dest->data.x_array.data.s_none.elements[i].parent.data.p_array.array_val = dest; dest->data.x_array.data.s_none.elements[i].parent.data.p_array.elem_index = i; } break; } case ConstArraySpecialUndef: { // Nothing to copy; the above memcpy did everything we needed. break; } case ConstArraySpecialBuf: { dest->data.x_array.data.s_buf = buf_create_from_buf(src->data.x_array.data.s_buf); break; } } } else if (dest->type->id == ZigTypeIdUnion) { bigint_init_bigint(&dest->data.x_union.tag, &src->data.x_union.tag); dest->data.x_union.payload = g->pass1_arena->create<ZigValue>(); copy_const_val(g, dest->data.x_union.payload, src->data.x_union.payload); dest->data.x_union.payload->parent.id = ConstParentIdUnion; dest->data.x_union.payload->parent.data.p_union.union_val = dest; } else if (type_has_optional_repr(dest->type) && dest->data.x_optional != nullptr) { dest->data.x_optional = g->pass1_arena->create<ZigValue>(); copy_const_val(g, dest->data.x_optional, src->data.x_optional); dest->data.x_optional->parent.id = ConstParentIdOptionalPayload; dest->data.x_optional->parent.data.p_optional_payload.optional_val = dest; } } bool optional_value_is_null(ZigValue *val) { assert(val->special == ConstValSpecialStatic); if (get_src_ptr_type(val->type) != nullptr) { if (val->data.x_ptr.special == ConstPtrSpecialNull) { return true; } else if (val->data.x_ptr.special == ConstPtrSpecialHardCodedAddr) { return val->data.x_ptr.data.hard_coded_addr.addr == 0; } else { return false; } } else if (is_opt_err_set(val->type)) { return val->data.x_err_set == nullptr; } else { return val->data.x_optional == nullptr; } } bool type_is_numeric(ZigType *ty) { switch (ty->id) { case ZigTypeIdInvalid: zig_unreachable(); case ZigTypeIdComptimeFloat: case ZigTypeIdComptimeInt: case ZigTypeIdInt: case ZigTypeIdFloat: case ZigTypeIdUndefined: return true; case ZigTypeIdVector: return type_is_numeric(ty->data.vector.elem_type); case ZigTypeIdMetaType: case ZigTypeIdVoid: case ZigTypeIdBool: case ZigTypeIdUnreachable: case ZigTypeIdPointer: case ZigTypeIdArray: case ZigTypeIdStruct: case ZigTypeIdNull: case ZigTypeIdOptional: case ZigTypeIdErrorUnion: case ZigTypeIdErrorSet: case ZigTypeIdEnum: case ZigTypeIdUnion: case ZigTypeIdFn: case ZigTypeIdBoundFn: case ZigTypeIdOpaque: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: case ZigTypeIdEnumLiteral: return false; } zig_unreachable(); } static void dump_value_indent_error_set(ZigValue *val, int indent) { fprintf(stderr, "<TODO dump value>\n"); } static void dump_value_indent(ZigValue *val, int indent); static void dump_value_indent_ptr(ZigValue *val, int indent) { switch (val->data.x_ptr.special) { case ConstPtrSpecialInvalid: fprintf(stderr, "<!invalid ptr!>\n"); return; case ConstPtrSpecialNull: fprintf(stderr, "<null>\n"); return; case ConstPtrSpecialRef: fprintf(stderr, "<ref\n"); dump_value_indent(val->data.x_ptr.data.ref.pointee, indent + 1); break; case ConstPtrSpecialBaseStruct: { ZigValue *struct_val = val->data.x_ptr.data.base_struct.struct_val; size_t field_index = val->data.x_ptr.data.base_struct.field_index; fprintf(stderr, "<struct %p field %zu\n", struct_val, field_index); if (struct_val != nullptr) { ZigValue *field_val = struct_val->data.x_struct.fields[field_index]; if (field_val != nullptr) { dump_value_indent(field_val, indent + 1); } else { for (int i = 0; i < indent; i += 1) { fprintf(stderr, " "); } fprintf(stderr, "(invalid null field)\n"); } } break; } case ConstPtrSpecialBaseOptionalPayload: { ZigValue *optional_val = val->data.x_ptr.data.base_optional_payload.optional_val; fprintf(stderr, "<optional %p payload\n", optional_val); if (optional_val != nullptr) { dump_value_indent(optional_val, indent + 1); } break; } default: fprintf(stderr, "TODO dump more pointer things\n"); } for (int i = 0; i < indent; i += 1) { fprintf(stderr, " "); } fprintf(stderr, ">\n"); } static void dump_value_indent(ZigValue *val, int indent) { for (int i = 0; i < indent; i += 1) { fprintf(stderr, " "); } fprintf(stderr, "Value@%p(", val); if (val->type != nullptr) { fprintf(stderr, "%s)", buf_ptr(&val->type->name)); } else { fprintf(stderr, "type=nullptr)"); } switch (val->special) { case ConstValSpecialUndef: fprintf(stderr, "[undefined]\n"); return; case ConstValSpecialLazy: fprintf(stderr, "[lazy]\n"); return; case ConstValSpecialRuntime: fprintf(stderr, "[runtime]\n"); return; case ConstValSpecialStatic: break; } if (val->type == nullptr) return; switch (val->type->id) { case ZigTypeIdInvalid: fprintf(stderr, "<invalid>\n"); return; case ZigTypeIdUnreachable: fprintf(stderr, "<unreachable>\n"); return; case ZigTypeIdUndefined: fprintf(stderr, "<undefined>\n"); return; case ZigTypeIdVoid: fprintf(stderr, "<{}>\n"); return; case ZigTypeIdMetaType: fprintf(stderr, "<%s>\n", buf_ptr(&val->data.x_type->name)); return; case ZigTypeIdBool: fprintf(stderr, "<%s>\n", val->data.x_bool ? "true" : "false"); return; case ZigTypeIdComptimeInt: case ZigTypeIdInt: { Buf *tmp_buf = buf_alloc(); bigint_append_buf(tmp_buf, &val->data.x_bigint, 10); fprintf(stderr, "<%s>\n", buf_ptr(tmp_buf)); buf_destroy(tmp_buf); return; } case ZigTypeIdComptimeFloat: case ZigTypeIdFloat: fprintf(stderr, "<TODO dump number>\n"); return; case ZigTypeIdStruct: fprintf(stderr, "<struct\n"); for (size_t i = 0; i < val->type->data.structure.src_field_count; i += 1) { for (int j = 0; j < indent; j += 1) { fprintf(stderr, " "); } TypeStructField *field = val->type->data.structure.fields[i]; fprintf(stderr, "%s: ", buf_ptr(field->name)); if (field->is_comptime) { fprintf(stderr, "<comptime field>"); } else if (val->data.x_struct.fields == nullptr) { fprintf(stderr, "<null>\n"); } else { dump_value_indent(val->data.x_struct.fields[i], 1); } } for (int i = 0; i < indent; i += 1) { fprintf(stderr, " "); } fprintf(stderr, ">\n"); return; case ZigTypeIdOptional: if (get_src_ptr_type(val->type) != nullptr) { return dump_value_indent_ptr(val, indent); } else if (val->type->data.maybe.child_type->id == ZigTypeIdErrorSet) { return dump_value_indent_error_set(val, indent); } else { fprintf(stderr, "<\n"); dump_value_indent(val->data.x_optional, indent + 1); for (int i = 0; i < indent; i += 1) { fprintf(stderr, " "); } fprintf(stderr, ">\n"); return; } case ZigTypeIdErrorUnion: if (val->data.x_err_union.payload != nullptr) { fprintf(stderr, "<\n"); dump_value_indent(val->data.x_err_union.payload, indent + 1); } else { fprintf(stderr, "<\n"); dump_value_indent(val->data.x_err_union.error_set, 0); } for (int i = 0; i < indent; i += 1) { fprintf(stderr, " "); } fprintf(stderr, ">\n"); return; case ZigTypeIdPointer: return dump_value_indent_ptr(val, indent); case ZigTypeIdErrorSet: return dump_value_indent_error_set(val, indent); case ZigTypeIdVector: case ZigTypeIdArray: case ZigTypeIdNull: case ZigTypeIdEnum: case ZigTypeIdUnion: case ZigTypeIdFn: case ZigTypeIdBoundFn: case ZigTypeIdOpaque: case ZigTypeIdFnFrame: case ZigTypeIdAnyFrame: case ZigTypeIdEnumLiteral: fprintf(stderr, "<TODO dump value>\n"); return; } zig_unreachable(); } void ZigValue::dump() { dump_value_indent(this, 0); } // float ops that take a single argument //TODO Powi, Pow, minnum, maxnum, maximum, minimum, copysign, lround, llround, lrint, llrint const char *float_op_to_name(BuiltinFnId op) { switch (op) { case BuiltinFnIdSqrt: return "sqrt"; case BuiltinFnIdSin: return "sin"; case BuiltinFnIdCos: return "cos"; case BuiltinFnIdExp: return "exp"; case BuiltinFnIdExp2: return "exp2"; case BuiltinFnIdLog: return "log"; case BuiltinFnIdLog10: return "log10"; case BuiltinFnIdLog2: return "log2"; case BuiltinFnIdFabs: return "fabs"; case BuiltinFnIdFloor: return "floor"; case BuiltinFnIdCeil: return "ceil"; case BuiltinFnIdTrunc: return "trunc"; case BuiltinFnIdNearbyInt: return "nearbyint"; case BuiltinFnIdRound: return "round"; default: zig_unreachable(); } }
/***** CLAIRE Compilation of file /Users/ycaseau/claire/v3.5/src/compile/odefine.cl [version 3.5.01 / safety 5] Sun Jul 24 08:43:46 2016 *****/ #include <claire.h> #include <Kernel.h> #include <Core.h> #include <Language.h> #include <Reader.h> #include <Optimize.h> ClaireType * c_type_List_Optimize(List *v13540) { GC_BIND; ;{ ClaireType *Result ; if (((v13540->of == (NULL)) ? CTRUE : CFALSE) != CTRUE) Result = param_I_class(Kernel._list,v13540->of); else { OID v61427 = _oid_(Kernel.emptySet); { OID gc_local; ITERATE(v61579); for (START(v13540->args); NEXT(v61579);) if (boolean_I_any(v61427) == CTRUE) v61427= _oid_(meet_class(OBJECT(ClaireClass,v61427),class_I_type(ptype_type(OBJECT(ClaireType,(*Optimize.c_type)(v61579)))))); else v61427= _oid_(class_I_type(ptype_type(OBJECT(ClaireType,(*Optimize.c_type)(v61579))))); } Result = nth_class1(Kernel._list,OBJECT(ClaireType,v61427)); } GC_UNBIND; return (Result);} } OID c_code_List_Optimize(List *v13540) { GC_BIND; (Optimize.OPT->allocation = CTRUE); { OID Result = 0; { List * v82400; { { List * v88616 = ((List *) GC_OBJECT(List,new_object_class(Language._List))); { Construct * v64279 = v88616; list * v64280; { bag *v_list; OID v_val; OID v61579,CLcount; v_list = GC_OBJECT(list,v13540->args); v64280 = v_list->clone(); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v61579 = (*(v_list))[CLcount]; v_val = c_gc_I_any2(GC_OID((*Optimize.c_code)(v61579, _oid_(Kernel._any))),GC_OBJECT(ClaireType,OBJECT(ClaireType,(*Optimize.c_type)(v61579)))); (*((list *) v64280))[CLcount] = v_val;} } (v64279->args = v64280);} add_I_property(Kernel.instances,Language._List,11,_oid_(v88616)); v82400 = v88616; } GC_OBJECT(List,v82400);} if (((v13540->of == (NULL)) ? CTRUE : CFALSE) != CTRUE) { { ClaireBoolean * g0307I; { ClaireBoolean *v_or; { v_or = ((Optimize.compiler->safety > 4) ? CTRUE : CFALSE); if (v_or == CTRUE) g0307I =CTRUE; else { v_or = ((equal(_oid_(v13540->of),_oid_(Kernel.emptySet)) == CTRUE) ? CTRUE : CFALSE); if (v_or == CTRUE) g0307I =CTRUE; else { { OID v42810; { OID gc_local; ITERATE(v61579); v42810= Kernel.cfalse; bag *v61579_support; v61579_support = GC_OBJECT(list,v13540->args); for (START(v61579_support); NEXT(v61579);) { GC_LOOP; if (_inf_equal_type(GC_OBJECT(ClaireType,OBJECT(ClaireType,(*Optimize.c_type)(v61579))),GC_OBJECT(ClaireType,v13540->of)) != CTRUE) { v42810 = Kernel.ctrue; break;} GC_UNLOOP;} } v_or = not_any(v42810); } if (v_or == CTRUE) g0307I =CTRUE; else g0307I = CFALSE;} } } } if (g0307I == CTRUE) { (v82400->of = v13540->of); Result = _oid_(v82400); } else { warn_void(); { list * v43771; { { OID v_bag; GC_ANY(v43771= list::empty(Kernel.emptySet)); { { list * v72556;{ bag *v_list; OID v_val; OID v61579,CLcount; v_list = GC_OBJECT(list,v13540->args); v72556 = v_list->clone(); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v61579 = (*(v_list))[CLcount]; v_val = (*Optimize.c_type)(v61579); (*((list *) v72556))[CLcount] = v_val;} } v_bag=_oid_(v72556);} GC_OID(v_bag);} ((list *) v43771)->addFast(v_bag); ((list *) v43771)->addFast(GC_OID(_oid_(v13540->of)));} GC_OBJECT(list,v43771);} tformat_string(CSTRING("unsafe typed list: ~S not in ~S [262]\n"),2,v43771); } { OID v65874; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.check_in); (v88616->args = list::alloc(3,_oid_(v82400), _oid_(Kernel._list), GC_OID(_oid_(v13540->of)))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65874 = _oid_(v88616); } Result = (*Optimize.c_code)(v65874, _oid_(Kernel._list)); } } } } else Result = _oid_(v82400); } GC_UNBIND; return (Result);} } ClaireType * c_type_Set_Optimize(Set *v13540) { GC_BIND; ;{ ClaireType *Result ; if (((v13540->of == (NULL)) ? CTRUE : CFALSE) != CTRUE) Result = param_I_class(Kernel._set,v13540->of); else { OID v61427 = _oid_(Kernel.emptySet); { OID gc_local; ITERATE(v61579); for (START(v13540->args); NEXT(v61579);) if (boolean_I_any(v61427) == CTRUE) v61427= _oid_(meet_class(OBJECT(ClaireClass,v61427),class_I_type(OBJECT(ClaireType,(*Optimize.c_type)(v61579))))); else v61427= _oid_(class_I_type(OBJECT(ClaireType,(*Optimize.c_type)(v61579)))); } Result = nth_class1(Kernel._set,OBJECT(ClaireType,v61427)); } GC_UNBIND; return (Result);} } OID c_code_Set_Optimize(Set *v13540) { GC_BIND; (Optimize.OPT->allocation = CTRUE); { OID Result = 0; { Set * v82400; { { Set * v88616 = ((Set *) GC_OBJECT(Set,new_object_class(Language._Set))); { Construct * v64307 = v88616; list * v64308; { bag *v_list; OID v_val; OID v61579,CLcount; v_list = GC_OBJECT(list,v13540->args); v64308 = v_list->clone(); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v61579 = (*(v_list))[CLcount]; v_val = c_gc_I_any2(GC_OID((*Optimize.c_code)(v61579, _oid_(Kernel._any))),GC_OBJECT(ClaireType,OBJECT(ClaireType,(*Optimize.c_type)(v61579)))); (*((list *) v64308))[CLcount] = v_val;} } (v64307->args = v64308);} add_I_property(Kernel.instances,Language._Set,11,_oid_(v88616)); v82400 = v88616; } GC_OBJECT(Set,v82400);} if (((v13540->of == (NULL)) ? CTRUE : CFALSE) != CTRUE) { { ClaireBoolean * g0314I; { ClaireBoolean *v_or; { v_or = ((Optimize.compiler->safety > 4) ? CTRUE : CFALSE); if (v_or == CTRUE) g0314I =CTRUE; else { v_or = ((equal(_oid_(v13540->of),_oid_(Kernel.emptySet)) == CTRUE) ? CTRUE : CFALSE); if (v_or == CTRUE) g0314I =CTRUE; else { { OID v69718; { OID gc_local; ITERATE(v61579); v69718= Kernel.cfalse; bag *v61579_support; v61579_support = GC_OBJECT(list,v13540->args); for (START(v61579_support); NEXT(v61579);) { GC_LOOP; if (_inf_equal_type(GC_OBJECT(ClaireType,OBJECT(ClaireType,(*Optimize.c_type)(v61579))),GC_OBJECT(ClaireType,v13540->of)) != CTRUE) { v69718 = Kernel.ctrue; break;} GC_UNLOOP;} } v_or = not_any(v69718); } if (v_or == CTRUE) g0314I =CTRUE; else g0314I = CFALSE;} } } } if (g0314I == CTRUE) { (v82400->of = v13540->of); Result = _oid_(v82400); } else { warn_void(); { list * v70679; { { OID v_bag; GC_ANY(v70679= list::empty(Kernel.emptySet)); { { list * v72563;{ bag *v_list; OID v_val; OID v61579,CLcount; v_list = GC_OBJECT(list,v13540->args); v72563 = v_list->clone(); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v61579 = (*(v_list))[CLcount]; v_val = (*Optimize.c_type)(v61579); (*((list *) v72563))[CLcount] = v_val;} } v_bag=_oid_(v72563);} GC_OID(v_bag);} ((list *) v70679)->addFast(v_bag); ((list *) v70679)->addFast(GC_OID(_oid_(v13540->of)));} GC_OBJECT(list,v70679);} tformat_string(CSTRING("unsafe typed set: ~S not in ~S [262]\n"),2,v70679); } { OID v72601; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.check_in); (v88616->args = list::alloc(3,_oid_(v82400), _oid_(Kernel._set), GC_OID(_oid_(v13540->of)))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v72601 = _oid_(v88616); } Result = (*Optimize.c_code)(v72601, _oid_(Kernel._set)); } } } } else Result = _oid_(v82400); } GC_UNBIND; return (Result);} } ClaireType * c_type_Tuple_Optimize(Tuple *v13540) { GC_BIND; { ClaireType *Result ; { list * v73562; { { bag *v_list; OID v_val; OID v82400,CLcount; v_list = v13540->args; v73562 = v_list->clone(); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v82400 = (*(v_list))[CLcount]; v_val = (*Optimize.c_type)(v82400); (*((list *) v73562))[CLcount] = v_val;} } GC_OBJECT(list,v73562);} Result = tuple_I_list(v73562); } GC_UNBIND; return (Result);} } OID c_code_Tuple_Optimize(Tuple *v13540) { GC_BIND; (Optimize.OPT->allocation = CTRUE); { OID Result = 0; { Tuple * v88616 = ((Tuple *) GC_OBJECT(Tuple,new_object_class(Language._Tuple))); { Construct * v64336 = v88616; list * v64337; { bag *v_list; OID v_val; OID v61579,CLcount; v_list = GC_OBJECT(list,v13540->args); v64337 = v_list->clone(); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v61579 = (*(v_list))[CLcount]; v_val = c_gc_I_any2(GC_OID((*Optimize.c_code)(v61579, _oid_(Kernel._any))),GC_OBJECT(ClaireType,OBJECT(ClaireType,(*Optimize.c_type)(v61579)))); (*((list *) v64337))[CLcount] = v_val;} } (v64336->args = v64337);} add_I_property(Kernel.instances,Language._Tuple,11,_oid_(v88616)); Result = _oid_(v88616); } GC_UNBIND; return (Result);} } ClaireType * c_type_Definition_Optimize(Definition *v13540) { { ClaireType *Result ; if (_inf_equalt_class(v13540->arg,Kernel._exception) == CTRUE) Result = Kernel.emptySet; else Result = v13540->arg; return (Result);} } OID c_code_Definition_Optimize(Definition *v13540,ClaireClass *v82395) { GC_BIND; { OID Result = 0; { ClaireClass * v61558 = v13540->arg; Variable * v61589; { { Cint v97587; { (Optimize.OPT->max_vars = (Optimize.OPT->max_vars+1)); v97587 = 0; } v61589 = Variable_I_symbol(OBJECT(symbol,Optimize._starname_star->value),v97587,v61558); } GC_OBJECT(Variable,v61589);} OID v61579 = GC_OID(total_ask_class(v61558,GC_OBJECT(list,v13540->args))); if (v61558->open <= 0) close_exception(((general_error *) (*Core._general_error)(_string_(CSTRING("[105] cannot instantiate ~S")), _oid_(list::alloc(1,_oid_(v61558)))))); if (boolean_I_any(v61579) == CTRUE) Result = (*Optimize.c_code)(v61579, _oid_(v82395)); else { OID v98548; { Let * v88616 = ((Let *) GC_OBJECT(Let,new_object_class(Language._Let))); (v88616->var = v61589); { Let * v64341 = v88616; OID v64342; { Cast * v88616 = ((Cast *) GC_OBJECT(Cast,new_object_class(Language._Cast))); { Cast * v64343 = v88616; OID v64344; { OID v103353; { { OID v124495; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.new_I); (v88616->args = list::alloc(1,_oid_(v61558))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v124495 = _oid_(v88616); } v103353 = (*Optimize.c_code)(v124495, _oid_(Kernel._object)); } GC_OID(v103353);} v64344 = c_gc_I_any1(v103353); } (v64343->arg = v64344);} (v88616->set_arg = v61558); add_I_property(Kernel.instances,Language._Cast,11,_oid_(v88616)); v64342 = _oid_(v88616); } (v64341->value = v64342);} { Let * v64368 = v88616; OID v64369; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); store_object(v88616, 2, Kernel._object, analyze_I_class(v61558,_oid_(v61589),GC_OBJECT(list,v13540->args),list::empty()), CFALSE); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v64369 = _oid_(v88616); } (v64368->arg = v64369);} add_I_property(Kernel.instances,Language._Let,11,_oid_(v88616)); v98548 = _oid_(v88616); } Result = (*Optimize.c_code)(v98548, _oid_(v82395)); } } GC_UNBIND; return (Result);} } OID total_ask_class(ClaireClass *v13540,list *v82388) { GC_BIND; { OID Result = 0; { list * v63772 = GC_OBJECT(list,OBJECT(list,(*Optimize.get_indexed)(_oid_(v13540)))); Cint v82390 = v63772->length; { ClaireBoolean * g0334I; { ClaireBoolean *v_and; { v_and = not_any(_oid_(Optimize.compiler->diet_ask)); if (v_and == CFALSE) g0334I =CFALSE; else { v_and = ((v82388->length == (v82390-1)) ? CTRUE : CFALSE); if (v_and == CFALSE) g0334I =CFALSE; else { v_and = ((v13540->open == ClEnv->ephemeral) ? CTRUE : ((_inf_equalt_class(v13540,Kernel._exception) == CTRUE) ? CTRUE : CFALSE)); if (v_and == CFALSE) g0334I =CFALSE; else { v_and = ((v82390 <= 4) ? CTRUE : CFALSE); if (v_and == CFALSE) g0334I =CFALSE; else { { OID v129300; { Cint v82385 = 2; Cint v64370 = v82390; { v129300= _oid_(CFALSE); while ((v82385 <= v64370)) { if ((((*Kernel.srange)((*(v63772))[v82385]) == _oid_(Kernel._integer)) ? CTRUE : (((*Kernel.srange)((*(v63772))[v82385]) == _oid_(Kernel._any)) ? CTRUE : CFALSE)) != CTRUE) { v129300 = Kernel.ctrue; break;} ++v82385; } } } v_and = not_any(v129300); } if (v_and == CFALSE) g0334I =CFALSE; else g0334I = CTRUE;} } } } } } if (g0334I == CTRUE) { OID v61558; { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = ((v82388->length == 0) ? Core.new_I : Optimize.anyObject_I )); { Call * v64373 = v88616; list * v64374; { list * v1111; { { bag *v_list; OID v_val; OID v82400,CLcount; v_list = v82388; v1111 = v_list->clone(); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v82400 = (*(v_list))[CLcount]; v_val = c_gc_I_any1(GC_OID((*Optimize.c_code)(GC_OID((*(OBJECT(bag,(*Core.args)(v82400))))[2]), _oid_(Kernel._any)))); (*((list *) v1111))[CLcount] = v_val;} } GC_OBJECT(list,v1111);} v64374 = cons_any(_oid_(v13540),v1111); } (v64373->args = v64374);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v61558 = _oid_(v88616); } GC_OID(v61558);} OID v82389 = GC_OID(_oid_(_at_property1(Kernel.close,v13540))); if (_inf_equal_type(v13540,Kernel._exception) != CTRUE) (Optimize.OPT->allocation = CTRUE); if (v82388->length == 0) v61558= GC_OID((*Optimize.c_code)(v61558)); if (boolean_I_any(v82389) == CTRUE) { Call_method1 * v88616 = ((Call_method1 *) GC_OBJECT(Call_method1,new_object_class(Language._Call_method1))); update_property(Kernel.arg, v88616, 2, Kernel._object, v82389); (v88616->args = list::alloc(1,v61558)); add_I_property(Kernel.instances,Language._Call_method1,11,_oid_(v88616)); Result = _oid_(v88616); } else Result = v61558; } else Result = Kernel.cfalse; } } GC_UNBIND; return (Result);} } OID analyze_I_class(ClaireClass *v82379,OID v13540,list *v61567,list *v63772) { GC_RESERVE(15); // v3.0.55 optim ! { OID Result = 0; { ClaireBoolean * v117673 = ((v82379->open != 4) ? ((boolean_I_any(_oid_(v63772)) != CTRUE) ? ((Optimize.compiler->class2file_ask != CTRUE) ? CTRUE: CFALSE): CFALSE): CFALSE); list * v82394; { { bag *v_list; OID v_val; OID v82400,CLcount; v_list = v61567; v82394 = v_list->clone(Kernel._any); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v82400 = (*(v_list))[CLcount]; { OID v82392 = GC_OID((*(OBJECT(Call,v82400)->args))[1]); OID v82401 = GC_OID((*(OBJECT(Call,v82400)->args))[2]); ClaireObject * v82395 = GC_OBJECT(ClaireObject,_at_property1(OBJECT(property,v82392),v82379)); ClaireBoolean * v45118 = (((*Kernel.open)(v82392) == 0) ? ((Kernel._slot == v82395->isa) ? CTRUE: CFALSE): CFALSE); GC__ANY(v63772 = v63772->addFast(v82392), 4); { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = ((v45118 == CTRUE) ? Kernel.put : Core.write )); { Call * v64376 = v88616; list * v64398; { OID v_bag; GC_ANY(v64398= list::empty(Kernel.emptySet)); ((list *) v64398)->addFast(v82392); ((list *) v64398)->addFast(v13540); { if ((v45118 != CTRUE) || (_inf_equal_type(GC_OBJECT(ClaireType,OBJECT(ClaireType,(*Optimize.c_type)(v82401))),GC_OBJECT(ClaireType,OBJECT(ClaireType,(*Kernel.range)(_oid_(v82395))))) == CTRUE)) v_bag = v82401; else v_bag = c_check_any(GC_OID((*Optimize.c_code)(v82401, _oid_(Kernel._any))),GC_OID((*Optimize.c_code)(GC_OID((*Kernel.range)(_oid_(v82395))), _oid_(Kernel._type)))); GC_OID(v_bag);} ((list *) v64398)->addFast(v_bag);} (v64376->args = v64398);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_val = _oid_(v88616); } } (*((list *) v82394))[CLcount] = v_val;} } GC_OBJECT(list,v82394);} if (v117673 == CTRUE) { { OID v24175; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.add); (v88616->args = list::alloc(3,_oid_(Kernel.instances), _oid_(v82379), v13540)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v24175 = _oid_(v88616); } v82394 = v82394->addFast(v24175); } GC_OBJECT(list,v82394);} if (Optimize.compiler->class2file_ask != CTRUE) { OID gc_local; ITERATE(v82395); bag *v82395_support; v82395_support = GC_OBJECT(list,OBJECT(bag,(*Optimize.get_indexed)(_oid_(v82379)))); for (START(v82395_support); NEXT(v82395);) { GC_LOOP; { property * v82392 = OBJECT(restriction,v82395)->selector; OID v82398 = GC_OID(OBJECT(slot,v82395)->DEFAULT); { ClaireBoolean * g0342I; { ClaireBoolean *v_and; { v_and = known_ask_any(v82398); if (v_and == CFALSE) g0342I =CFALSE; else { { OID v26097; if (multi_ask_any(_oid_(v82392)) == CTRUE) v26097 = v82398; else v26097 = Kernel.ctrue; v_and = boolean_I_any(v26097); } if (v_and == CFALSE) g0342I =CFALSE; else { v_and = not_any(_oid_(v63772->memq(_oid_(v82392)))); if (v_and == CFALSE) g0342I =CFALSE; else { v_and = ((((v82392->inverse == (NULL)) ? CTRUE : CFALSE) != CTRUE) ? CTRUE : ((((v82392->if_write == CNULL) ? CTRUE : CFALSE) != CTRUE) ? CTRUE : (((OBJECT(slot,v82395)->srange != Kernel._object) && ((OBJECT(slot,v82395)->srange != Kernel._float) && (inherit_ask_class(OWNER(v82398),Kernel._integer) != CTRUE))) ? CTRUE : CFALSE))); if (v_and == CFALSE) g0342I =CFALSE; else g0342I = CTRUE;} } } } } if (g0342I == CTRUE) { OID v45936; if (designated_ask_any(v82398) == CTRUE) v45936 = v82398; else { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.DEFAULT); { Call * v64402 = v88616; list * v64403; { OID v_bag; GC_ANY(v64403= list::empty(Kernel.emptySet)); { { Cast * v88616 = ((Cast *) GC_OBJECT(Cast,new_object_class(Language._Cast))); { Cast * v64404 = v88616; OID v64405; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core._at); (v88616->args = list::alloc(2,_oid_(v82392),_oid_(v82379))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v64405 = _oid_(v88616); } (v64404->arg = v64405);} (v88616->set_arg = Kernel._slot); add_I_property(Kernel.instances,Language._Cast,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v64403)->addFast(v_bag);} (v64402->args = v64403);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v45936 = _oid_(v88616); } { { OID v30902; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.write); (v88616->args = list::alloc(3,_oid_(v82392), v13540, v45936)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v30902 = _oid_(v88616); } v82394 = v82394->addFast(v30902); } GC__ANY(v82394, 7);} } } } GC_UNLOOP;} } { OID v82389 = GC_OID(_oid_(_at_property1(Kernel.close,v82379))); { OID v31863; if (boolean_I_any(v82389) == CTRUE) { Call_method1 * v88616 = ((Call_method1 *) GC_OBJECT(Call_method1,new_object_class(Language._Call_method1))); update_property(Kernel.arg, v88616, 2, Kernel._object, v82389); (v88616->args = list::alloc(1,v13540)); add_I_property(Kernel.instances,Language._Call_method1,11,_oid_(v88616)); v31863 = _oid_(v88616); } else v31863 = v13540; v82394 = v82394->addFast(v31863); } } Result = _oid_(v82394); } GC_UNBIND; return (Result);} } OID c_code_Defobj_Optimize(Defobj *v13540,ClaireClass *v82395) { GC_BIND; { OID Result = 0; { ClaireBoolean * v61556 = Optimize.OPT->allocation; ClaireClass * v61558 = v13540->arg; OID v82391 = GC_OID(get_symbol(v13540->ident)); OID v61589; { if ((v82391 != CNULL) && (inherit_ask_class(OWNER(v82391),Core._global_variable) != CTRUE)) v61589 = v82391; else { Variable * v72682;{ Cint v55888; { (Optimize.OPT->max_vars = (Optimize.OPT->max_vars+1)); v55888 = 0; } v72682 = Variable_I_symbol(OBJECT(symbol,Optimize._starname_star->value),v55888,v61558); } v61589=_oid_(v72682);} GC_OID(v61589);} Call * v74021; { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Optimize.object_I); (v88616->args = list::alloc(2,_oid_(v13540->ident),_oid_(v61558))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v74021 = v88616; } GC_OBJECT(Call,v74021);} OID v74022 = GC_OID(analyze_I_class(v61558,v61589,GC_OBJECT(list,v13540->args),list::alloc(1,_oid_(Kernel.name)))); OID v61579; if (inherit_ask_class(OWNER(v61589),Language._Variable) != CTRUE) { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); store_object(v88616, 2, Kernel._object, (*Kernel.cons)(_oid_(v74021), v74022), CFALSE); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v61579 = _oid_(v88616); } else { Let * v88616 = ((Let *) GC_OBJECT(Let,new_object_class(Language._Let))); store_object(v88616, 2, Kernel._object, v61589, CFALSE); (v88616->value = _oid_(v74021)); { Let * v64433 = v88616; OID v64434; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); store_object(v88616, 2, Kernel._object, v74022, CFALSE); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v64434 = _oid_(v88616); } (v64433->arg = v64434);} add_I_property(Kernel.instances,Language._Let,11,_oid_(v88616)); v61579 = _oid_(v88616); } if (v61558->open <= 0) close_exception(((general_error *) (*Core._general_error)(_string_(CSTRING("[105] cannot instantiate ~S")), _oid_(list::alloc(1,_oid_(v61558)))))); if (v82391 != CNULL) { if (contain_ask_list(Optimize.OPT->objects,v82391) != CTRUE) { GC_OBJECT(list,Optimize.OPT->objects)->addFast(v82391); (*Optimize.c_register)(v82391); } } else { warn_void(); tformat_string(CSTRING("~S is unknown [265]\n"),2,list::alloc(1,_oid_(v13540->ident))); } v61579= GC_OID((*Optimize.c_code)(v61579, _oid_(v82395))); if (_inf_equal_type(v13540->arg,Kernel._exception) == CTRUE) (Optimize.OPT->allocation = v61556); Result = v61579; } GC_UNBIND; return (Result);} } OID c_code_Defclass_Optimize(Defclass *v13540,ClaireClass *v82395) { GC_BIND; { OID Result = 0; { symbol * v77208 = v13540->ident; OID v82391 = GC_OID(get_symbol(v77208)); Call * v50377; { ClaireObject *V_CC ; if (v82391 != CNULL) { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.class_I); (v88616->args = list::alloc(2,_oid_(v77208),_oid_(v13540->arg))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); V_CC = v88616; } else close_exception(((general_error *) (*Core._general_error)(_string_(CSTRING("[internal] cannot compile unknown class ~S")), _oid_(list::alloc(1,_oid_(v77208)))))); v50377= (Call *) V_CC;} Do * v61579; { { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); { Do * v64436 = v88616; list * v64437; { list * v61654; { { list * v82796; { { bag *v_list; OID v_val; OID v82400,CLcount; v_list = GC_OBJECT(list,v13540->args); v82796 = v_list->clone(); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v82400 = (*(v_list))[CLcount]; { OID v82398 = CNULL; if (INHERIT(OWNER(v82400),Language._Call)) { v82398= GC_OID((*(OBJECT(Call,v82400)->args))[2]); v82400= GC_OID((*(OBJECT(Call,v82400)->args))[1]); } { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.add_slot); (v88616->args = list::alloc(5,v82391, _oid_(make_a_property_any(_oid_(OBJECT(Variable,v82400)->pname))), GC_OID((*Kernel.range)(v82400)), v82398, 0)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_val = _oid_(v88616); } } (*((list *) v82796))[CLcount] = v_val;} } GC_OBJECT(list,v82796);} list * v83757; if (v13540->params->length != 0) { OID v_bag; GC_ANY(v83757= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); (v88616->args = list::alloc(3,_oid_(Kernel.params), v82391, GC_OID(_oid_(v13540->params)))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v83757)->addFast(v_bag);} else v83757 = list::empty(); v61654 = append_list(v82796,v83757); } GC_OBJECT(list,v61654);} v64437 = cons_any(_oid_(v50377),v61654); } (v64436->args = v64437);} add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v61579 = v88616; } GC_OBJECT(Do,v61579);} if (contain_ask_list(Optimize.OPT->objects,v82391) != CTRUE) { GC_OBJECT(list,Optimize.OPT->objects)->addFast(v82391); (*Optimize.c_register)(v82391); } Result = (*Optimize.c_code)(_oid_(v61579), _oid_(v82395)); } GC_UNBIND; return (Result);} } ClaireType * c_type_Defmethod_Optimize(Defmethod *v13540) { return (Kernel._any);} OID c_code_Defmethod_Optimize(Defmethod *v13540) { GC_BIND; { OID Result = 0; { property * v63904 = v13540->arg->selector; list * v82388 = GC_OBJECT(list,v13540->arg->args); list * v63778 = (((v82388->length == 1) && ((*(v82388))[1] == _oid_(ClEnv))) ? list::alloc(1,GC_OID(_oid_(Variable_I_symbol(OBJECT(symbol,Optimize._starname_star->value),0,Kernel._void)))) : v82388 ); list * v63775 = GC_OBJECT(list,extract_signature_I_list(v63778)); list * v64489 = GC_OBJECT(list,extract_range_any(GC_OID(v13540->set_arg),v63778,GC_OBJECT(list,OBJECT(list,Language.LDEF->value)))); OID v12362; { if ((boolean_I_any(v13540->inline_ask) == CTRUE) && (Optimize.compiler->inline_ask == CTRUE)) { print_in_string_void(); princ_string(CSTRING("lambda[(")); ppvariable_list(v63778); princ_string(CSTRING("),")); print_any(GC_OID(v13540->body)); princ_string(CSTRING("]")); v12362 = _string_(end_of_print_void()); } else v12362 = Kernel.cfalse; GC_OID(v12362);} list * v29046 = GC_OBJECT(list,extract_status_new_any(GC_OID(v13540->body))); OID v49519 = GC_OID((*Core._at)(_oid_(v63904), (*(v63775))[2])); method * v82389; { ClaireObject *V_CC ; if (Kernel._method == OBJECT(ClaireObject,v49519)->isa) V_CC = OBJECT(method,v49519); else close_exception(((general_error *) (*Core._general_error)(_string_(CSTRING("[internal] the method ~S @ ~S is not known")), _oid_(list::alloc(2,_oid_(v63904),(*(v63775))[2]))))); v82389= (method *) V_CC;} OID v31940 = v82389->status; ((*(v29046))[2]=get_property(Kernel.functional,v82389)); if ((Optimize.compiler->inline_ask != CTRUE) && ((v63904 == Language.Iterate) || (v63904 == Language.iterate))) Result = Core.nil->value; else if (((*(v64489))[1] == _oid_(Kernel._void)) && (sort_pattern_ask_list(v63778,GC_OID(v13540->body)) == CTRUE)) Result = sort_code_Defmethod(v13540,v63778); else { if ((*(v29046))[3] != _oid_(Kernel.body)) { char * v63819 = GC_STRING(string_v((*Optimize.function_name)(_oid_(v63904), (*(v63775))[2], (*(v29046))[2]))); lambda * v63757 = GC_OBJECT(lambda,lambda_I_list(v63778,(*(v29046))[3])); Cint v127083 = ((Optimize.OPT->recompute == CTRUE) ? c_status_any(GC_OID(v63757->body),GC_OBJECT(list,v63757->vars)) : status_I_restriction(v82389) ); compile_lambda_string(v63819,v63757,_oid_(v82389)); if (((*(v29046))[1] == CNULL) || (Optimize.OPT->recompute == CTRUE)) { if ((Optimize.OPT->use_nth_equal != CTRUE) && (BCONTAIN(v127083,2))) v127083= (v127083-exp2_integer(2)); if ((Optimize.OPT->use_update != CTRUE) && (BCONTAIN(v127083,3))) v127083= (v127083-exp2_integer(3)); if ((Optimize.OPT->use_string_update != CTRUE) && (BCONTAIN(v127083,7))) v127083= (v127083-exp2_integer(7)); if ((Optimize.OPT->allocation != CTRUE) && (BCONTAIN(v127083,1))) v127083= (v127083-exp2_integer(1)); ((*(v29046))[1]=v127083); } ((*(v29046))[2]=_oid_(make_function_string(v63819))); } if (INHERIT(OWNER(v13540->set_arg),Core._global_variable)) ((*(v64489))[1]=v13540->set_arg); else if ((INHERIT(v82389->range->isa,Kernel._class)) && (inherit_ask_class(OWNER((*(v64489))[1]),Kernel._class) != CTRUE)) ((*(v64489))[1]=_oid_(v82389->range)); { OID v61568 = GC_OID(add_method_I_method(v82389, OBJECT(list,(*(v63775))[1]), (*(v64489))[1], (*(v29046))[1], OBJECT(ClaireFunction,(*(v29046))[2]))); { OID v84718; if ((boolean_I_any(v13540->inline_ask) == CTRUE) && ((Optimize.compiler->inline_ask == CTRUE) && (Optimize.compiler->diet_ask != CTRUE))) { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.inlineok_ask); (v88616->args = list::alloc(2,v61568,v12362)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v84718 = _oid_(v88616); } else if ((boolean_I_any((*(v64489))[2]) == CTRUE) && (Optimize.compiler->diet_ask != CTRUE)) { char * v63819 = GC_STRING(append_string(GC_STRING(string_v((*Optimize.function_name)(_oid_(v63904), (*(v63775))[2], (*(v29046))[2]))),CSTRING("_type"))); compile_lambda_string(v63819,OBJECT(lambda,(*(v64489))[2]),_oid_(Kernel._type)); { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.write); (v88616->args = list::alloc(3,Language.typing->value, v61568, _oid_(make_function_string(v63819)))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v84718 = _oid_(v88616); } } else v84718 = v61568; Result = (*Optimize.c_code)(v84718); } } } } GC_UNBIND; return (Result);} } ClaireBoolean * sort_pattern_ask_list(list *v63778,OID v126127) { GC_BIND; { ClaireBoolean *Result ; { ClaireBoolean *v_and; { v_and = ((v63778->length == 1) ? CTRUE : CFALSE); if (v_and == CFALSE) Result =CFALSE; else { if (INHERIT(OWNER(v126127),Language._Call)) { ClaireBoolean *v_and1; { v_and1 = ((OBJECT(Call,v126127)->selector == Core.sort) ? CTRUE : CFALSE); if (v_and1 == CFALSE) v_and =CFALSE; else { { OID v63368 = GC_OID((*(OBJECT(Call,v126127)->args))[1]); v_and1 = ((INHERIT(OWNER(v63368),Language._Call)) ? ((OBJECT(Call,v63368)->selector == Core._at) ? ((INHERIT(OWNER((*(OBJECT(Call,v63368)->args))[1]),Kernel._property)) ? CTRUE: CFALSE): CFALSE) : CFALSE ); } if (v_and1 == CFALSE) v_and =CFALSE; else { v_and1 = ((equal(lexical_build_any(GC_OID((*(OBJECT(Call,v126127)->args))[2]),v63778,0),(*(v63778))[1]) == CTRUE) ? CTRUE : CFALSE); if (v_and1 == CFALSE) v_and =CFALSE; else v_and = CTRUE;} } } } else v_and = CFALSE; if (v_and == CFALSE) Result =CFALSE; else Result = CTRUE;} } } GC_UNBIND; return (Result);} } OID sort_code_Defmethod(Defmethod *v13540,list *v63778) { GC_BIND; { OID Result = 0; { OID v82388 = (*(v63778))[1]; OID v82382 = GC_OID((*(OBJECT(bag,(*Core.args)(GC_OID((*(OBJECT(bag,(*Core.args)(GC_OID(v13540->body)))))[1])))))[1]); Variable * v82389 = GC_OBJECT(Variable,Variable_I_symbol(symbol_I_string2(CSTRING("m")),0,Kernel._integer)); Variable * v82390 = GC_OBJECT(Variable,Variable_I_symbol(symbol_I_string2(CSTRING("n")),0,Kernel._integer)); Variable * v82400 = GC_OBJECT(Variable,Variable_I_symbol(symbol_I_string2(CSTRING("x")),0,GC_OBJECT(ClaireType,member_type(GC_OBJECT(ClaireType,OBJECT(ClaireType,(*Kernel.range)(v82388))))))); Variable * v82392 = GC_OBJECT(Variable,Variable_I_symbol(symbol_I_string2(CSTRING("p")),0,Kernel._integer)); Variable * v41817 = GC_OBJECT(Variable,Variable_I_symbol(symbol_I_string2(CSTRING("q")),0,Kernel._integer)); Defmethod * v90724; { { Defmethod * v88616 = ((Defmethod *) GC_OBJECT(Defmethod,new_object_class(Language._Defmethod))); (v88616->arg = v13540->arg); (v88616->inline_ask = Kernel.cfalse); (v88616->set_arg = v13540->set_arg); { Defmethod * v64463 = v88616; OID v64464; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = v13540->arg->selector); { Call * v64465 = v88616; list * v64466; { OID v_bag; GC_ANY(v64466= list::empty(Kernel.emptySet)); ((list *) v64466)->addFast(1); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.length); (v88616->args = list::alloc(1,(*(v63778))[1])); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v64466)->addFast(v_bag); ((list *) v64466)->addFast(v82388);} (v64465->args = v64466);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v64464 = _oid_(v88616); } (v64463->body = v64464);} add_I_property(Kernel.instances,Language._Defmethod,11,_oid_(v88616)); v90724 = v88616; } GC_OBJECT(Defmethod,v90724);} If * v73359; { { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v64467 = v88616; OID v64468; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel._sup); (v88616->args = list::alloc(2,_oid_(v82389),_oid_(v82390))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v64468 = _oid_(v88616); } (v64467->test = v64468);} { If * v64469 = v88616; OID v64491; { Let * v88616 = ((Let *) GC_OBJECT(Let,new_object_class(Language._Let))); (v88616->var = v82400); { Let * v64492 = v88616; OID v64493; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth); (v88616->args = list::alloc(2,v82388,_oid_(v82390))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v64493 = _oid_(v88616); } (v64492->value = v64493);} { Let * v64494 = v88616; OID v64495; { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v64496 = v88616; OID v64497; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel._equal); { Call * v64498 = v88616; list * v64499; { OID v_bag; GC_ANY(v64499= list::empty(Kernel.emptySet)); ((list *) v64499)->addFast(_oid_(v82389)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core._plus); (v88616->args = list::alloc(2,_oid_(v82390),1)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v64499)->addFast(v_bag);} (v64498->args = v64499);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v64497 = _oid_(v88616); } (v64496->test = v64497);} { If * v64500 = v88616; OID v64522; { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v64523 = v88616; OID v64524; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); update_property(Kernel.selector, v88616, 2, Kernel._object, v82382); { Call * v64525 = v88616; list * v64526; { OID v_bag; GC_ANY(v64526= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth); (v88616->args = list::alloc(2,v82388,_oid_(v82389))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v64526)->addFast(v_bag); ((list *) v64526)->addFast(_oid_(v82400));} (v64525->args = v64526);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v64524 = _oid_(v88616); } (v64523->test = v64524);} { If * v64527 = v88616; OID v64528; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); { Do * v64529 = v88616; list * v64530; { OID v_bag; GC_ANY(v64530= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth_equal); { Call * v64531 = v88616; list * v64553; { OID v_bag; GC_ANY(v64553= list::empty(Kernel.emptySet)); ((list *) v64553)->addFast(v82388); ((list *) v64553)->addFast(_oid_(v82390)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth); (v88616->args = list::alloc(2,v82388,_oid_(v82389))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v64553)->addFast(v_bag);} (v64531->args = v64553);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v64530)->addFast(v_bag); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth_equal); (v88616->args = list::alloc(3,v82388, _oid_(v82389), _oid_(v82400))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v64530)->addFast(v_bag);} (v64529->args = v64530);} add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v64528 = _oid_(v88616); } (v64527->arg = v64528);} add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); (v88616->other = Kernel.cfalse); v64522 = _oid_(v88616); } (v64500->arg = v64522);} { If * v64554 = v88616; OID v64555; { Let * v88616 = ((Let *) GC_OBJECT(Let,new_object_class(Language._Let))); (v88616->var = v82392); { Let * v64556 = v88616; OID v64557; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core._sup_sup); { Call * v64558 = v88616; list * v64559; { OID v_bag; GC_ANY(v64559= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core._plus); (v88616->args = list::alloc(2,_oid_(v82390),_oid_(v82389))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v64559)->addFast(v_bag); ((list *) v64559)->addFast(1);} (v64558->args = v64559);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v64557 = _oid_(v88616); } (v64556->value = v64557);} { Let * v64560 = v88616; OID v64561; { Let * v88616 = ((Let *) GC_OBJECT(Let,new_object_class(Language._Let))); (v88616->var = v41817); (v88616->value = _oid_(v82390)); { Let * v64562 = v88616; OID v65235; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); { Do * v65236 = v88616; list * v65237; { OID v_bag; GC_ANY(v65237= list::empty(Kernel.emptySet)); { { Assign * v88616 = ((Assign *) GC_OBJECT(Assign,new_object_class(Language._Assign))); (v88616->var = _oid_(v82400)); { Assign * v65238 = v88616; OID v65239; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth); (v88616->args = list::alloc(2,v82388,_oid_(v82392))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65239 = _oid_(v88616); } (v65238->arg = v65239);} add_I_property(Kernel.instances,Language._Assign,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65237)->addFast(v_bag); { { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v65240 = v88616; OID v65241; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core._I_equal); (v88616->args = list::alloc(2,_oid_(v82392),_oid_(v82390))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65241 = _oid_(v88616); } (v65240->test = v65241);} { If * v65242 = v88616; OID v65243; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth_equal); { Call * v65244 = v88616; list * v65266; { OID v_bag; GC_ANY(v65266= list::empty(Kernel.emptySet)); ((list *) v65266)->addFast(v82388); ((list *) v65266)->addFast(_oid_(v82392)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth); (v88616->args = list::alloc(2,v82388,_oid_(v82390))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65266)->addFast(v_bag);} (v65244->args = v65266);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65243 = _oid_(v88616); } (v65242->arg = v65243);} add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); (v88616->other = Kernel.cfalse); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65237)->addFast(v_bag); { { For * v88616 = ((For *) GC_OBJECT(For,new_object_class(Language._For))); (v88616->var = v82392); { Iteration * v65267 = v88616; OID v65268; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel._dot_dot); { Call * v65269 = v88616; list * v65270; { OID v_bag; GC_ANY(v65270= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core._plus); (v88616->args = list::alloc(2,_oid_(v82390),1)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65270)->addFast(v_bag); ((list *) v65270)->addFast(_oid_(v82389));} (v65269->args = v65270);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65268 = _oid_(v88616); } (v65267->set_arg = v65268);} { Iteration * v65271 = v88616; OID v65272; { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v65273 = v88616; OID v65274; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); update_property(Kernel.selector, v88616, 2, Kernel._object, v82382); { Call * v65275 = v88616; list * v65297; { OID v_bag; GC_ANY(v65297= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth); (v88616->args = list::alloc(2,v82388,_oid_(v82392))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65297)->addFast(v_bag); ((list *) v65297)->addFast(_oid_(v82400));} (v65275->args = v65297);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65274 = _oid_(v88616); } (v65273->test = v65274);} { If * v65298 = v88616; OID v65299; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); { Do * v65300 = v88616; list * v65301; { OID v_bag; GC_ANY(v65301= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth_equal); { Call * v65302 = v88616; list * v65303; { OID v_bag; GC_ANY(v65303= list::empty(Kernel.emptySet)); ((list *) v65303)->addFast(v82388); ((list *) v65303)->addFast(_oid_(v82390)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth); (v88616->args = list::alloc(2,v82388,_oid_(v82392))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65303)->addFast(v_bag);} (v65302->args = v65303);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65301)->addFast(v_bag); { { Assign * v88616 = ((Assign *) GC_OBJECT(Assign,new_object_class(Language._Assign))); (v88616->var = _oid_(v82390)); { Assign * v65304 = v88616; OID v65305; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core._plus); (v88616->args = list::alloc(2,_oid_(v82390),1)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65305 = _oid_(v88616); } (v65304->arg = v65305);} add_I_property(Kernel.instances,Language._Assign,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65301)->addFast(v_bag); { { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v65306 = v88616; OID v65328; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel._sup); (v88616->args = list::alloc(2,_oid_(v82392),_oid_(v82390))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65328 = _oid_(v88616); } (v65306->test = v65328);} { If * v65329 = v88616; OID v65330; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth_equal); { Call * v65331 = v88616; list * v65332; { OID v_bag; GC_ANY(v65332= list::empty(Kernel.emptySet)); ((list *) v65332)->addFast(v82388); ((list *) v65332)->addFast(_oid_(v82392)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth); (v88616->args = list::alloc(2,v82388,_oid_(v82390))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65332)->addFast(v_bag);} (v65331->args = v65332);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65330 = _oid_(v88616); } (v65329->arg = v65330);} add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); (v88616->other = Kernel.cfalse); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65301)->addFast(v_bag);} (v65300->args = v65301);} add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v65299 = _oid_(v88616); } (v65298->arg = v65299);} add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); (v88616->other = Kernel.cfalse); v65272 = _oid_(v88616); } (v65271->arg = v65272);} add_I_property(Kernel.instances,Language._For,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65237)->addFast(v_bag); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth_equal); (v88616->args = list::alloc(3,v82388, _oid_(v82390), _oid_(v82400))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65237)->addFast(v_bag); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = v13540->arg->selector); { Call * v65333 = v88616; list * v65334; { OID v_bag; GC_ANY(v65334= list::empty(Kernel.emptySet)); ((list *) v65334)->addFast(_oid_(v41817)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel._dash); (v88616->args = list::alloc(2,_oid_(v82390),1)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65334)->addFast(v_bag); ((list *) v65334)->addFast(v82388);} (v65333->args = v65334);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65237)->addFast(v_bag); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = v13540->arg->selector); { Call * v65335 = v88616; list * v65336; { OID v_bag; GC_ANY(v65336= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core._plus); (v88616->args = list::alloc(2,_oid_(v82390),1)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65336)->addFast(v_bag); ((list *) v65336)->addFast(_oid_(v82389)); ((list *) v65336)->addFast(v82388);} (v65335->args = v65336);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65237)->addFast(v_bag);} (v65236->args = v65237);} add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v65235 = _oid_(v88616); } (v64562->arg = v65235);} add_I_property(Kernel.instances,Language._Let,11,_oid_(v88616)); v64561 = _oid_(v88616); } (v64560->arg = v64561);} add_I_property(Kernel.instances,Language._Let,11,_oid_(v88616)); v64555 = _oid_(v88616); } (v64554->other = v64555);} add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); v64495 = _oid_(v88616); } (v64494->arg = v64495);} add_I_property(Kernel.instances,Language._Let,11,_oid_(v88616)); v64491 = _oid_(v88616); } (v64469->arg = v64491);} add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); (v88616->other = Kernel.cfalse); v73359 = v88616; } GC_OBJECT(If,v73359);} Defmethod * v90725; { { Defmethod * v88616 = ((Defmethod *) GC_OBJECT(Defmethod,new_object_class(Language._Defmethod))); { Defmethod * v65337 = v88616; Call * v65359; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = v13540->arg->selector); (v88616->args = list::alloc(3,_oid_(v82390), _oid_(v82389), v82388)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65359 = v88616; } (v65337->arg = v65359);} (v88616->inline_ask = Kernel.cfalse); (v88616->set_arg = v13540->set_arg); (v88616->body = _oid_(v73359)); add_I_property(Kernel.instances,Language._Defmethod,11,_oid_(v88616)); v90725 = v88616; } GC_OBJECT(Defmethod,v90725);} tformat_string(CSTRING("---- note: quick sort optimisation for ~S ---- \n"),2,list::alloc(1,_oid_(v13540->arg->selector))); OPT_EVAL(_oid_(v90725)); { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); (v88616->args = list::alloc(2,GC_OID((*Optimize.c_code)(_oid_(v90724))),GC_OID((*Optimize.c_code)(_oid_(v90725))))); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); Result = _oid_(v88616); } } GC_UNBIND; return (Result);} } method * add_method_property2(property *v82392,list *v63775,ClaireType *v63949,Cint v63993,ClaireFunction *v63523,ClaireFunction *v63524) { return (add_method_property(v82392, v63775, v63949, v63993, _oid_(v63523)));} OID add_method_I_method(method *v82389,list *v63775,OID v63949,OID v105068,ClaireFunction *v63591) { GC_BIND; { OID Result = 0; { Call_method * v61558; { { Call_method * v88616 = ((Call_method *) GC_OBJECT(Call_method,new_object_class(Language._Call_method))); (v88616->arg = ((method *) _at_property1(Kernel.add_method,Kernel._property))); (v88616->args = list::alloc(5,GC_OID((*Optimize.c_code)(_oid_(v82389->selector), _oid_(Kernel._property))), GC_OID((*Optimize.c_code)(_oid_(v63775), _oid_(Kernel._list))), GC_OID((*Optimize.c_code)(v63949, _oid_(Kernel._type))), v105068, _oid_(v63591))); add_I_property(Kernel.instances,Language._Call_method,11,_oid_(v88616)); v61558 = v88616; } GC_OBJECT(Call_method,v61558);} if ((v82389->range == Kernel._float) || ((v82389->domain->memq(_oid_(Kernel._float)) == CTRUE) || (INHERIT(v82389->range->isa,Kernel._tuple)))) GC_OBJECT(list,v61558->args)->addFast(_oid_(make_function_string(append_string(GC_STRING(string_I_function(v63591)),CSTRING("_"))))); Result = _oid_(v61558); } GC_UNBIND; return (Result);} } list * extract_status_new_any(OID v82400) { GC_BIND; { list *Result ; { OID v82395 = CNULL; OID v82382; if ((INHERIT(OWNER(v82400),Language._Call)) && (OBJECT(Call,v82400)->selector == Language.function_I)) v82382 = v82400; else v82382 = CNULL; if (INHERIT(OWNER(v82400),Language._And)) { OID v82401 = (*(OBJECT(And,v82400)->args))[1]; if ((INHERIT(OWNER(v82401),Language._Call)) && (OBJECT(Call,v82401)->selector == Language.function_I)) { v82382= v82401; v82400= (*(OBJECT(And,v82400)->args))[2]; } } else if (INHERIT(OWNER(v82400),Language._Call)) { if (OBJECT(Call,v82400)->selector == Language.function_I) v82400= _oid_(Kernel.body); } if (v82382 != CNULL) { v82400= _oid_(Kernel.body); if (length_bag(OBJECT(bag,(*Core.args)(v82382))) > 1) { ClaireHandler c_handle = ClaireHandler(); if ERROR_IN { { Cint v73612;{ set * v32114; { set * v112294 = set::empty(Kernel.emptySet); { OID gc_local; ITERATE(v82397); bag *v82397_support; v82397_support = GC_OBJECT(list,cdr_list(GC_OBJECT(list,OBJECT(list,(*Core.args)(v82382))))); for (START(v82397_support); NEXT(v82397);) { GC_LOOP; v112294->addFast(GC_OID(OPT_EVAL(v82397))); GC_UNLOOP;} } v32114 = GC_OBJECT(set,v112294); } v73612 = integer_I_set(v32114); } v82395=v73612;} ClEnv->cHandle--;} else if (belong_to(_oid_(ClEnv->exception_I),_oid_(Kernel._any)) == CTRUE) { c_handle.catchIt();{ warn_void(); (Optimize.SHIT->value= _oid_(cdr_list(GC_OBJECT(list,OBJECT(list,(*Core.args)(v82382)))))); tformat_string(CSTRING("wrong status ~S -> ~S [266]\n"),2,GC_OBJECT(list,list::alloc(2,v82382,_oid_(set_I_bag(cdr_list(GC_OBJECT(list,OBJECT(list,(*Core.args)(v82382))))))))); v82395= 0; } } else PREVIOUS_HANDLER;} else v82395= 0; v82382= _oid_(make_function_string(string_I_symbol(extract_symbol_any((*(OBJECT(bag,(*Core.args)(v82382))))[1])))); } Result = list::alloc(3,v82395, v82382, v82400); } GC_UNBIND; return (Result);} } list * extract_signature_I_list(list *v82388) { GC_BIND; (Language.LDEF->value= _oid_(list::empty(Kernel._any))); { list *Result ; { Cint v82390 = 0; list * v63709 = list::empty(Kernel._type); list * v63710; { { bag *v_list; OID v_val; OID v82398,CLcount; v_list = v82388; v63710 = v_list->clone(Kernel._any); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v82398 = (*(v_list))[CLcount]; { OID v82392 = GC_OID(extract_pattern_any(GC_OID(_oid_(OBJECT(Variable,v82398)->range)),list::alloc(1,v82390))); ++v82390; { { OID v33075; { if (INHERIT(OBJECT(Variable,v82398)->range->isa,Core._global_variable)) v33075 = _oid_(OBJECT(Variable,v82398)->range); else v33075 = v82392; GC_OID(v33075);} v63709 = v63709->addFast(v33075); } GC_OBJECT(list,v63709);} (OBJECT(Variable,v82398)->range = type_I_any(v82392)); v_val = v82392; } (*((list *) v63710))[CLcount] = v_val;} } GC_OBJECT(list,v63710);} Result = list::alloc(2,_oid_(v63709),_oid_(v63710)); } GC_UNBIND; return (Result);} } ClaireBoolean * _equalsig_ask_list(list *v82400,list *v82401) { return (((tmatch_ask_list(v82400,v82401) == CTRUE) ? ((tmatch_ask_list(v82401,v82400) == CTRUE) ? CTRUE: CFALSE): CFALSE));} char * function_name_property_Optimize(property *v82392,list *v82388,OID v82400) { GC_BIND; { char *Result ; if (INHERIT(OWNER(v82400),Kernel._function)) Result = string_I_function(OBJECT(ClaireFunction,v82400)); else { Cint v82390 = 0; Cint v82389 = 0; module * v63791 = v82392->name->module_I; ClaireClass * v82379 = class_I_type(OBJECT(ClaireType,(*(v82388))[1])); char * v82394 = GC_STRING(append_string(GC_STRING(append_string(GC_STRING(string_I_symbol(v82392->name)),CSTRING("_"))),GC_STRING(string_I_symbol(v82379->name)))); if ((Optimize.compiler->naming == 0) && (v82392 != Core.main)) v82394= GC_STRING(append_string(GC_STRING(append_string(GC_STRING(string_I_symbol(v63791->name)),CSTRING("_"))),v82394)); { ITERATE(v82394); for (START(v82392->restrictions); NEXT(v82394);) { if (v82379 == domain_I_restriction(OBJECT(restriction,v82394))) ++v82390; if (_equalsig_ask_list(v82388,OBJECT(restriction,v82394)->domain) == CTRUE) v82389= v82390; } } v82394= GC_STRING(((v82390 <= 1) ? v82394 : append_string(v82394,GC_STRING(string_I_integer (v82389))) )); Result = (((stable_ask_relation(v82392) == CTRUE) || (v82392 == Core.main)) ? v82394 : append_string(GC_STRING(append_string(v82394,CSTRING("_"))),GC_STRING(string_I_symbol(ClEnv->module_I->name))) ); } GC_UNBIND; return (Result);} } OID compile_lambda_string(char *v13540,lambda *v82388,OID v82389) { { OID Result = 0; { Cint v82400 = Optimize.compiler->safety; lambda * v82401 = v82388; if (Kernel._method == OWNER(v82389)) (Optimize.OPT->in_method = v82389); (Optimize.OPT->protection = CFALSE); (Optimize.OPT->allocation = CFALSE); if (Optimize.OPT->loop_index > 0) (Optimize.OPT->loop_index = 0); (Optimize.OPT->loop_gc = CFALSE); (Optimize.OPT->use_update = CFALSE); (Optimize.OPT->use_nth_equal = CFALSE); (Optimize.OPT->use_string_update = CFALSE); (Optimize.OPT->max_vars = 0); if (contain_ask_list(Optimize.OPT->unsure,v82389) == CTRUE) (Optimize.compiler->safety = 1); (*Optimize.make_c_function)(_oid_(v82388), _string_(v13540), v82389); (Optimize.OPT->in_method = CNULL); (Optimize.compiler->safety = v82400); Result = Kernel.ctrue; } return (Result);} } OID c_code_Defarray_Optimize(Defarray *v13540) { GC_BIND; { OID Result = 0; { list * v82377 = GC_OBJECT(list,v13540->arg->args); OID v61556 = GC_OID(get_symbol(extract_symbol_any((*(v82377))[1]))); table * v61589; { ClaireObject *V_CC ; if (INHERIT(OWNER(v61556),Kernel._table)) V_CC = OBJECT(table,v61556); else close_exception(((general_error *) (*Core._general_error)(_string_(CSTRING("[internal] the table ~S is unknown")), _oid_(list::alloc(1,(*(v82377))[1]))))); v61589= (table *) V_CC;} OID v82395 = GC_OID((*Kernel.domain)(v61556)); OID v82381; { { list * v82388 = GC_OBJECT(list,cdr_list(v82377)); OID v82378 = GC_OID(lexical_build_any(GC_OID(v13540->body),v82388,0)); { ClaireBoolean * g0446I; { OID v35958; { ITERATE(v64067); v35958= Kernel.cfalse; for (START(v82388); NEXT(v64067);) if (occurrence_any(v82378,OBJECT(Variable,v64067)) > 0) { v35958 = Kernel.ctrue; break;} } g0446I = boolean_I_any(v35958); } if (g0446I == CTRUE) v82381 = _oid_(lambda_I_list(v82388,v82378)); else v82381 = v13540->body; } } GC_OID(v82381);} OID v82380; { if (INHERIT(OWNER(v82381),Core._lambda)) v82380 = CNULL; else v82380 = v13540->body; GC_OID(v82380);} list * v73618; if (boolean_I_any(_oid_(OBJECT(ClaireRelation,v61556)->multivalued_ask)) == CTRUE) { OID v_bag; GC_ANY(v73618= list::empty(Kernel._any)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); (v88616->args = list::alloc(3,_oid_(Kernel.multivalued_ask), _oid_(v61589), GC_OID(_oid_(OBJECT(ClaireRelation,v61556)->multivalued_ask)))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v73618)->addFast(v_bag);} else v73618 = list::empty(Kernel._any); list * v73619; { OID v_bag; GC_ANY(v73619= list::empty(Kernel._any)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); (v88616->args = list::alloc(3,_oid_(Kernel.range), _oid_(v61589), GC_OID((*Kernel.range)(v61556)))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v73619)->addFast(v_bag); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); (v88616->args = list::alloc(3,_oid_(Kernel.params), _oid_(v61589), GC_OID((*Kernel.params)(v61556)))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v73619)->addFast(v_bag); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); (v88616->args = list::alloc(3,_oid_(Kernel.domain), _oid_(v61589), v82395)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v73619)->addFast(v_bag);} (OBJECT(Variable,(*(v82377))[2])->range = extract_type_any(GC_OID(_oid_(OBJECT(Variable,(*(v82377))[2])->range)))); if (v82377->length == 2) { { { OID v36919; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); { Call * v65368 = v88616; list * v65390; { OID v_bag; GC_ANY(v65390= list::empty(Kernel.emptySet)); ((list *) v65390)->addFast(_oid_(Kernel.graph)); ((list *) v65390)->addFast(_oid_(v61589)); if (INHERIT(OBJECT(ClaireObject,v82395)->isa,Core._Interval)) { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.make_copy_list); (v88616->args = list::alloc(2,size_Interval(OBJECT(Interval,v82395)),v82380)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } else { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.make_list); (v88616->args = list::alloc(2,29,CNULL)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } ((list *) v65390)->addFast(v_bag);} (v65368->args = v65390);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v36919 = _oid_(v88616); } v73619 = v73619->addFast(v36919); } GC_OBJECT(list,v73619);} { { OID v59983; if (INHERIT(OWNER(v82381),Core._lambda)) { For * v88616 = ((For *) GC_OBJECT(For,new_object_class(Language._For))); store_object(v88616, 2, Kernel._object, (*(v82377))[2], CFALSE); (v88616->set_arg = v82395); { Iteration * v65392 = v88616; OID v65393; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth_equal); (v88616->args = list::alloc(3,_oid_(v61589), (*(v82377))[2], GC_OID(OBJECT(lambda,v82381)->body))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65393 = _oid_(v88616); } (v65392->arg = v65393);} add_I_property(Kernel.instances,Language._For,11,_oid_(v88616)); v59983 = _oid_(v88616); } else { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); (v88616->args = list::alloc(3,_oid_(Kernel.DEFAULT), _oid_(v61589), v82380)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v59983 = _oid_(v88616); } v73619 = v73619->addFast(v59983); } GC_OBJECT(list,v73619);} } else { ClaireType * v63927 = GC_OBJECT(ClaireType,extract_type_any(GC_OID(_oid_(OBJECT(Variable,(*(v82377))[3])->range)))); (OBJECT(Variable,(*(v82377))[3])->range = v63927); { { OID v62866; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); { Call * v65395 = v88616; list * v65396; { OID v_bag; GC_ANY(v65396= list::empty(Kernel.emptySet)); ((list *) v65396)->addFast(_oid_(Kernel.graph)); ((list *) v65396)->addFast(_oid_(v61589)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.make_copy_list); { Call * v65397 = v88616; list * v65398; { OID v_bag; GC_ANY(v65398= list::empty(Kernel.emptySet)); ((list *) v65398)->addFast(OBJECT(table,v61556)->graph->length); { if ((*Kernel.params)(v61556) == _oid_(Kernel._any)) v_bag = CNULL; else v_bag = (*Kernel.DEFAULT)(v61556); GC_OID(v_bag);} ((list *) v65398)->addFast(v_bag);} (v65397->args = v65398);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65396)->addFast(v_bag);} (v65395->args = v65396);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v62866 = _oid_(v88616); } v73619 = v73619->addFast(v62866); } GC_OBJECT(list,v73619);} { { OID v67671; if (INHERIT(OWNER(v82381),Core._lambda)) { For * v88616 = ((For *) GC_OBJECT(For,new_object_class(Language._For))); store_object(v88616, 2, Kernel._object, (*(v82377))[2], CFALSE); (v88616->set_arg = (*(OBJECT(bag,v82395)))[1]); { Iteration * v65421 = v88616; OID v65422; { For * v88616 = ((For *) GC_OBJECT(For,new_object_class(Language._For))); store_object(v88616, 2, Kernel._object, (*(v82377))[3], CFALSE); (v88616->set_arg = _oid_(v63927)); { Iteration * v65423 = v88616; OID v65424; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth_equal); (v88616->args = list::alloc(4,_oid_(v61589), (*(v82377))[2], (*(v82377))[3], GC_OID(OBJECT(lambda,v82381)->body))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65424 = _oid_(v88616); } (v65423->arg = v65424);} add_I_property(Kernel.instances,Language._For,11,_oid_(v88616)); v65422 = _oid_(v88616); } (v65421->arg = v65422);} add_I_property(Kernel.instances,Language._For,11,_oid_(v88616)); v67671 = _oid_(v88616); } else { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); (v88616->args = list::alloc(3,_oid_(Kernel.DEFAULT), _oid_(v61589), v82380)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v67671 = _oid_(v88616); } v73619 = v73619->addFast(v67671); } GC_OBJECT(list,v73619);} } GC_OBJECT(list,Optimize.OPT->objects)->addFast(v61556); (*Optimize.c_register)(v61556); { OID v92657; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); { Do * v65426 = v88616; list * v65427; { OID v95540; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Optimize.object_I); (v88616->args = list::alloc(2,GC_OID((*Kernel.name)(v61556)),_oid_(Kernel._table))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v95540 = _oid_(v88616); } v65427 = cons_any(v95540,GC_OBJECT(list,add_star_list(v73618,v73619))); } (v65426->args = v65427);} add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v92657 = _oid_(v88616); } Result = (*Optimize.c_code)(v92657, _oid_(Kernel._any)); } } GC_UNBIND; return (Result);} } void compute_if_write_inverse_relation2(ClaireRelation *v82362) { GC_BIND; { Variable * v82400; { { Variable * v88616 = ((Variable *) GC_OBJECT(Variable,new_object_class(Language._Variable))); (v88616->pname = symbol_I_string2(CSTRING("XX"))); (v88616->range = v82362->domain); add_I_property(Kernel.instances,Language._Variable,11,_oid_(v88616)); v82400 = v88616; } GC_OBJECT(Variable,v82400);} Variable * v82401; { { Variable * v88616 = ((Variable *) GC_OBJECT(Variable,new_object_class(Language._Variable))); (v88616->pname = symbol_I_string2(CSTRING("YY"))); (v88616->range = ((multi_ask_any(_oid_(v82362)) == CTRUE) ? member_type(v82362->range) : v82362->range )); add_I_property(Kernel.instances,Language._Variable,11,_oid_(v88616)); v82401 = v88616; } GC_OBJECT(Variable,v82401);} Variable * v82402; { { Variable * v88616 = ((Variable *) GC_OBJECT(Variable,new_object_class(Language._Variable))); (v88616->pname = symbol_I_string2(CSTRING("ZZ"))); (v88616->range = v82362->range); add_I_property(Kernel.instances,Language._Variable,11,_oid_(v88616)); v82402 = v88616; } GC_OBJECT(Variable,v82402);} list * v63709 = list::empty(Kernel._any); if (multi_ask_any(_oid_(v82362)) == CTRUE) { v63709= list::alloc(Kernel._any,1,GC_OID((INHERIT(v82362->isa,Kernel._property) ? Produce_put_property2((property *) OBJECT(property,_oid_(v82362)),OBJECT(Variable,_oid_(v82400)),_oid_(v82401)) : Produce_put_table2((table *) OBJECT(table,_oid_(v82362)),OBJECT(Variable,_oid_(v82400)),_oid_(v82401))))); if (((v82362->inverse == (NULL)) ? CTRUE : CFALSE) != CTRUE) v63709= GC_OBJECT(list,v63709->addFast(GC_OID((INHERIT(v82362->inverse->isa,Kernel._property) ? Produce_put_property2((property *) OBJECT(property,_oid_(v82362->inverse)),OBJECT(Variable,_oid_(v82401)),_oid_(v82400)) : Produce_put_table2((table *) OBJECT(table,_oid_(v82362->inverse)),OBJECT(Variable,_oid_(v82401)),_oid_(v82400)))))); { ClaireRelation * v65429 = v82362; OID v65430; { lambda * v73703;{ OID v119565; { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v65454 = v88616; OID v65455; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.NOT); { Call * v65456 = v88616; list * v65457; { OID v_bag; GC_ANY(v65457= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel._Z); (v88616->args = list::alloc(2,_oid_(v82401),GC_OID(Produce_get_relation2(v82362,v82400)))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65457)->addFast(v_bag);} (v65456->args = v65457);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65455 = _oid_(v88616); } (v65454->test = v65455);} { If * v65458 = v88616; OID v65459; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); (v88616->args = v63709); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v65459 = _oid_(v88616); } (v65458->arg = v65459);} add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); (v88616->other = Kernel.cfalse); v119565 = _oid_(v88616); } v73703 = lambda_I_list(list::alloc(2,_oid_(v82400),_oid_(v82401)),v119565); } v65430=_oid_(v73703);} (v65429->if_write = v65430);} } else { v63709= list::alloc(Kernel._any,1,GC_OID((INHERIT(v82362->isa,Kernel._property) ? Produce_put_property2((property *) OBJECT(property,_oid_(v82362)),OBJECT(Variable,_oid_(v82400)),_oid_(v82401)) : Produce_put_table2((table *) OBJECT(table,_oid_(v82362)),OBJECT(Variable,_oid_(v82400)),_oid_(v82401))))); if (((v82362->inverse == (NULL)) ? CTRUE : CFALSE) != CTRUE) { { { OID v126292; { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v65461 = v88616; OID v65483; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.known_ask); (v88616->args = list::alloc(1,_oid_(v82402))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65483 = _oid_(v88616); } (v65461->test = v65483);} (v88616->arg = (INHERIT(v82362->inverse->isa,Kernel._property) ? Produce_remove_property2((property *) OBJECT(property,_oid_(v82362->inverse)),OBJECT(Variable,_oid_(v82402)),_oid_(v82400)) : Produce_remove_table2((table *) OBJECT(table,_oid_(v82362->inverse)),OBJECT(Variable,_oid_(v82402)),_oid_(v82400)))); add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); (v88616->other = Kernel.cfalse); v126292 = _oid_(v88616); } v63709 = v63709->addFast(v126292); } GC_OBJECT(list,v63709);} v63709= GC_OBJECT(list,v63709->addFast(GC_OID((INHERIT(v82362->inverse->isa,Kernel._property) ? Produce_put_property2((property *) OBJECT(property,_oid_(v82362->inverse)),OBJECT(Variable,_oid_(v82401)),_oid_(v82400)) : Produce_put_table2((table *) OBJECT(table,_oid_(v82362->inverse)),OBJECT(Variable,_oid_(v82401)),_oid_(v82400)))))); } { ClaireRelation * v65484 = v82362; OID v65485; { lambda * v73737;{ OID v21167; { Let * v88616 = ((Let *) GC_OBJECT(Let,new_object_class(Language._Let))); (v88616->var = v82402); (v88616->value = Produce_get_relation2(v82362,v82400)); { Let * v65488 = v88616; OID v65489; { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v65490 = v88616; OID v65491; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core._I_equal); (v88616->args = list::alloc(2,_oid_(v82401),_oid_(v82402))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v65491 = _oid_(v88616); } (v65490->test = v65491);} { If * v65492 = v88616; OID v65514; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); (v88616->args = v63709); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v65514 = _oid_(v88616); } (v65492->arg = v65514);} add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); (v88616->other = Kernel.cfalse); v65489 = _oid_(v88616); } (v65488->arg = v65489);} add_I_property(Kernel.instances,Language._Let,11,_oid_(v88616)); v21167 = _oid_(v88616); } v73737 = lambda_I_list(list::alloc(2,_oid_(v82400),_oid_(v82401)),v21167); } v65485=_oid_(v73737);} (v65484->if_write = v65485);} } { char * v116386 = GC_STRING(append_string(GC_STRING(string_I_symbol(v82362->name)),CSTRING("_write"))); compile_lambda_string(v116386,GC_OBJECT(lambda,OBJECT(lambda,v82362->if_write)),_oid_(Kernel._void)); } } GC_UNBIND;} OID compute_set_write_relation2(ClaireRelation *v82362) { GC_BIND; { OID Result = 0; { Variable * v82400; { { Variable * v88616 = ((Variable *) GC_OBJECT(Variable,new_object_class(Language._Variable))); (v88616->pname = symbol_I_string2(CSTRING("XX"))); (v88616->range = v82362->domain); add_I_property(Kernel.instances,Language._Variable,11,_oid_(v88616)); v82400 = v88616; } GC_OBJECT(Variable,v82400);} Variable * v82401; { { Variable * v88616 = ((Variable *) GC_OBJECT(Variable,new_object_class(Language._Variable))); (v88616->pname = symbol_I_string2(CSTRING("YY"))); (v88616->range = Kernel._bag); add_I_property(Kernel.instances,Language._Variable,11,_oid_(v88616)); v82401 = v88616; } GC_OBJECT(Variable,v82401);} Variable * v82402; { { Variable * v88616 = ((Variable *) GC_OBJECT(Variable,new_object_class(Language._Variable))); (v88616->pname = symbol_I_string2(CSTRING("ZZ"))); (v88616->range = member_type(v82362->range)); add_I_property(Kernel.instances,Language._Variable,11,_oid_(v88616)); v82402 = v88616; } GC_OBJECT(Variable,v82402);} list * v63709 = list::empty(Kernel._any); tformat_string(CSTRING("compute set_write for ~S \n"),0,list::alloc(1,_oid_(v82362))); if (((v82362->inverse == (NULL)) ? CTRUE : CFALSE) != CTRUE) { { OID v48075; { For * v88616 = ((For *) GC_OBJECT(For,new_object_class(Language._For))); (v88616->var = v82402); (v88616->set_arg = Produce_get_relation2(v82362,v82400)); (v88616->arg = (INHERIT(v82362->inverse->isa,Kernel._property) ? Produce_remove_property2((property *) OBJECT(property,_oid_(v82362->inverse)),OBJECT(Variable,_oid_(v82402)),_oid_(v82400)) : Produce_remove_table2((table *) OBJECT(table,_oid_(v82362->inverse)),OBJECT(Variable,_oid_(v82402)),_oid_(v82400)))); add_I_property(Kernel.instances,Language._For,11,_oid_(v88616)); v48075 = _oid_(v88616); } v63709 = v63709->addFast(v48075); } GC_OBJECT(list,v63709);} v63709= GC_OBJECT(list,v63709->addFast(GC_OID(Produce_erase_property2(((property *) v82362),v82400)))); { { OID v49036; { For * v88616 = ((For *) GC_OBJECT(For,new_object_class(Language._For))); (v88616->var = v82402); (v88616->set_arg = _oid_(v82401)); (v88616->arg = (INHERIT(v82362->isa,Kernel._property) ? Produce_put_property2((property *) OBJECT(property,_oid_(v82362)),OBJECT(Variable,_oid_(v82400)),_oid_(v82402)) : Produce_put_table2((table *) OBJECT(table,_oid_(v82362)),OBJECT(Variable,_oid_(v82400)),_oid_(v82402)))); add_I_property(Kernel.instances,Language._For,11,_oid_(v88616)); v49036 = _oid_(v88616); } v63709 = v63709->addFast(v49036); } GC_OBJECT(list,v63709);} { char * v116386 = GC_STRING(append_string(GC_STRING(string_I_symbol(v82362->name)),CSTRING("_set_write"))); { lambda * v49997; { { OID v50958; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); (v88616->args = v63709); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v50958 = _oid_(v88616); } v49997 = lambda_I_list(list::alloc(2,_oid_(v82400),_oid_(v82401)),v50958); } GC_OBJECT(lambda,v49997);} Result = compile_lambda_string(v116386,v49997,_oid_(Kernel._void)); } } } GC_UNBIND; return (Result);} } OID Produce_put_property2(property *v82394,Variable *v82400,OID v82401) { GC_BIND; { OID Result = 0; { list * v82388 = list::empty(Kernel._any); { OID gc_local; ITERATE(v64147); for (START(v82394->restrictions); NEXT(v64147);) { GC_LOOP; if ((Kernel._slot == OBJECT(ClaireObject,v64147)->isa) && (boolean_I_any(_oid_(_exp_type(GC_OBJECT(ClaireType,ptype_type(v82400->range)),domain_I_restriction(OBJECT(restriction,v64147))))) == CTRUE)) { list * v51919; { { OID v_bag; GC_ANY(v51919= list::empty(Kernel.emptySet)); ((list *) v51919)->addFast(_oid_(domain_I_restriction(OBJECT(restriction,v64147)))); if (boolean_I_any(_oid_(v82394->multivalued_ask)) == CTRUE) { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.add_I); { Call * v65520 = v88616; list * v65521; { OID v_bag; GC_ANY(v65521= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = v82394); { Call * v65522 = v88616; list * v65523; { OID v_bag; GC_ANY(v65523= list::empty(Kernel.emptySet)); { { Cast * v88616 = ((Cast *) GC_OBJECT(Cast,new_object_class(Language._Cast))); (v88616->arg = _oid_(v82400)); (v88616->set_arg = domain_I_restriction(OBJECT(restriction,v64147))); add_I_property(Kernel.instances,Language._Cast,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65523)->addFast(v_bag);} (v65522->args = v65523);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v65521)->addFast(v_bag); ((list *) v65521)->addFast(v82401);} (v65520->args = v65521);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } else { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); { Call * v66196 = v88616; list * v66197; { OID v_bag; GC_ANY(v66197= list::empty(Kernel.emptySet)); ((list *) v66197)->addFast(_oid_(v82394)); { { Cast * v88616 = ((Cast *) GC_OBJECT(Cast,new_object_class(Language._Cast))); (v88616->arg = _oid_(v82400)); (v88616->set_arg = domain_I_restriction(OBJECT(restriction,v64147))); add_I_property(Kernel.instances,Language._Cast,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v66197)->addFast(v_bag); ((list *) v66197)->addFast(v82401);} (v66196->args = v66197);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } ((list *) v51919)->addFast(v_bag);} GC_OBJECT(list,v51919);} v82388 = add_star_list(v82388,v51919); } GC_UNLOOP;} } if (v82388->length == 2) Result = (*(v82388))[2]; else { Case * v88616 = ((Case *) GC_OBJECT(Case,new_object_class(Language._Case))); (v88616->var = _oid_(v82400)); (v88616->args = v82388); add_I_property(Kernel.instances,Language._Case,11,_oid_(v88616)); Result = _oid_(v88616); } } GC_UNBIND; return (Result);} } OID Produce_erase_property2(property *v82394,Variable *v82400) { GC_BIND; { OID Result = 0; { list * v82388 = list::empty(Kernel._any); bag * v20105; if (v82394->multivalued_ask == Kernel._list) v20105 = list::empty(Kernel._any); else v20105 = set::empty(Kernel._any); cast_I_bag(v20105,member_type(v82394->range)); { OID gc_local; ITERATE(v64147); for (START(v82394->restrictions); NEXT(v64147);) { GC_LOOP; if ((Kernel._slot == OBJECT(ClaireObject,v64147)->isa) && (boolean_I_any(_oid_(_exp_type(GC_OBJECT(ClaireType,ptype_type(v82400->range)),domain_I_restriction(OBJECT(restriction,v64147))))) == CTRUE)) { list * v49078; { { OID v_bag; GC_ANY(v49078= list::empty(Kernel.emptySet)); ((list *) v49078)->addFast(_oid_(domain_I_restriction(OBJECT(restriction,v64147)))); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); { Call * v66199 = v88616; list * v66200; { OID v_bag; GC_ANY(v66200= list::empty(Kernel.emptySet)); ((list *) v66200)->addFast(_oid_(v82394)); { { Cast * v88616 = ((Cast *) GC_OBJECT(Cast,new_object_class(Language._Cast))); (v88616->arg = _oid_(v82400)); (v88616->set_arg = domain_I_restriction(OBJECT(restriction,v64147))); add_I_property(Kernel.instances,Language._Cast,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v66200)->addFast(v_bag); { if (boolean_I_any(_oid_(v82394->multivalued_ask)) == CTRUE) v_bag = _oid_(v20105); else v_bag = OBJECT(slot,v64147)->DEFAULT; GC_OID(v_bag);} ((list *) v66200)->addFast(v_bag);} (v66199->args = v66200);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v49078)->addFast(v_bag);} GC_OBJECT(list,v49078);} v82388 = add_star_list(v82388,v49078); } GC_UNLOOP;} } if (v82388->length == 2) Result = (*(v82388))[2]; else { Case * v88616 = ((Case *) GC_OBJECT(Case,new_object_class(Language._Case))); (v88616->var = _oid_(v82400)); (v88616->args = v82388); add_I_property(Kernel.instances,Language._Case,11,_oid_(v88616)); Result = _oid_(v88616); } } GC_UNBIND; return (Result);} } OID Produce_put_table2(table *v82394,Variable *v82400,OID v82401) { GC_BIND; { OID Result = 0; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); { Call * v66201 = v88616; list * v66202; { OID v_bag; GC_ANY(v66202= list::empty(Kernel.emptySet)); ((list *) v66202)->addFast(_oid_(v82394)); ((list *) v66202)->addFast(_oid_(v82400)); if (boolean_I_any(_oid_(v82394->multivalued_ask)) == CTRUE) { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.add); (v88616->args = list::alloc(2,_oid_(list::alloc(2,_oid_(Kernel.nth),_oid_(list::alloc(2,_oid_(v82394),_oid_(v82400))))),v82401)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } else v_bag = v82401; ((list *) v66202)->addFast(v_bag);} (v66201->args = v66202);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); Result = _oid_(v88616); } GC_UNBIND; return (Result);} } OID Produce_get_relation2(ClaireRelation *v82394,Variable *v82400) { GC_BIND; { OID Result = 0; if (INHERIT(v82394->isa,Kernel._table)) { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.nth); (v88616->args = list::alloc(2,_oid_(v82394),_oid_(v82400))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); Result = _oid_(v88616); } else if (INHERIT(v82394->isa,Kernel._property)) { list * v82388 = list::empty(Kernel._any); { OID gc_local; ITERATE(v64147); for (START(CLREAD(property,v82394,restrictions)); NEXT(v64147);) { GC_LOOP; if ((Kernel._slot == OBJECT(ClaireObject,v64147)->isa) && (boolean_I_any(_oid_(_exp_type(GC_OBJECT(ClaireType,ptype_type(v82400->range)),domain_I_restriction(OBJECT(restriction,v64147))))) == CTRUE)) { list * v53883; { { OID v_bag; GC_ANY(v53883= list::empty(Kernel.emptySet)); ((list *) v53883)->addFast(_oid_(domain_I_restriction(OBJECT(restriction,v64147)))); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = ((property *) v82394)); { Call * v66204 = v88616; list * v66205; { OID v_bag; GC_ANY(v66205= list::empty(Kernel.emptySet)); { { Cast * v88616 = ((Cast *) GC_OBJECT(Cast,new_object_class(Language._Cast))); (v88616->arg = _oid_(v82400)); (v88616->set_arg = domain_I_restriction(OBJECT(restriction,v64147))); add_I_property(Kernel.instances,Language._Cast,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v66205)->addFast(v_bag);} (v66204->args = v66205);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v53883)->addFast(v_bag);} GC_OBJECT(list,v53883);} v82388 = add_star_list(v82388,v53883); } GC_UNLOOP;} } if (v82388->length == 2) Result = (*(v82388))[2]; else { Case * v88616 = ((Case *) GC_OBJECT(Case,new_object_class(Language._Case))); (v88616->var = _oid_(v82400)); (v88616->args = v82388); add_I_property(Kernel.instances,Language._Case,11,_oid_(v88616)); Result = _oid_(v88616); } } else Result = Kernel.cfalse; GC_UNBIND; return (Result);} } OID Produce_remove_property2(property *v82394,Variable *v82400,OID v82401) { GC_BIND; { OID Result = 0; { list * v82388 = list::empty(Kernel._any); { OID gc_local; ITERATE(v64147); for (START(v82394->restrictions); NEXT(v64147);) { GC_LOOP; if (Kernel._slot == OBJECT(ClaireObject,v64147)->isa) { list * v76947; { { OID v_bag; GC_ANY(v76947= list::empty(Kernel.emptySet)); ((list *) v76947)->addFast(_oid_(domain_I_restriction(OBJECT(restriction,v64147)))); if (boolean_I_any(_oid_(v82394->multivalued_ask)) == CTRUE) { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel._delete); { Call * v66228 = v88616; list * v66229; { OID v_bag; GC_ANY(v66229= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = v82394); (v88616->args = list::alloc(1,_oid_(v82400))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v66229)->addFast(v_bag); ((list *) v66229)->addFast(v82401);} (v66228->args = v66229);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } else { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); (v88616->args = list::alloc(3,_oid_(v82394), _oid_(v82400), CNULL)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } ((list *) v76947)->addFast(v_bag);} GC_OBJECT(list,v76947);} v82388 = add_star_list(v82388,v76947); } GC_UNLOOP;} } if (v82388->length == 2) Result = (*(v82388))[2]; else { Case * v88616 = ((Case *) GC_OBJECT(Case,new_object_class(Language._Case))); (v88616->var = _oid_(v82400)); (v88616->args = v82388); add_I_property(Kernel.instances,Language._Case,11,_oid_(v88616)); Result = _oid_(v88616); } } GC_UNBIND; return (Result);} } OID Produce_remove_table2(table *v82394,Variable *v82400,OID v82401) { GC_BIND; { OID Result = 0; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); { Call * v66230 = v88616; list * v66231; { OID v_bag; GC_ANY(v66231= list::empty(Kernel.emptySet)); ((list *) v66231)->addFast(_oid_(v82394)); ((list *) v66231)->addFast(_oid_(v82400)); if (boolean_I_any(_oid_(v82394->multivalued_ask)) == CTRUE) { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel._delete); (v88616->args = list::alloc(2,_oid_(list::alloc(2,_oid_(Kernel.nth),_oid_(list::alloc(2,_oid_(v82394),_oid_(v82400))))),v82401)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } else v_bag = CNULL; ((list *) v66231)->addFast(v_bag);} (v66230->args = v66231);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); Result = _oid_(v88616); } GC_UNBIND; return (Result);} } void Tighten_relation2(ClaireRelation *v82394) { GC_RESERVE(6); // v3.0.55 optim ! if (INHERIT(v82394->isa,Kernel._property)) { ClaireType * v63419 = set::empty(); ClaireType * v63433 = set::empty(); { OID gc_local; ITERATE(v82395); for (START(CLREAD(property,v82394,restrictions)); NEXT(v82395);) { GC_LOOP; if (Kernel._slot == OBJECT(ClaireObject,v82395)->isa) { GC__ANY(v63419 = U_type(v63419,domain_I_restriction(OBJECT(restriction,v82395))), 3); GC__ANY(v63433 = U_type(v63433,GC_OBJECT(ClaireType,((multi_ask_any(_oid_(v82394)) == CTRUE) ? member_type(OBJECT(restriction,v82395)->range) : OBJECT(restriction,v82395)->range ))), 4); } GC_UNLOOP;} } (v82394->open = 1); (v82394->domain = class_I_type(v63419)); (v82394->range = ((v82394->multivalued_ask == Kernel._list) ? param_I_class(Kernel._list,class_I_type(v63433)) : ((v82394->multivalued_ask == Kernel._set) ? param_I_class(Kernel._set,class_I_type(v63433)) : v63433 ) )); ;} GC_UNBIND;} void lexical_num_any2(OID v13540,Cint v82390) { GC_BIND; if (INHERIT(OWNER(v13540),Language._Call)) lexical_num_any2(GC_OID(_oid_(OBJECT(Call,v13540)->args)),v82390); else if (INHERIT(OWNER(v13540),Language._Instruction)) { ClaireClass * v16967 = OBJECT(ClaireObject,v13540)->isa; if (contain_ask_set(Language._Instruction_with_var->descendents,_oid_(v16967)) == CTRUE) { put_property2(Kernel.index,GC_OBJECT(ClaireObject,OBJECT(ClaireObject,(*Language.var)(v13540))),v82390); ++v82390; if (v82390 > Language._starvariable_index_star->value) (Language._starvariable_index_star->value= v82390); } { OID gc_local; ITERATE(v82395); for (START(v16967->slots); NEXT(v82395);) { GC_LOOP; lexical_num_any2(GC_OID(get_slot(OBJECT(slot,v82395),OBJECT(ClaireObject,v13540))),v82390); GC_UNLOOP;} } } else if (INHERIT(OWNER(v13540),Kernel._bag)) { OID gc_local; ITERATE(v82400); for (START(OBJECT(bag,v13540)); NEXT(v82400);) lexical_num_any2(v82400,v82390); } else ;GC_UNBIND;} ClaireType * c_type_Defrule2_Optimize(Defrule *v13540) { return (Kernel._any);} OID c_code_Defrule_Optimize(Defrule *v13540,ClaireClass *v82395) { GC_RESERVE(11); // v3.0.55 optim ! { OID Result = 0; { OID v63963 = GC_OID(get_symbol(v13540->ident)); list * v82388 = list::empty(Kernel._any); tformat_string(CSTRING("compile a rule ~S \n"),0,list::alloc(1,v63963)); { OID gc_local; ITERATE(v82394); bag *v82394_support; v82394_support = GC_OBJECT(set,OBJECT(bag,nth_table1(Language.relations,v63963))); for (START(v82394_support); NEXT(v82394);) if (eventMethod_ask_relation2(OBJECT(ClaireRelation,v82394)) != CTRUE) Tighten_relation2(OBJECT(ClaireRelation,v82394)); } { OID gc_local; ITERATE(v82394); bag *v82394_support; v82394_support = GC_OBJECT(set,OBJECT(bag,nth_table1(Language.relations,v63963))); for (START(v82394_support); NEXT(v82394);) { GC_LOOP; { if ((*Kernel.open)(v82394) < 2) { OID v81752; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.FINAL); (v88616->args = list::alloc(1,v82394)); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v81752 = _oid_(v88616); } v82388 = v82388->addFast(v81752); } compile_if_write_relation(OBJECT(ClaireRelation,v82394)); { OID v116386 = GC_OID((*Kernel._7_plus)(GC_OID((*Kernel.name)(v82394)), _string_(CSTRING("_write")))); char * v82395 = GC_STRING(string_I_symbol(OBJECT(symbol,v116386))); OID v63758 = GC_OID((*Kernel.if_write)(v82394)); compile_lambda_string(v82395,OBJECT(lambda,v63758),_oid_(Kernel._void)); { OID v82713; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel.put); (v88616->args = list::alloc(3,Optimize.if_write->value, v82394, _oid_(make_function_string(v82395)))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v82713 = _oid_(v88616); } v82388->addFast(v82713); } } } GC_UNLOOP;} } { OID gc_local; ITERATE(v82394); bag *v82394_support; v82394_support = GC_OBJECT(set,OBJECT(bag,nth_table1(Language.relations,v63963))); for (START(v82394_support); NEXT(v82394);) { GC_LOOP; if (eventMethod_ask_relation2(OBJECT(ClaireRelation,v82394)) == CTRUE) v82388= v82388->addFast(GC_OID(compileEventMethod_property(OBJECT(property,v82394)))); GC_UNLOOP;} } { OID v83674; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); (v88616->args = v82388); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v83674 = _oid_(v88616); } Result = (*Optimize.c_code)(v83674, _oid_(v82395)); } } GC_UNBIND; return (Result);} } void compile_if_write_relation(ClaireRelation *v82362) { GC_BIND; { OID v82388 = GC_OID(nth_table1(Language.demons,_oid_(v82362))); list * v83155 = GC_OBJECT(list,OBJECT(Language_demon,(*(OBJECT(bag,v82388)))[1])->formula->vars); list * v63709 = list::alloc(Kernel._any,1,GC_OID((*Optimize.Produce_put)(_oid_(v82362), (*(v83155))[1], (*(v83155))[2]))); list * v63710; { { bag *v_list; OID v_val; OID v82400,CLcount; v_list = OBJECT(bag,v82388); v63710 = v_list->clone(Kernel._any); for (CLcount= 1; CLcount <= v_list->length; CLcount++) { v82400 = (*(v_list))[CLcount]; v_val = substitution_any(substitution_any(substitution_any(OBJECT(Language_demon,v82400)->formula->body,OBJECT(Variable,(*(OBJECT(Language_demon,v82400)->formula->vars))[3]),(*(v83155))[3]),OBJECT(Variable,(*(OBJECT(Language_demon,v82400)->formula->vars))[1]),(*(v83155))[1]),OBJECT(Variable,(*(OBJECT(Language_demon,v82400)->formula->vars))[2]),(*(v83155))[2]); (*((list *) v63710))[CLcount] = v_val;} } GC_OBJECT(list,v63710);} put_property2(Kernel.range,OBJECT(ClaireObject,(*(v83155))[1]),_oid_(v82362->domain)); put_property2(Kernel.range,OBJECT(ClaireObject,(*(v83155))[2]),_oid_(v82362->range)); { ITERATE(v82398); for (START(v83155); NEXT(v82398);) put_property2(Kernel.range,OBJECT(ClaireObject,v82398),_oid_(class_I_type(OBJECT(ClaireType,(*Kernel.range)(v82398))))); } if ((INHERIT(OWNER((*(v63710))[1]),Language._If)) && (eventMethod_ask_relation2(v82362) != CTRUE)) { if (INHERIT(OWNER(OBJECT(If,(*(v63710))[1])->test),Language._And)) { If * v66235 = OBJECT(If,(*(v63710))[1]); OID v66236; { And * v88616 = ((And *) GC_OBJECT(And,new_object_class(Language._And))); (v88616->args = cdr_list(GC_OBJECT(list,OBJECT(list,(*Core.args)(GC_OID(OBJECT(If,(*(v63710))[1])->test)))))); add_I_property(Kernel.instances,Language._And,11,_oid_(v88616)); v66236 = _oid_(v88616); } (v66235->test = v66236);} else ((*(v63710))[1]=OBJECT(If,(*(v63710))[1])->arg); } if (((v82362->inverse == (NULL)) ? CTRUE : CFALSE) != CTRUE) { if (multi_ask_any(_oid_(v82362)) != CTRUE) v63709= GC_OBJECT(list,v63709->addFast(GC_OID((*Optimize.Produce_remove)(_oid_(v82362->inverse), (*(v83155))[3], (*(v83155))[1])))); v63709= GC_OBJECT(list,v63709->addFast(GC_OID((*Optimize.Produce_put)(_oid_(v82362->inverse), (*(v83155))[2], (*(v83155))[1])))); } { ClaireRelation * v66258 = v82362; OID v66259; { lambda * v74511;{ OID v109621; if (eventMethod_ask_relation2(v82362) == CTRUE) { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); (v88616->args = v63710); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v109621 = _oid_(v88616); } else if (multi_ask_any(_oid_(v82362)) == CTRUE) { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v66262 = v88616; OID v66263; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core.NOT); { Call * v66264 = v88616; list * v66265; { OID v_bag; GC_ANY(v66265= list::empty(Kernel.emptySet)); { { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Kernel._Z); (v88616->args = list::alloc(2,(*(v83155))[2],GC_OID(_oid_(readCall_relation(v82362,(*(v83155))[1]))))); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v_bag = _oid_(v88616); } GC_OID(v_bag);} ((list *) v66265)->addFast(v_bag);} (v66264->args = v66265);} add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v66263 = _oid_(v88616); } (v66262->test = v66263);} { If * v66266 = v88616; OID v66267; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); (v88616->args = append_list(v63709,v63710)); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v66267 = _oid_(v88616); } (v66266->arg = v66267);} add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); (v88616->other = Kernel.cfalse); v109621 = _oid_(v88616); } else { Let * v88616 = ((Let *) GC_OBJECT(Let,new_object_class(Language._Let))); store_object(v88616, 2, Kernel._object, (*(v83155))[3], CFALSE); (v88616->value = _oid_(readCall_relation(v82362,(*(v83155))[1]))); { Let * v66289 = v88616; OID v66290; { If * v88616 = ((If *) GC_OBJECT(If,new_object_class(Language._If))); { If * v66291 = v88616; OID v66292; { Call * v88616 = ((Call *) GC_OBJECT(Call,new_object_class(Language._Call))); (v88616->selector = Core._I_equal); (v88616->args = list::alloc(2,(*(v83155))[2],(*(v83155))[3])); add_I_property(Kernel.instances,Language._Call,11,_oid_(v88616)); v66292 = _oid_(v88616); } (v66291->test = v66292);} { If * v66293 = v88616; OID v66294; { Do * v88616 = ((Do *) GC_OBJECT(Do,new_object_class(Language._Do))); (v88616->args = append_list(v63709,v63710)); add_I_property(Kernel.instances,Language._Do,11,_oid_(v88616)); v66294 = _oid_(v88616); } (v66293->arg = v66294);} add_I_property(Kernel.instances,Language._If,11,_oid_(v88616)); (v88616->other = Kernel.cfalse); v66290 = _oid_(v88616); } (v66289->arg = v66290);} add_I_property(Kernel.instances,Language._Let,11,_oid_(v88616)); v109621 = _oid_(v88616); } v74511 = lambda_I_list(list::alloc(2,(*(v83155))[1],(*(v83155))[2]),v109621); } v66259=_oid_(v74511);} (v66258->if_write = v66259);} } GC_UNBIND;} OID compileEventMethod_property(property *v82392) { GC_BIND; { OID Result = 0; { method * v82389 = OBJECT(method,(*(v82392->restrictions))[1]); char * v63819 = GC_STRING(append_string(GC_STRING(string_I_symbol(v82392->name)),CSTRING("_write"))); Result = add_method_I_method(v82389, list::alloc(2,_oid_(v82392->domain),_oid_(v82392->range)), _oid_(Kernel._void), 0, make_function_string(v63819)); } GC_UNBIND; return (Result);} }
// generated from // rosidl_typesupport_introspection_cpp/resource/srv__rosidl_typesupport_introspection_cpp.hpp.em // generated code does not contain a copyright notice #ifndef RCL_INTERFACES__SRV__SET_PARAMETERS__ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_HPP_ #define RCL_INTERFACES__SRV__SET_PARAMETERS__ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_HPP_ #include <rosidl_generator_c/service_type_support_struct.h> #include "rosidl_typesupport_interface/macros.h" #include "rosidl_typesupport_introspection_cpp/visibility_control.h" #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC const rosidl_service_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__SERVICE_SYMBOL_NAME(rosidl_typesupport_introspection_cpp, rcl_interfaces, srv, SetParameters)(); #ifdef __cplusplus } #endif #endif // RCL_INTERFACES__SRV__SET_PARAMETERS__ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_HPP_
#include "BlobDataController.h" VerticalSequencer::VerticalSequencer(float loopTime, int channel, ofColor col) { mChannel = channel; mCol.set(col); mLoopTime = loopTime; setup(); } void VerticalSequencer::setup() { mPos = mLastPos = 0; } void VerticalSequencer::update(float tick) { mLastPos = mPos; if (mLastPos > mLoopTime) { mPos = 0; mLastPos = 0; } mPos += tick; } void VerticalSequencer::emit(const BLOBS_TYPE& blobs) { float y1 = ofMap(mLastPos, 0, mLoopTime, 0, mHeight); float y2 = ofMap(mPos, 0, mLoopTime, 0, mHeight); for (const auto& e : blobs) { if (e.hole) continue; const ofPoint& pos = e.centroid; if (pos.y > y1 && pos.y <= y2) { Sequencer::sendNote(e, 0.5, mChannel); sequencerAnimation::manager.createInstance<sequencerAnimation::BlobDrawr>(&e, mCol)->play(0.5); BlobNoteEvent event(&e, mChannel); ofNotifyEvent(mBlobNoteEvent, event, this); } } } void VerticalSequencer::draw(int x, int y, int w, int h) { ofPushStyle(); ofSetColor(mCol); ofFill(); ofSetLineWidth(10); float posY1 = ofMap(mLastPos, 0, mLoopTime, y, y + h); float posY2 = ofMap(mPos, 0, mLoopTime, y, y + h); ofRect(x, posY1, x + w, posY2 - posY1); ofPopStyle(); } //----------------------------------------------------------------------------------------------- OrdinalSequencer::OrdinalSequencer(float maxDurationToNext, bool loop, int channel, ofColor col) { mMaxDurationToNext = maxDurationToNext; mChannel = channel; mCol.set(col); bLoop = loop; setup(); } void OrdinalSequencer::setup() { mCurrentIndex = 0; mCount = 0; mDurationToNext = 0; bPlay = true; mLastPos.set(0, 0); mTargetPos.set(0, 0); } void OrdinalSequencer::update(float tick) { if (!bPlay) { mCount += tick; if (mDurationToNext < mCount) { bPlay = true; } } } void OrdinalSequencer::emit(const BLOBS_TYPE& blobs) { if (bPlay) { if (blobs.empty() || mCurrentIndex >= blobs.size()) return; // send midi Sequencer::sendNote(blobs[mCurrentIndex], mMaxDurationToNext, mChannel); sequencerAnimation::manager.createInstance<sequencerAnimation::BlobDrawr>(&blobs[mCurrentIndex], mCol)->play(0.5); // notify event BlobNoteEvent event(&blobs[mCurrentIndex], mChannel); ofNotifyEvent(mBlobNoteEvent, event, this); // set duration to next if (mCurrentIndex + 1 >= blobs.size()) { if (bLoop) { // loop setup(); mDurationToNext = mMaxDurationToNext; bPlay = false; return; } else { // stop sequence setup(); bPlaying = false; return; } } else { mLastPos.set(blobs[mCurrentIndex].centroid); mTargetPos.set(blobs[mCurrentIndex + 1].centroid); float dist = ofDist(blobs[mCurrentIndex ].centroid.x, blobs[mCurrentIndex ].centroid.y, blobs[mCurrentIndex+1].centroid.x, blobs[mCurrentIndex+1].centroid.y); mDurationToNext = mMaxDurationToNext; } // reset bPlay = false; mCurrentIndex++; mCount = 0; } } void OrdinalSequencer::draw(int x, int y, int w, int h) { if (mLastPos.match(mTargetPos) || mDurationToNext == 0) return; ofPushMatrix(); ofTranslate(x, y); ofSetColor(mCol); ofFill(); ofVec2f pos = mLastPos.interpolate(mTargetPos, ofMap(mCount, 0, mDurationToNext, 0, 1)); ofCircle(pos.x * w, pos.y * h, 5); ofPopMatrix(); } //----------------------------------------------------------------------------------------------- RandomSequencer::RandomSequencer(float maxDurationToNext, int channel, ofColor col) { mMaxDurationToNext = maxDurationToNext; mChannel = channel; mCol.set(col); setup(); } void RandomSequencer::setup() { mCount = 0; mCurrentIndex = 0; mDurationToNext = 0; bPlay = true; mLastPos.set(0, 0); mTargetPos.set(0, 0); } void RandomSequencer::update(float tick) { if (!bPlay) { mCount += tick; if (mDurationToNext < mCount) { bPlay = true; } } } void RandomSequencer::emit(const BLOBS_TYPE& blobs) { if (bPlay) { int nextIndex = ofRandom(blobs.size()); if (blobs.empty() || mCurrentIndex >= blobs.size()) return; // send midi Sequencer::sendNote(blobs[mCurrentIndex], mMaxDurationToNext, mChannel); sequencerAnimation::manager.createInstance<sequencerAnimation::BlobDrawr>(&blobs[mCurrentIndex], mCol)->play(0.5); // notify event BlobNoteEvent event(&blobs[mCurrentIndex], mChannel); ofNotifyEvent(mBlobNoteEvent, event, this); // set duration to next mLastPos.set(blobs[mCurrentIndex].centroid); mTargetPos.set(blobs[nextIndex].centroid); float dist = ofDist(blobs[mCurrentIndex ].centroid.x, blobs[mCurrentIndex ].centroid.y, blobs[nextIndex].centroid.x, blobs[nextIndex].centroid.y); mDurationToNext = mMaxDurationToNext; // reset bPlay = false; mCurrentIndex = nextIndex; mCount = 0; } } void RandomSequencer::draw(int x, int y, int w, int h) { if (mLastPos.match(mTargetPos) || mDurationToNext == 0) return; ofPushMatrix(); ofTranslate(x, y); ofSetColor(mCol); ofFill(); ofVec2f pos = mLastPos.interpolate(mTargetPos, ofMap(mCount, 0, mDurationToNext, 0, 1)); ofCircle(pos.x * w, pos.y * h, 5); ofPopMatrix(); } ///////////////////////////////////////////////////////////////////////////////////////////////// // // BLOBS DATA CONTROLLER // ///////////////////////////////////////////////////////////////////////////////////////////////// BlobsDataController::BlobsDataController() { float pct = 1.8; mSeq.push_back(new VerticalSequencer(4 * pct, 1, ofColor(0, 255, 255))); mSeq.push_back(new VerticalSequencer(2 * pct, 2, ofColor(255, 0, 255))); mSeq.push_back(new OrdinalSequencer(0.25 * pct, true, 3, ofColor(127, 255, 0))); mSeq.push_back(new OrdinalSequencer(1.00 * pct, true, 4, ofColor(255, 127, 0))); mSeq.push_back(new RandomSequencer(0.125 * pct, 5, ofColor(255, 127, 255))); mSeq.push_back(new OrdinalSequencer(2.00 * pct, true, 6, ofColor(0, 0, 255))); mSeq.push_back(new OrdinalSequencer(0.50, false, 9, ofColor(255, 255, 0))); for (auto& e : mSeq) { ofAddListener(e->mBlobNoteEvent, this, &BlobsDataController::sequencerCallback); } } void BlobsDataController::setupMidi(const string& senderPoitName, const string& receiverPortName) { MIDI_SENDER->listPorts(); MIDI_SENDER->openPort(senderPoitName); MIDI_RECEIVER->openPort(receiverPortName); // ofAddListener(MIDI_RECEIVER->receivedMidiEvent, this, &BlobsDataController::receivedMidiMessage); } void BlobsDataController::update() { const float tick = ofGetLastFrameTime(); for (auto& e : mSeq) { if (e->isPlaying()) { e->setSize(1, 1); e->update(tick); e->emit(mBlobs); } } sequencerAnimation::manager.update(); } void BlobsDataController::draw(int x, int y, int w, int h) { ofPushStyle(); ofSetColor(255, 0, 0); ofPushMatrix(); ofTranslate(x, y); ofNoFill(); for( int i=0; i<(int)mBlobs.size(); i++ ) { ofRect(mBlobs[i].boundingRect.x * w, mBlobs[i].boundingRect.y * h, mBlobs[i].boundingRect.width * w, mBlobs[i].boundingRect.height * h); } for( int i=0; i<(int)mBlobs.size(); i++ ) { ofNoFill(); mBlobs[i].hole ? ofSetColor(0, 0, 255) : ofSetColor(0, 255, 0); ofBeginShape(); for( int j=0; j<mBlobs[i].nPts; j++ ) { ofVertex( mBlobs[i].pts[j].x * w, mBlobs[i].pts[j].y * h ); } ofEndShape(); } sequencerAnimation::manager.draw(); ofPopMatrix(); for (auto& e : mSeq) { e->draw(x, y, w, h); } ofPopStyle(); } void BlobsDataController::sequencerCallback(BlobNoteEvent& e) { ofNotifyEvent(mBlobNoteEvent, e, this); } void BlobsDataController::sequencerPlay(int sequencerIndex) { if (sequencerIndex < 0 || sequencerIndex >= mSeq.size()) return; mSeq[sequencerIndex]->setup(); mSeq[sequencerIndex]->play(); } void BlobsDataController::sequencerStop(int sequencerIndex) { if (sequencerIndex < 0 || sequencerIndex >= mSeq.size()) return; mSeq[sequencerIndex]->setup(); mSeq[sequencerIndex]->stop(); } void BlobsDataController::sequencerTogglePlay(int sequencerIndex) { if (sequencerIndex < 0 || sequencerIndex >= mSeq.size()) return; mSeq[sequencerIndex]->setup(); mSeq[sequencerIndex]->togglePlay(); } void BlobsDataController::addBlob(ofxCvBlob& cvBlob, float w, float h, float offsetW) { mBlobs.push_back(Blob(cvBlob, w, h, offsetW)); } void BlobsDataController::removeBlob() { // FIXME: blob pointer // if (!mBlobs.empty()) // { // mBlobs.pop_back(); // } } const BLOBS_TYPE& BlobsDataController::getBlobsRef() const { return mBlobs; } void BlobsDataController::drawSeq(int index, int x, int y, int w, int h) { if (index >= 0 || index < mSeq.size()) { mSeq[index]->draw(x, y, w, h); } } void BlobsDataController::drawSeqAll(int x, int y, int w, int h) { for (auto e : mSeq) { e->draw(x, y, w, h); } }
// { Driver Code Starts #include <iostream> using namespace std; // } Driver Code Ends class Solution{ public: // Function to find equilibrium point in the array. // a: input array // n: size of array int equilibriumPoint(long long a[], int n) { // Your code here int sum =0; for(int i=0;i<n;i++) { sum+=a[i]; } int lsum=0; for(int i=0;i<n;i++) { if(lsum==sum-a[i]) return i+1; lsum += a[i]; sum -= a[i]; } return -1; } }; // { Driver Code Starts. int main() { long long t; //taking testcases cin >> t; while (t--) { long long n; //taking input n cin >> n; long long a[n]; //adding elements to the array for (long long i = 0; i < n; i++) { cin >> a[i]; } Solution ob; //calling equilibriumPoint() function cout << ob.equilibriumPoint(a, n) << endl; } return 0; } // } Driver Code Ends
#include <iostream> #include "SDL.h" #include "SDL_opengl.h" #include "IRenderWorld.hpp" #include "glm/gtc/matrix_transform.hpp" constexpr int Width = 1280; constexpr int Height = 720; /* Generally, the way this works is the following: * Create the window using your preferred framework (in this case SDL2) * Initialise the render system * Initialise the render world with render initialisation parameters (window resolution, preferred render backend etc.) * Create/load a model * Create a render entity with the model * Create a render view * Render In a game engine, it could go something like this: ''' void Entity::Spawn() { renderEntity = renderWorld->CreateEntity( renderEntityParams ); } void Entity::PrecacheModel( string modelPath ) { renderEntityParams.model = renderWorld->CreateModel( { modelPath, RenderModelType::FromFile } ); } ''' oooor: ''' void Game::Init() { if ( !IsDedicatedServer() ) { InitialiseRenderer(); foreach ( modelFile in "assets/models" ) { auto model = modelManager.LoadModel( modelFile ); modelHandles.push_back( renderWorld->CreateModel( { model.GetPath(), RenderModelType::FromFile } ); } } else { foreach ( modelFile in "assets/models" ) { modelManager.LoadModel( modelFile ); } } } void Game::Draw() { renderWorld->RenderFrame( GetCurrentCamera().GetRenderView() ); } ''' You get the idea by now, I suppose. */ int main( int argc, char** argv ) { // ===================================== // STEP 1 // Init SDL2 here and make a window SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ); // Set the OpenGL context version SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 4 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 5 ); // Create the window and context SDL_Window* window = SDL_CreateWindow( "FoxGLBox test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Width, Height, SDL_WINDOW_OPENGL ); SDL_GLContext glContext = SDL_GL_CreateContext( window ); // Also initialise the render system, which is just a thing // that we can use to obtain other subsystems from FoxGLBox // // At the moment, it only has the renderer system in it, but // later on, it'll also have the material system exposed // // GetRenderSystem doesn't allocate anything, so you can // simply call foxglbox::GetRenderSystem() every time you wanna // access something. I just do this to decrease typing IRenderSystem* renderSystem = foxglbox::GetRenderSystem(); // ===================================== // STEP 2 // Renderer initialisation parameters RenderInitParams rip { Width, Height, // resolution RenderInitParams::Renderer_OpenGL45,// render backend RenderInitParams::Windowing_SDL2, // SDL2 windowing glContext // OpenGL context }; // ===================================== // STEP 3 // Primary render view // You can think of a render view as a camera RenderView rv { Width, Height, // viewport dimensions 0, // render mask glm::vec3( 0.0f, 0.0f, -1.0f ), // position glm::identity<glm::mat4>(), // orientation matrix 105.0f, // FOV false // orthographic }; // ===================================== // STEP 4 // Get the render world // The render world is basically the render "frontend" here IRenderWorld* renderWorld = renderSystem->InitRenderer( rip ); if ( nullptr == renderWorld ) { std::cout << "Could not initialise the renderer" << std::endl; return 1; } // ===================================== // STEP 5 // Load model RenderModelParams modelParams { "text2.obj", // model path relative to the .exe RenderModelType::FromFile // model type, dynamic models aren't yet there }; // Actually load the model and get a handle auto modelHandle = renderWorld->CreateModel( modelParams ); if ( modelHandle == RenderHandleInvalid ) { std::cout << "Could not load text.obj"; return 1; } // Create a render entity that uses this model RenderEntityParams entityParams { glm::vec3( 0.0f, 0.0f, 0.0f ), // position glm::identity<glm::mat4>(), // orientation modelHandle, // model ID 0 // render mask }; // ===================================== // STEP 6 // Create the render entity and get a handle to it // Keep in mind, this is not a GAME entity, this is a RENDER entity auto entityHandle = renderWorld->CreateEntity( entityParams ); if ( entityHandle == RenderHandleInvalid ) { std::cout << "Could not create a render entity"; return 1; } // Turning on VSync here so my GPU (and yours) doesn't crash'n'burn SDL_GL_SetSwapInterval( 1 ); // ===================================== // STEP 7 // Render stuff float time = 0.0f; bool quit = false; SDL_Event e; while ( !quit ) { time += 0.016f; // Update the time so we can rotate the render entities while ( SDL_PollEvent( &e ) ) { if ( e.type == SDL_QUIT ) quit = true; if ( e.type == SDL_KEYDOWN ) { // Press R to reload shaders if ( e.key.keysym.sym == SDLK_r ) renderWorld->ReloadShaders(); // Simple back'n'forth movement if ( e.key.keysym.sym == SDLK_w ) rv.cameraPosition.z += 0.05f; if ( e.key.keysym.sym == SDLK_s ) rv.cameraPosition.z -= 0.05f; } // Zooming in/out if ( e.type == SDL_MOUSEWHEEL ) rv.cameraFov -= e.wheel.y * 5.0f; } // Example of moving the camera rv.cameraPosition.x = sin( time * 0.25f ) * 0.125f; // Crude example of rotating the render entity // Ideally you'd calculate/obtain the orientation matrix from your game's physics or directly from the game entity/object entityParams.orientation = glm::rotate( entityParams.orientation, glm::radians( 0.5f ), glm::vec3( 0.0f, 1.0f, 0.0f ) ); renderWorld->UpdateEntity( entityHandle, entityParams ); renderWorld->RenderFrame( rv ); SDL_GL_SwapWindow( window ); } // ===================================== // STEP 7 // Shut everything down renderWorld->Shutdown(); SDL_Quit(); return 0; } /* Copyright (c) 2021 Admer456 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/search/omnibox_result.h" #include <stddef.h> #include "base/strings/string_split.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/app_list_controller_delegate.h" #include "chrome/browser/ui/app_list/search/search_util.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/omnibox/browser/autocomplete_controller.h" #include "components/omnibox/browser/autocomplete_match_type.h" #include "grit/theme_resources.h" #include "ui/app_list/app_list_constants.h" #include "ui/base/resource/material_design/material_design_controller.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/gfx/vector_icons_public.h" #include "url/gurl.h" #include "url/url_canon.h" using bookmarks::BookmarkModel; namespace app_list { namespace { int ACMatchStyleToTagStyle(int styles) { int tag_styles = 0; if (styles & ACMatchClassification::URL) tag_styles |= SearchResult::Tag::URL; if (styles & ACMatchClassification::MATCH) tag_styles |= SearchResult::Tag::MATCH; if (styles & ACMatchClassification::DIM) tag_styles |= SearchResult::Tag::DIM; return tag_styles; } // Translates ACMatchClassifications into SearchResult tags. void ACMatchClassificationsToTags( const base::string16& text, const ACMatchClassifications& text_classes, SearchResult::Tags* tags) { int tag_styles = SearchResult::Tag::NONE; size_t tag_start = 0; for (size_t i = 0; i < text_classes.size(); ++i) { const ACMatchClassification& text_class = text_classes[i]; // Closes current tag. if (tag_styles != SearchResult::Tag::NONE) { tags->push_back(SearchResult::Tag( tag_styles, tag_start, text_class.offset)); tag_styles = SearchResult::Tag::NONE; } if (text_class.style == ACMatchClassification::NONE) continue; tag_start = text_class.offset; tag_styles = ACMatchStyleToTagStyle(text_class.style); } if (tag_styles != SearchResult::Tag::NONE) { tags->push_back(SearchResult::Tag( tag_styles, tag_start, text.length())); } } // Returns true if |url| is on a Google Search domain. May return false // positives. bool IsUrlGoogleSearch(const GURL& url) { // Just return true if the second or third level domain is "google". This may // result in false positives (e.g. "google.example.com"), but since we are // only using this to decide when to add the spoken feedback query parameter, // this doesn't have any bad consequences. const char kGoogleDomainLabel[] = "google"; std::vector<std::string> pieces = base::SplitString( url.host(), ".", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); size_t num_pieces = pieces.size(); if (num_pieces >= 2 && pieces[num_pieces - 2] == kGoogleDomainLabel) return true; if (num_pieces >= 3 && pieces[num_pieces - 3] == kGoogleDomainLabel) return true; return false; } // Converts a Google Search URL into a spoken feedback URL, by adding query // parameters. |search_url| must be a Google Search URL. GURL MakeGoogleSearchSpokenFeedbackUrl(const GURL& search_url) { std::string query = search_url.query(); query += "&gs_ivs=1"; GURL::Replacements replacements; replacements.SetQueryStr(query); return search_url.ReplaceComponents(replacements); } } // namespace OmniboxResult::OmniboxResult(Profile* profile, AppListControllerDelegate* list_controller, AutocompleteController* autocomplete_controller, bool is_voice_query, const AutocompleteMatch& match) : profile_(profile), list_controller_(list_controller), autocomplete_controller_(autocomplete_controller), is_voice_query_(is_voice_query), match_(match) { if (match_.search_terms_args && autocomplete_controller_) { match_.search_terms_args->from_app_list = true; autocomplete_controller_->UpdateMatchDestinationURL( *match_.search_terms_args, &match_); } set_id(match_.destination_url.spec()); // Derive relevance from omnibox relevance and normalize it to [0, 1]. // The magic number 1500 is the highest score of an omnibox result. // See comments in autocomplete_provider.h. set_relevance(match_.relevance / 1500.0); UpdateIcon(); UpdateTitleAndDetails(); // The raw "what you typed" search results should be promoted and // automatically selected by voice queries. If a "history" result exactly // matches what you typed, then the omnibox will not produce a "what you // typed" result; therefore, we must also flag "history" results as voice // results if they exactly match the query. if (match_.type == AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED || (match_.type == AutocompleteMatchType::SEARCH_HISTORY && match_.search_terms_args && match_.contents == match_.search_terms_args->original_query)) { set_voice_result(true); } } OmniboxResult::~OmniboxResult() { } void OmniboxResult::Open(int event_flags) { RecordHistogram(OMNIBOX_SEARCH_RESULT); GURL url = match_.destination_url; if (is_voice_query_ && IsUrlGoogleSearch(url)) { url = MakeGoogleSearchSpokenFeedbackUrl(url); } list_controller_->OpenURL(profile_, url, match_.transition, ui::DispositionFromEventFlags(event_flags)); } scoped_ptr<SearchResult> OmniboxResult::Duplicate() const { return scoped_ptr<SearchResult>(new OmniboxResult(profile_, list_controller_, autocomplete_controller_, is_voice_query_, match_)); } void OmniboxResult::UpdateIcon() { BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile_); bool is_bookmarked = bookmark_model && bookmark_model->IsBookmarked(match_.destination_url); if (ui::MaterialDesignController::IsModeMaterial()) { gfx::VectorIconId icon_id = is_bookmarked ? gfx::VectorIconId::OMNIBOX_STAR : AutocompleteMatch::TypeToVectorIcon(match_.type); SetIcon(gfx::CreateVectorIcon(icon_id, 16, app_list::kIconColor)); return; } int resource_id = is_bookmarked ? IDR_OMNIBOX_STAR : AutocompleteMatch::TypeToIcon(match_.type); SetIcon( *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id)); } void OmniboxResult::UpdateTitleAndDetails() { set_title(match_.contents); SearchResult::Tags title_tags; ACMatchClassificationsToTags(match_.contents, match_.contents_class, &title_tags); set_title_tags(title_tags); set_details(match_.description); SearchResult::Tags details_tags; ACMatchClassificationsToTags(match_.description, match_.description_class, &details_tags); set_details_tags(details_tags); } } // namespace app_list
version https://git-lfs.github.com/spec/v1 oid sha256:b09270e5e76688f9093c055d4f92cf82d612cbc2f3d3d69e2343bbfd3acb8b13 size 425
/* * * * * * * * * * * * * * * * * * * * * @author: Xingjian Bai * @date: 2020-12-30 15:29:36 * @description: * /Users/jackbai/Desktop/Goodbye2020/data.cpp * * @notes: * g++ -fsanitize=address -ftrapv data.cpp * * * * * * * * * * * * * * * * * */ #include <bits/stdc++.h> #define F first #define S second #define MP make_pair #define TIME (double)clock()/CLOCKS_PER_SEC using namespace std; typedef long long ll; typedef long double ld; typedef pair <int, int> pii; const int MOD = 1000000007; const ll INF = 1e18; const ld eps = 1e-8; #define FOR(i,a,b) for (int i = (a); i < (b); i ++) #define F0R(i,a) FOR(i, 0, a) #define ROF(i, a, b) for (int i = (b) - 1; i >= a; i --) #define R0F(i, a) ROF(i, 0, a) #define trav(a, x) for (auto& a: x) #define debug(x) cerr << "(debug mod) " << #x << " = " << x << endl int main() { cout << 50 << endl; cout << 50 << endl; for (int i = 1; i <= 50; i ++) cout << i << ' ' << i << endl; cout << endl; return 0; }
/* * Copyright (c) 2019, The OpenThread Authors. * 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. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER 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. */ /** * @file * This file includes definitions for MAC radio links. */ #ifndef MAC_LINKS_HPP_ #define MAC_LINKS_HPP_ #include "openthread-core-config.h" #include "common/debug.hpp" #include "common/locator.hpp" #include "mac/mac_frame.hpp" #include "mac/mac_types.hpp" #include "mac/sub_mac.hpp" #include "radio/trel_link.hpp" namespace ot { namespace Mac { /** * @addtogroup core-mac * * @brief * This module includes definitions for MAC radio links (multi radio). * * @{ * */ /** * This class represents tx frames for different radio link types. * */ class TxFrames : InstanceLocator { friend class Links; public: #if OPENTHREAD_CONFIG_MULTI_RADIO /** * This method gets the `TxFrame` for a given radio link type. * * This method also updates the selected radio types (from `GetSelectedRadioTypes()`) to include the @p aRadioType. * * @param[in] aRadioType A radio link type. * * @returns A reference to the `TxFrame` for the given radio link type. * */ TxFrame &GetTxFrame(RadioType aRadioType); /** * This method gets the `TxFrame` with the smallest MTU size among a given set of radio types. * * This method also updates the selected radio types (from `GetSelectedRadioTypes()`) to include the set * @p aRadioTypes. * * @param[in] aRadioTypes A set of radio link types. * * @returns A reference to the `TxFrame` with the smallest MTU size among the set of @p aRadioTypes. * */ TxFrame &GetTxFrame(RadioTypes aRadioTypes); /** * This method gets the `TxFrame` for sending a broadcast frame. * * This method also updates the selected radio type (from `GetSelectedRadioTypes()`) to include all radio types * (supported by device). * * The broadcast frame is the `TxFrame` with the smallest MTU size among all radio types. * * @returns A reference to a `TxFrame` for broadcast. * */ TxFrame &GetBroadcastTxFrame(void); /** * This method gets the selected radio types. * * This set specifies the radio links the frame should be sent over (in parallel). The set starts a empty after * method `Clear()` is called. It gets updated through calls to methods `GetTxFrame(aType)`, * `GetTxFrame(aRadioTypes)`, or `GetBroadcastTxFrame()`. * * @returns The selected radio types. * */ RadioTypes GetSelectedRadioTypes(void) const { return mSelectedRadioTypes; } /** * This method gets the required radio types. * * This set specifies the radio links for which we expect the frame tx to be successful to consider the overall tx * successful. If the set is empty, successful tx over any radio link is sufficient for overall tx to be considered * successful. The required radio type set is expected to be a subset of selected radio types. * * The set starts as empty after `Clear()` call. It can be updated through `SetRequiredRadioTypes()` method * * @returns The required radio types. * */ RadioTypes GetRequiredRadioTypes(void) const { return mRequiredRadioTypes; } /** * This method sets the required types. * * Please see `GetRequiredRadioTypes()` for more details on how this set is used during tx. * * @param[in] aRadioTypes A set of radio link types. * */ void SetRequiredRadioTypes(RadioTypes aRadioTypes) { mRequiredRadioTypes = aRadioTypes; } #else // #if OPENTHREAD_CONFIG_MULTI_RADIO #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE /** * This method gets the tx frame. * * @returns A reference to `TxFrame`. * */ TxFrame &GetTxFrame(void) { return mTxFrame802154; } #elif OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE /** * This method gets the tx frame. * * @returns A reference to `TxFrame`. * */ TxFrame &GetTxFrame(void) { return mTxFrameTrel; } #endif /** * This method gets a tx frame for sending a broadcast frame. * * @returns A reference to a `TxFrame` for broadcast. * */ TxFrame &GetBroadcastTxFrame(void) { return GetTxFrame(); } #endif // #if OPENTHREAD_CONFIG_MULTI_RADIO /** * This method clears all supported radio tx frames (sets the PSDU length to zero and clears flags). * */ void Clear(void) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mTxFrame802154.SetLength(0); mTxFrame802154.SetIsARetransmission(false); mTxFrame802154.SetIsSecurityProcessed(false); mTxFrame802154.SetCsmaCaEnabled(true); // Set to true by default, only set to `false` for CSL transmission mTxFrame802154.SetIsHeaderUpdated(false); #if OPENTHREAD_FTD && OPENTHREAD_CONFIG_MAC_CSL_TRANSMITTER_ENABLE mTxFrame802154.SetTxDelay(0); mTxFrame802154.SetTxDelayBaseTime(0); #endif #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTxFrameTrel.SetLength(0); mTxFrameTrel.SetIsARetransmission(false); mTxFrameTrel.SetIsSecurityProcessed(false); mTxFrameTrel.SetCsmaCaEnabled(true); mTxFrameTrel.SetIsHeaderUpdated(false); #endif #if OPENTHREAD_CONFIG_MULTI_RADIO mSelectedRadioTypes.Clear(); mRequiredRadioTypes.Clear(); #endif } /** * This method sets the channel on all supported radio tx frames. * * @param[in] aChannel A channel. * */ void SetChannel(uint8_t aChannel) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mTxFrame802154.SetChannel(aChannel); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTxFrameTrel.SetChannel(aChannel); #endif } /** * This method sets the Sequence Number value on all supported radio tx frames. * * @param[in] aSequence The Sequence Number value. * */ void SetSequence(uint8_t aSequence) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mTxFrame802154.SetSequence(aSequence); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTxFrameTrel.SetSequence(aSequence); #endif } /** * This method sets the maximum number of the CSMA-CA backoffs on all supported radio tx * frames. * * @param[in] aMaxCsmaBackoffs The maximum number of CSMA-CA backoffs. * */ void SetMaxCsmaBackoffs(uint8_t aMaxCsmaBackoffs) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mTxFrame802154.SetMaxCsmaBackoffs(aMaxCsmaBackoffs); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTxFrameTrel.SetMaxCsmaBackoffs(aMaxCsmaBackoffs); #endif } /** * This method sets the maximum number of retries allowed after a transmission failure on all supported radio tx * frames. * * @param[in] aMaxFrameRetries The maximum number of retries allowed after a transmission failure. * */ void SetMaxFrameRetries(uint8_t aMaxFrameRetries) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mTxFrame802154.SetMaxFrameRetries(aMaxFrameRetries); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTxFrameTrel.SetMaxFrameRetries(aMaxFrameRetries); #endif } private: explicit TxFrames(Instance &aInstance); #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE TxFrame &mTxFrame802154; #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE TxFrame &mTxFrameTrel; #endif #if OPENTHREAD_CONFIG_MULTI_RADIO RadioTypes mSelectedRadioTypes; RadioTypes mRequiredRadioTypes; #endif }; /** * This class represents MAC radio links (multi radio). * */ class Links : public InstanceLocator { friend class ot::Instance; public: static const int8_t kInvalidRssiValue = SubMac::kInvalidRssiValue; ///< Invalid RSSI value. /** * This constructor initializes the `Links` object. * * @param[in] aInstance A reference to the OpenThread instance. * */ explicit Links(Instance &aInstance); /** * This method sets the PAN ID. * * @param[in] aPanId The PAN ID. * */ void SetPanId(PanId aPanId) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.SetPanId(aPanId); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTrel.SetPanId(aPanId); #endif } /** * This method gets the MAC Short Address. * * @returns The MAC Short Address. * */ ShortAddress GetShortAddress(void) const { return #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.GetShortAddress(); #else mShortAddress; #endif } /** * This method sets the MAC Short Address. * * @param[in] aShortAddress A MAC Short Address. * */ void SetShortAddress(ShortAddress aShortAddress) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.SetShortAddress(aShortAddress); #else mShortAddress = aShortAddress; #endif } /** * This method gets the MAC Extended Address. * * @returns The MAC Extended Address. * */ const ExtAddress &GetExtAddress(void) const { return #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.GetExtAddress(); #else mExtAddress; #endif } /** * This method sets the MAC Extended Address. * * @param[in] aExtAddress A MAC Extended Address. * */ void SetExtAddress(const ExtAddress &aExtAddress) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.SetExtAddress(aExtAddress); #else mExtAddress = aExtAddress; #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTrel.HandleExtAddressChange(); #endif } /** * This method registers a callback to provide received packet capture for IEEE 802.15.4 frames. * * @param[in] aPcapCallback A pointer to a function that is called when receiving an IEEE 802.15.4 link frame * or nullptr to disable the callback. * @param[in] aCallbackContext A pointer to application-specific context. * */ void SetPcapCallback(otLinkPcapCallback aPcapCallback, void *aCallbackContext) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.SetPcapCallback(aPcapCallback, aCallbackContext); #endif OT_UNUSED_VARIABLE(aPcapCallback); OT_UNUSED_VARIABLE(aCallbackContext); } /** * This method indicates whether radio should stay in Receive or Sleep during CSMA backoff. * * @param[in] aRxOnWhenBackoff TRUE to keep radio in Receive, FALSE to put to Sleep during CSMA backoff. * */ void SetRxOnWhenBackoff(bool aRxOnWhenBackoff) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.SetRxOnWhenBackoff(aRxOnWhenBackoff); #endif OT_UNUSED_VARIABLE(aRxOnWhenBackoff); } /** * This method enables all radio links. * */ void Enable(void) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE IgnoreError(mSubMac.Enable()); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTrel.Enable(); #endif } /** * This method disables all radio links. * */ void Disable(void) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE IgnoreError(mSubMac.Disable()); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTrel.Disable(); #endif } /** * This method transitions all radio links to Sleep. * */ void Sleep(void) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE IgnoreError(mSubMac.Sleep()); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTrel.Sleep(); #endif } #if OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE /** * This method transitions all radios link to CSL sample state. * * CSL sample state is only applicable and used for 15.4 radio link. Other link are transitioned to sleep state. * * @param[in] aPanChannel The current phy channel used by the device. This param will only take effect when CSL * channel hasn't been explicitly specified. */ void CslSample(uint8_t aPanChannel) { OT_UNUSED_VARIABLE(aPanChannel); #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE IgnoreError(mSubMac.CslSample(aPanChannel)); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTrel.Sleep(); #endif } #endif // OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE /** * This method transitions all radio links to Receive. * * @param[in] aChannel The channel to use for receiving. * */ void Receive(uint8_t aChannel) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE IgnoreError(mSubMac.Receive(aChannel)); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTrel.Receive(aChannel); #endif } /** * This method gets the radio transmit frames. * * @returns The transmit frames. * */ TxFrames &GetTxFrames(void) { return mTxFrames; } #if !OPENTHREAD_CONFIG_MULTI_RADIO /** * This method sends a prepared frame. * * The prepared frame is from `GetTxFrames()`. This method is available only in single radio link mode. * */ void Send(void) { #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE SuccessOrAssert(mSubMac.Send()); #endif #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE mTrel.Send(); #endif } #else // #if !OPENTHREAD_CONFIG_MULTI_RADIO /** * This method sends prepared frames over a given set of radio links. * * The prepared frame must be from `GetTxFrames()`. This method is available only in multi radio link mode. * * @param[in] aFrame A reference to a prepared frame. * @param[in] aRadioTypes A set of radio types to send on. * */ void Send(TxFrame &aFrame, RadioTypes aRadioTypes); #endif // !OPENTHREAD_CONFIG_MULTI_RADIO /** * This method gets the number of transmit retries for the last transmitted frame. * * @returns Number of transmit retries. * */ uint8_t GetTransmitRetries(void) const { return #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.GetTransmitRetries(); #else 0; #endif } /** * This method gets the most recent RSSI measurement from radio link. * * @returns The RSSI in dBm when it is valid. `kInvalidRssiValue` when RSSI is invalid. * */ int8_t GetRssi(void) const { return #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.GetRssi(); #else kInvalidRssiValue; #endif } /** * This method begins energy scan. * * @param[in] aScanChannel The channel to perform the energy scan on. * @param[in] aScanDuration The duration, in milliseconds, for the channel to be scanned. * * @retval kErrorNone Successfully started scanning the channel. * @retval kErrorInvalidState The radio was disabled or transmitting. * @retval kErrorNotImplemented Energy scan is not supported by radio link. * */ Error EnergyScan(uint8_t aScanChannel, uint16_t aScanDuration) { OT_UNUSED_VARIABLE(aScanChannel); OT_UNUSED_VARIABLE(aScanDuration); return #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.EnergyScan(aScanChannel, aScanDuration); #else kErrorNotImplemented; #endif } /** * This method returns the noise floor value (currently use the radio receive sensitivity value). * * @returns The noise floor value in dBm. * */ int8_t GetNoiseFloor(void) { return #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE mSubMac.GetNoiseFloor(); #else kDefaultNoiseFloor; #endif } /** * This methods gets a reference to the `SubMac` instance. * * @returns A reference to the `SubMac` instance. * */ SubMac &GetSubMac(void) { return mSubMac; } /** * This methods gets a reference to the `SubMac` instance. * * @returns A reference to the `SubMac` instance. * */ const SubMac &GetSubMac(void) const { return mSubMac; } /** * This method returns a reference to the current MAC key (for Key Mode 1) for a given Frame. * * @param[in] aFrame The frame for which to get the MAC key. * * @returns A reference to the current MAC key. * */ const KeyMaterial *GetCurrentMacKey(const Frame &aFrame) const; /** * This method returns a reference to the temporary MAC key (for Key Mode 1) for a given Frame based on a given * Key Sequence. * * @param[in] aFrame The frame for which to get the MAC key. * @param[in] aKeySequence The Key Sequence number (MUST be one off (+1 or -1) from current key sequence number). * * @returns A reference to the temporary MAC key. * */ const KeyMaterial *GetTemporaryMacKey(const Frame &aFrame, uint32_t aKeySequence) const; #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE /** * This method sets the current MAC frame counter value from the value from a `TxFrame`. * * @param[in] TxFrame The `TxFrame` from which to get the counter value. * * @retval kErrorNone If successful. * @retval kErrorInvalidState If the raw link-layer isn't enabled. * */ void SetMacFrameCounter(TxFrame &aFrame); #endif private: static constexpr int8_t kDefaultNoiseFloor = -100; SubMac mSubMac; #if OPENTHREAD_CONFIG_RADIO_LINK_TREL_ENABLE Trel::Link mTrel; #endif // `TxFrames` member definition should be after `mSubMac`, `mTrel` // definitions to allow it to use their methods from its // constructor. TxFrames mTxFrames; #if !OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE ShortAddress mShortAddress; ExtAddress mExtAddress; #endif }; /** * @} * */ } // namespace Mac } // namespace ot #endif // MAC_LINKS_HPP_
#include <catboost/libs/model/model_import_interface.h> #include <catboost/libs/model/model_build_helper.h> #include <catboost/private/libs/algo/learn_context.h> #include <catboost/private/libs/algo/split.h> #include <catboost/libs/helpers/progress_helper.h> namespace NCB{ class TCPUSnapshotModelLoader : public IModelLoader { public: TFullModel ReadModel(IInputStream *modelStream) const override { Y_UNUSED(modelStream); Y_UNREACHABLE(); } TFullModel ReadModel(const TString& snapshotPath) const override { CB_ENSURE(NFs::Exists(snapshotPath), "Model file doesn't exist: " << snapshotPath); TLearnProgress learnProgress; TProfileInfoData profileRestored; TProgressHelper(ToString(ETaskType::CPU)).CheckedLoad(snapshotPath, [&](TIFStream* in) { learnProgress.Load(in); ::Load(in, profileRestored); }); CB_ENSURE(learnProgress.CatFeatures.empty(), "Can't load model trained on dataset with categorical features from snapshot"); TObliviousTreeBuilder builder(learnProgress.FloatFeatures, learnProgress.CatFeatures, {}, {}, learnProgress.ApproxDimension); TVector<TModelSplit> modelSplits; for (ui32 treeId = 0; treeId < learnProgress.TreeStruct.size(); ++treeId) { // TODO(ilyzhin) implement it CB_ENSURE_INTERNAL( HoldsAlternative<TSplitTree>(learnProgress.TreeStruct[treeId]), "ReadModel is unimplemented for non-symmetric trees yet"); const TSplitTree& tree = Get<TSplitTree>(learnProgress.TreeStruct[treeId]); modelSplits.resize(tree.Splits.size()); auto iter = modelSplits.begin(); for (const TSplit& split : tree.Splits) { iter->FloatFeature.FloatFeature = split.FeatureIdx; iter->FloatFeature.Split = learnProgress.FloatFeatures[split.FeatureIdx].Borders[split.BinBorder]; ++iter; } builder.AddTree(modelSplits, learnProgress.LeafValues[treeId], learnProgress.TreeStats[treeId].LeafWeightsSum); } TFullModel model; builder.Build(model.ModelTrees.GetMutable()); model.SetScaleAndBias({1, learnProgress.StartingApprox.GetOrElse({})}); model.ModelInfo["params"] = learnProgress.SerializedTrainParams; return model; } }; TModelLoaderFactory::TRegistrator<TCPUSnapshotModelLoader> CPUSnapshotModelLoaderRegistator(EModelType::CPUSnapshot); }
/*********************************************************************************/ /********** THIS FILE IS GENERATED BY TOUCHGFX DESIGNER, DO NOT MODIFY ***********/ /*********************************************************************************/ #ifndef SIMCONSTANTS_HPP #define SIMCONSTANTS_HPP static unsigned short SIM_WIDTH = 320; static unsigned short SIM_HEIGHT = 240; #define SIM_TITLE "GUITestNoOS" #endif // SIMCONSTANTS_HPP
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #include <aws/quicksight/model/JoinInstruction.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace QuickSight { namespace Model { JoinInstruction::JoinInstruction() : m_leftOperandHasBeenSet(false), m_rightOperandHasBeenSet(false), m_type(JoinType::NOT_SET), m_typeHasBeenSet(false), m_onClauseHasBeenSet(false) { } JoinInstruction::JoinInstruction(JsonView jsonValue) : m_leftOperandHasBeenSet(false), m_rightOperandHasBeenSet(false), m_type(JoinType::NOT_SET), m_typeHasBeenSet(false), m_onClauseHasBeenSet(false) { *this = jsonValue; } JoinInstruction& JoinInstruction::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("LeftOperand")) { m_leftOperand = jsonValue.GetString("LeftOperand"); m_leftOperandHasBeenSet = true; } if(jsonValue.ValueExists("RightOperand")) { m_rightOperand = jsonValue.GetString("RightOperand"); m_rightOperandHasBeenSet = true; } if(jsonValue.ValueExists("Type")) { m_type = JoinTypeMapper::GetJoinTypeForName(jsonValue.GetString("Type")); m_typeHasBeenSet = true; } if(jsonValue.ValueExists("OnClause")) { m_onClause = jsonValue.GetString("OnClause"); m_onClauseHasBeenSet = true; } return *this; } JsonValue JoinInstruction::Jsonize() const { JsonValue payload; if(m_leftOperandHasBeenSet) { payload.WithString("LeftOperand", m_leftOperand); } if(m_rightOperandHasBeenSet) { payload.WithString("RightOperand", m_rightOperand); } if(m_typeHasBeenSet) { payload.WithString("Type", JoinTypeMapper::GetNameForJoinType(m_type)); } if(m_onClauseHasBeenSet) { payload.WithString("OnClause", m_onClause); } return payload; } } // namespace Model } // namespace QuickSight } // namespace Aws
//https://codeforces.com/group/Rv2Qzg0DgK/contest/286457/problem/H #include <bits/stdc++.h> using namespace std; #define F first #define S second typedef long long ll; typedef long double ld; ll mod = 1e9 + 7; int main () { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); int n, m, a, b; cin >> n >> m >> a >> b; cout << min ({n * a, ((n + m - 1) / m) * b, ((n % m) * a) + ((n - (n % m)) / m * b)}); }
#include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; }
/** * Copyright (C) 2016-2022 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located 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. */ #include "shim.h" #include "system_hwemu.h" #include "xclbin.h" #include "core/common/xclbin_parser.h" #include "core/common/AlignedAllocator.h" #include "xcl_perfmon_parameters.h" #include <fstream> #include <boost/property_tree/xml_parser.hpp> #include <unistd.h> #include <array> #include <cctype> #include <cerrno> #include <cstring> #include <mutex> #include <set> #include <vector> #include "plugin/xdp/device_offload.h" #define SEND_RESP2QDMA() \ { \ auto raw_response_header = std::make_unique<char[]>(ri_len); \ auto raw_response_payload = std::make_unique<char[]>(r_len);\ response_header->set_size(r_len);\ response_header->SerializeToArray((void*)raw_response_header.get(),ri_len);\ response_payload.SerializeToArray((void*)raw_response_payload.get(),r_len);\ Q2h_sock->sk_write((void*)raw_response_header.get(),ri_len);\ Q2h_sock->sk_write((void*)raw_response_payload.get(),r_len);\ } namespace { inline bool file_exists(const std::string& fnm) { struct stat statBuf; return stat(fnm.c_str(), &statBuf) == 0; } } namespace xclhwemhal2 { //Thread for which pooling for transaction from SIM_QDMA void hostMemAccessThread(xclhwemhal2::HwEmShim* inst); /** * helper class for transactions from SIM_QDMA to XRT * */ class Q2H_helper { private: std::unique_ptr<call_packet_info> header; std::unique_ptr<response_packet_info> response_header; size_t i_len; size_t ri_len; unix_socket* Q2h_sock; xclhwemhal2::HwEmShim* inst; public: Q2H_helper(xclhwemhal2::HwEmShim* _inst); ~Q2H_helper(); int poolingon_Qdma(); bool connect_sock(); }; namespace pt = boost::property_tree; namespace fs = boost::filesystem; std::map<unsigned int, HwEmShim*> devices; std::map<std::string, std::string> HwEmShim::mEnvironmentNameValueMap(xclemulation::getEnvironmentByReadingIni()); std::map<int, std::tuple<std::string,int,void*, unsigned int> > HwEmShim::mFdToFileNameMap; std::ofstream HwEmShim::mDebugLogStream; bool HwEmShim::mFirstBinary = true; unsigned int HwEmShim::mBufferCount = 0; const int xclhwemhal2::HwEmShim::SPIR_ADDRSPACE_PRIVATE = 0; const int xclhwemhal2::HwEmShim::SPIR_ADDRSPACE_GLOBAL = 1; const int xclhwemhal2::HwEmShim::SPIR_ADDRSPACE_CONSTANT = 2; const int xclhwemhal2::HwEmShim::SPIR_ADDRSPACE_LOCAL = 3; const int xclhwemhal2::HwEmShim::SPIR_ADDRSPACE_PIPES = 4; const unsigned HwEmShim::CONTROL_AP_START = 1; const unsigned HwEmShim::CONTROL_AP_DONE = 2; const unsigned HwEmShim::CONTROL_AP_IDLE = 4; const unsigned HwEmShim::CONTROL_AP_CONTINUE = 0x10; const unsigned HwEmShim::REG_BUFF_SIZE = 0x4; const unsigned HwEmShim::M2M_KERNEL_ARGS_SIZE = 36; void messagesThread(xclhwemhal2::HwEmShim* inst); // Maintain a list of all currently open device handles. // // xclClose removes a handle from the list. At static destruction // the list of still open handles is iterated and devices are // manually closed. This ensures xclClose is called for all opened // devices even when upper level code (OpenCL in particular) doesn't // close all acquired resources. // // The static handles must be descructed before other static data // members, so it is important device_handles::handles is defined // after above initializations. Order of static destruciton is in // reverse order of construction. // // Ideally all statics should be managed in the unnamed namespace of // this compilation unit and not be data members of the shim class. namespace device_handles { static std::mutex mutex; static std::set<xclDeviceHandle> handles; inline void add(xclDeviceHandle hdl) { std::lock_guard<std::mutex> lk(mutex); handles.insert(hdl); } inline void remove(xclDeviceHandle hdl) { std::lock_guard<std::mutex> lk(mutex); handles.erase(hdl); } struct X { ~X() { auto end = handles.end(); for (auto itr = handles.begin(); itr != end;) { xclClose(*itr); // removes handle from handles itr = handles.begin(); } } }; static X x; } Event::Event() { awlen = 0; arlen = 0 ; eventflags = 0; timestamp = 0; host_timestamp =0; readBytes = 0; writeBytes = 0; } size_t HwEmShim::alloc_void(size_t new_size) { if (buf_size == 0) { buf = malloc(new_size); return new_size; } if (buf_size < new_size) { void *temp = buf; buf = (void*) realloc(temp,new_size); if (!buf) // prevent leak of original buf free(temp); return new_size; } return buf_size; } static void saveWaveDataBases() { std::map<unsigned int, HwEmShim*>::iterator start = devices.begin(); std::map<unsigned int, HwEmShim*>::iterator end = devices.end(); for(; start != end; start++) { HwEmShim* handle = (*start).second; if(!handle) continue; handle->saveWaveDataBase(); if (xclemulation::config::getInstance()->isKeepRunDirEnabled() == false) { systemUtil::makeSystemCall(handle->deviceDirectory, systemUtil::systemOperation::REMOVE, "", std::to_string(__LINE__)); } } } std::string HwEmShim::loadFileContentsToString(const std::string& path) { std::ifstream file(path); return {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()}; } int HwEmShim::parseLog() { std::vector<std::string> myvector = {"SIM-IPC's external process can be connected to instance", "SystemC TLM functional mode", "HLS_PRINT", "Exiting xsim", "FATAL_ERROR"}; std::ifstream ifs(getSimPath() + "/simulate.log"); if (ifs.is_open()) { std::string line; while (std::getline(ifs, line)) { for (auto matchString : myvector) { std::string::size_type index = line.find(matchString); if (index != std::string::npos) { if(std::find(parsedMsgs.begin(), parsedMsgs.end(), line) == parsedMsgs.end()) { logMessage(line); parsedMsgs.push_back(line); if (!matchString.compare("Exiting xsim") || !matchString.compare("FATAL_ERROR")) std::cout << "SIMULATION EXITED" << std::endl; } } } } } return 0; } void HwEmShim::parseString(const std::string& simPath , const std::string& searchString) { std::ifstream ifs(simPath + "/simulate.log"); std::string lineHandle; while(getline(ifs, lineHandle)) { if(lineHandle.find(searchString, 0) != std::string::npos) logMessage(lineHandle); } } void HwEmShim::parseSimulateLog () { std::string simPath = getSimPath(); std::string content = loadFileContentsToString(simPath + "/simulate.log"); if (content.find("// ERROR!!! DEADLOCK DETECTED ") != std::string::npos) { size_t first = content.find("// ERROR!!! DEADLOCK DETECTED"); size_t last = content.find("detected!", first); // substr including the word detected! std::string deadlockMsg = content.substr(first , last + 9 - first); logMessage(deadlockMsg); } } static void sigHandler(int sn, siginfo_t *si, void *sc) { switch(sn) { case SIGSEGV: { saveWaveDataBases(); kill(0,SIGSEGV); exit(1); break; } case SIGFPE : { saveWaveDataBases(); kill(0,SIGTERM); exit(1); break; } case SIGABRT: { saveWaveDataBases(); kill(0,SIGABRT); exit(1); break; } default: { break; } } } static void printMem(std::ofstream &os, int base, uint64_t offset, void* buf, unsigned int size ) { std::ios_base::fmtflags f( os.flags() ); if(os.is_open()) { for(uint64_t i = 0; i < size ; i = i + base) { os << "@" << std::hex << offset + i <<std::endl; for(int j = base-1 ;j >=0 ; j--) os << std::hex << std::setfill('0') << std::setw(2) << (unsigned int)(((unsigned char*)buf)[i+j]); os << std::endl; } } os.flags( f ); } bool HwEmShim::isUltraScale() const { return false; } int HwEmShim::xclLoadXclBin(const xclBin *header) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } char *bitstreambin = reinterpret_cast<char*> (const_cast<xclBin*> (header)); //int result = 0; Not used. Removed to get rid of compiler warning, and probably a Coverity CID. ssize_t zipFileSize = 0; ssize_t xmlFileSize = 0; ssize_t debugFileSize = 0; ssize_t memTopologySize = 0; ssize_t pdiSize = 0; ssize_t emuDataSize = 0; std::unique_ptr<char[]> zipFile; std::unique_ptr<char[]> xmlFile; std::unique_ptr<char[]> debugFile; std::unique_ptr<char[]> memTopology; std::unique_ptr<char[]> pdi; std::unique_ptr<char[]> emuData; if (std::memcmp(bitstreambin, "xclbin2", 7)) { PRINTENDFUNC; return -1; } //check xclbin version with vivado tool version xclemulation::checkXclibinVersionWithTool(header); auto top = reinterpret_cast<const axlf*>(header); if (auto sec = xclbin::get_axlf_section(top, EMBEDDED_METADATA)) { xmlFileSize = sec->m_sectionSize; xmlFile = std::make_unique<char[]>(xmlFileSize); memcpy(xmlFile.get(), bitstreambin + sec->m_sectionOffset, xmlFileSize); } if (auto sec = xclbin::get_axlf_section(top, BITSTREAM)) { zipFileSize = sec->m_sectionSize; zipFile = std::make_unique<char[]>(zipFileSize); memcpy(zipFile.get(), bitstreambin + sec->m_sectionOffset, zipFileSize); } if (auto sec = xclbin::get_axlf_section(top, DEBUG_IP_LAYOUT)) { debugFileSize = sec->m_sectionSize; debugFile = std::make_unique<char[]>(debugFileSize); memcpy(debugFile.get(), bitstreambin + sec->m_sectionOffset, debugFileSize); } if (auto sec = xrt_core::xclbin::get_axlf_section(top, ASK_GROUP_TOPOLOGY)) { memTopologySize = sec->m_sectionSize; memTopology = std::make_unique<char[]>(memTopologySize); memcpy(memTopology.get(), bitstreambin + sec->m_sectionOffset, memTopologySize); } if (auto sec = xclbin::get_axlf_section(top, PDI)) { pdiSize = sec->m_sectionSize; pdi = std::make_unique<char[]>(pdiSize); memcpy(pdi.get(), bitstreambin + sec->m_sectionOffset, pdiSize); } if (auto sec = xclbin::get_axlf_section(top, EMULATION_DATA)) { emuDataSize = sec->m_sectionSize; emuData = std::make_unique<char[]>(emuDataSize); memcpy(emuData.get(), bitstreambin + sec->m_sectionOffset, emuDataSize); } bitStreamArg loadBitStreamArgs; loadBitStreamArgs.m_zipFile = zipFile.get(); loadBitStreamArgs.m_zipFileSize = zipFileSize; loadBitStreamArgs.m_xmlfile = xmlFile.get(); loadBitStreamArgs.m_xmlFileSize = xmlFileSize; loadBitStreamArgs.m_debugFile = debugFile.get(); loadBitStreamArgs.m_debugFileSize = debugFileSize; loadBitStreamArgs.m_memTopology = memTopology.get(); loadBitStreamArgs.m_memTopologySize = memTopologySize; loadBitStreamArgs.m_pdi = pdi.get(); loadBitStreamArgs.m_pdiSize = pdiSize; loadBitStreamArgs.m_emuData = emuData.get(); loadBitStreamArgs.m_emuDataSize = emuDataSize; loadBitStreamArgs.m_top = top; int returnValue = xclLoadBitstreamWorker(loadBitStreamArgs); //mFirstBinary is a static member variable which becomes false once first binary gets loaded if(returnValue >=0 && mFirstBinary ) { HwEmShim::mDebugLogStream.open(xclemulation::getEmDebugLogFile(),std::ofstream::out); if(xclemulation::config::getInstance()->isInfoSuppressed() == false) { std::string initMsg ="INFO: [HW-EMU 01] Hardware emulation runs simulation underneath. Using a large data set will result in long simulation times. It is recommended that a small dataset is used for faster execution. The flow uses approximate models for Global memories and interconnect and hence the performance data generated is approximate."; logMessage(initMsg); } mFirstBinary = false; } if(xclemulation::config::getInstance()->isNewMbscheduler()) { m_scheduler = new hwemu::xocl_scheduler(this); } else if (xclemulation::config::getInstance()->isXgqMode()) { m_xgq = new hwemu::xocl_xgq(this); if (m_xgq && pdi && pdiSize > 0) { returnValue = m_xgq->load_xclbin(pdi.get(), pdiSize); } } else { mCore = new exec_core; mMBSch = new MBScheduler(this); mMBSch->init_scheduler_thread(); } PRINTENDFUNC; return returnValue; } int HwEmShim::xclLoadBitstreamWorker(bitStreamArg args) { bool is_enable_debug = xrt_core::config::get_is_enable_debug(); std::string aie_sim_options = xrt_core::config::get_aie_sim_options(); if (mLogStream.is_open()) { // mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << args.m_zipFile << std::endl; } mCuIndx = 0; //TBD the file read may slowdown things...whenever xclLoadBitStream hal API implementation changes, we also need to make changes. boost::format fmt = boost::format("%1%/tempFile_%2%.zip") % deviceDirectory.c_str() % std::to_string(binaryCounter); std::string zip_fileName = fmt.str(); if (mMemModel) { delete mMemModel; mMemModel = NULL; } if (sock) { resetProgram(); } //CR-1116870 changes. Clearing "mOffsetInstanceStreamMap" for each kernel in case of multiple kernels with different xclbin's //required for sys_opt/kernel_swap example mOffsetInstanceStreamMap.clear(); std::stringstream ss; ss << deviceDirectory << "/binary_" << binaryCounter; std::string binaryDirectory = ss.str(); systemUtil::makeSystemCall(binaryDirectory, systemUtil::systemOperation::CREATE, "", std::to_string(__LINE__)); systemUtil::makeSystemCall(binaryDirectory, systemUtil::systemOperation::PERMISSIONS, "777", std::to_string(__LINE__)); mRunDeviceBinDir = binaryDirectory; std::ofstream os(zip_fileName); os.write(args.m_zipFile, args.m_zipFileSize); os.close(); struct sigaction s; memset(&s, 0, sizeof(s)); s.sa_flags = SA_SIGINFO; s.sa_sigaction = sigHandler; if (sigaction(SIGSEGV, &s, (struct sigaction *)0) || sigaction(SIGFPE, &s, (struct sigaction *)0) || sigaction(SIGABRT, &s, (struct sigaction *)0)) { //debug_print("unable to support all signals"); } std::string sim_file("launch_hw_emu.sh"); // Write and read debug IP layout (for debug & profiling) // NOTE: for now, let's do this file based so we can debug std::string debugFileName = mRunDeviceBinDir + "/debug_ip_layout"; FILE *fp2 = fopen(debugFileName.c_str(), "wb"); if (fp2 == NULL) { if (mLogStream.is_open()) mLogStream << __func__ << " failed to create temporary debug_ip_layout file " << std::endl; return -1; } if ((args.m_debugFile != nullptr) && (args.m_debugFileSize > 1)) fwrite(args.m_debugFile, args.m_debugFileSize, 1, fp2); fflush(fp2); fclose(fp2); std::string pdiFileName = binaryDirectory + "/aie_pdi"; if ((args.m_pdi != nullptr) && (args.m_pdiSize > 1)) { FILE *fp2 = fopen(pdiFileName.c_str(), "wb"); if (fp2 == NULL) { if (mLogStream.is_open()) mLogStream << __func__ << " failed to create temporary aie_pdi file " << std::endl; return -1; } fwrite(args.m_pdi, args.m_pdiSize, 1, fp2); fflush(fp2); fclose(fp2); } readDebugIpLayout(debugFileName); const mem_topology* m_mem = (reinterpret_cast<const ::mem_topology*>(args.m_memTopology)); if (m_mem) { mMembanks.clear(); for (int32_t i = 0; i<m_mem->m_count; ++i) { if (m_mem->m_mem_data[i].m_type == MEM_TYPE::MEM_STREAMING) continue; std::string tag = reinterpret_cast<const char*>(m_mem->m_mem_data[i].m_tag); mMembanks.emplace_back(membank{ m_mem->m_mem_data[i].m_base_address, tag, m_mem->m_mem_data[i].m_size * 1024, i }); } if (m_mem->m_count > 0) { mDDRMemoryManager.clear(); } if (mLogStream.is_open()) mLogStream << __func__ << " Creating the DDRMemoryManager Object with RTD section info" << std::endl; for (auto it : mMembanks) { //CR 966701: alignment to 4k (instead of mDeviceInfo.mDataAlignment) mDDRMemoryManager.push_back(new xclemulation::MemoryManager(it.size, it.base_addr, getpagesize(), it.tag)); std::size_t found = it.tag.find("HOST"); if (found != std::string::npos) { host_sptag_idx = it.index; } } for (auto it : mDDRMemoryManager) { std::string tag = it->tag(); //continue if not MBG group if (tag.find("MBG") == std::string::npos) { continue; } // Connectivity provided with the bus direction for HBM[31:0], XCLBIN creates the large group of memory with all the HBM[31:0] size // like MBG. It indicates allocation of sequential memory is possible and not to limited size of one HBM. Hence creating the // HBM child memories (HBM subsets listed in RTD which falls under the range of MBG) for MBG memory type for (auto it2 : mDDRMemoryManager) { if (it2->size() != 0 && it2 != it && it->start() <= it2->start() && (it->start() + it->size()) >= (it2->start() + it2->size())) { //add HBM child memories to MBG large group[ it->mChildMemories.push_back(it2); } } } } //CR-1116870 Changes Start auto projectName = xrt_core::xclbin::get_project_name(args.m_top); xrt::xclbin xclbin_object{args.m_top}; auto fpgaDeviceName = xclbin_object.get_fpga_device_name(); //New DRC check for Versal Platforms if (!fpgaDeviceName.empty() && fpgaDeviceName.find("versal:") != std::string::npos) { mVersalPlatform=true; if ((args.m_emuData == nullptr) && (args.m_emuDataSize <= 0)) { std::string dMsg = "ERROR: [HW-EMU 09] EMULATION_DATA section is missing in XCLBIN. This is a mandatory section required for Versal platforms. Please ensure the design is built with 'v++ -package' step, which inserts EMULATION_DATA into the XCLBIN."; logMessage(dMsg, 0); return -1; } } if (xclemulation::config::getInstance()->isSharedFmodel() && !mVersalPlatform) { setenv("SDX_USE_SHARED_MEMORY","true",true); } std::string instance_name = ""; //CR-1122692:'auto' is treated as 32 bit int.But 'uint64_t' is needed uint64_t base_address = 0; for (const auto& kernel : xclbin_object.get_kernels()) { // get properties of each kernel object auto props = xrt_core::xclbin_int::get_properties(kernel); //get CU's of each kernel object //iterate over CU's to get arguments for (const auto& cu : kernel.get_cus()) { base_address = cu.get_base_address(); //CR-1122692: Adding checks to validate base_address and adding 'mVersalPlatform' check if (base_address != (uint64_t)-1 && mVersalPlatform) { mCuBaseAddress = base_address & 0xFFFFFFFF00000000; //BAD Worharound for vck5000 need to remove once SIM_QDMA supports PCIE bar if(xclemulation::config::getInstance()->getCuBaseAddrForce()!=-1) { mCuBaseAddress = xclemulation::config::getInstance()->getCuBaseAddrForce(); } else if(mVersalPlatform) { mCuBaseAddress = 0x20200000000; } } //fetch instance name instance_name = cu.get_name(); if (xclemulation::config::getInstance()->isMemLogsEnabled()) { //trim instance_name to get actual instance name auto position = instance_name.find(":"); auto trimmed_instance_name = instance_name.substr(position+1); mOffsetInstanceStreamMap.emplace(std::make_pair(base_address,new std::ofstream(trimmed_instance_name + "_control.mem"))); } if (props.address_range != 0 && !props.name.empty() && !instance_name.empty()) { mCURangeMap[instance_name] = props.address_range; } } } std::string xclBinName = projectName; //CR-1116870 Changes End set_simulator_started(true); //Thread to fetch messages from Device to display on host if(mMessengerThreadStarted == false) { mMessengerThread = std::thread(xclhwemhal2::messagesThread,this); mMessengerThreadStarted = true; } if (mLogStream.is_open()) mLogStream << __func__ << " mMessengerThreadStarted " << std::endl; bool simDontRun = xclemulation::config::getInstance()->isDontRun(); std::string launcherArgs = xclemulation::config::getInstance()->getLauncherArgs(); std::string wdbFileName(""); std::string kernelProfileFileName("profile_kernels.csv"); std::string kernelTraceFileName("timeline_kernels.csv"); // The following is evil--hardcoding. This name may change. // Is there a way we can determine the name from the directories or otherwise? std::string bdName("dr"); // Used to be opencldesign. This is new default. unsetenv("VITIS_WAVEFORM_WDB_FILENAME"); unsetenv("VITIS_KERNEL_PROFILE_FILENAME"); unsetenv("VITIS_KERNEL_TRACE_FILENAME"); if (args.m_emuData) { extractEmuData(binaryDirectory, binaryCounter, args); std::string emuSettingsFilePath = binaryDirectory + "/emulation_data/emu_meta_data.json"; readEmuSettingsJsonFile(emuSettingsFilePath); } //xrt.ini setting (dont_run=true) is getting the high priority if (simDontRun) { mSimDontRun = simDontRun; } if (!mSimDontRun) { wdbFileName = std::string(mDeviceInfo.mName) + "-" + std::to_string(mDeviceIndex) + "-" + xclBinName; xclemulation::debug_mode lWaveform = xclemulation::config::getInstance()->getLaunchWaveform(); if (lWaveform == xclemulation::debug_mode::gdb) { std::string dMsg = "ERROR: [HW-EMU 21] debug_mode option 'gdb' is no more valid. Valid options for debug_mode are 'gui', 'batch' and 'off'. Please make sure you build the application with 'wdb' mode"; logMessage(dMsg, 0); return -1; } std::string userSpecifiedSimPath = xclemulation::config::getInstance()->getSimDir(); if (userSpecifiedSimPath.empty()) { if (mLogStream.is_open()) mLogStream << __func__ << " UNZIP of sim bin started" << std::endl; systemUtil::makeSystemCall(zip_fileName, systemUtil::systemOperation::UNZIP, binaryDirectory, std::to_string(__LINE__)); if (mLogStream.is_open()) mLogStream << __func__ << " UNZIP of sim bin complete" << std::endl; systemUtil::makeSystemCall(binaryDirectory, systemUtil::systemOperation::PERMISSIONS, "777", std::to_string(__LINE__)); if (mLogStream.is_open()) mLogStream << __func__ << " Permissions operation is complete" << std::endl; simulatorType = getSimulatorType(binaryDirectory); std::transform(simulatorType.begin(), simulatorType.end(), simulatorType.begin(), [](unsigned char c){return std::tolower(c);}); } if (lWaveform == xclemulation::debug_mode::gui) { // NOTE: proto inst filename must match name in HPIKernelCompilerHwEmu.cpp std::string protoFileName = "./" + bdName + "_behav.protoinst"; std::stringstream cmdLineOption; std::string waveformDebugfilePath = ""; sim_path = binaryDirectory + "/behav_waveform/" + simulatorType; setSimPath(sim_path); if (boost::filesystem::exists(sim_path) != false) { waveformDebugfilePath = sim_path + "/waveform_debug_enable.txt"; if (simulatorType == "xsim") { cmdLineOption << " -g --wdb " << wdbFileName << ".wdb" << " --protoinst " << protoFileName; launcherArgs = launcherArgs + cmdLineOption.str(); } else { cmdLineOption << " gui "; launcherArgs = launcherArgs + cmdLineOption.str(); } } std::string generatedWcfgFileName = sim_path + "/" + bdName + "_behav.wcfg"; unsetenv("VITIS_LAUNCH_WAVEFORM_BATCH"); if (waveformDebugfilePath != "" && boost::filesystem::exists(waveformDebugfilePath) != false) { setenv("VITIS_WAVEFORM", generatedWcfgFileName.c_str(), true); setenv("VITIS_WAVEFORM_WDB_FILENAME", std::string(wdbFileName + ".wdb").c_str(), true); } else { std::string dMsg = "WARNING: [HW-EMU 08-1] None of the Kernels compiled in the waveform enabled mode to get the WDB file. Do run V++ link with the -g option"; logMessage(dMsg, 0); } setenv("VITIS_KERNEL_PROFILE_FILENAME", kernelProfileFileName.c_str(), true); setenv("VITIS_KERNEL_TRACE_FILENAME", kernelTraceFileName.c_str(), true); } if (lWaveform == xclemulation::debug_mode::batch) { // NOTE: proto inst filename must match name in HPIKernelCompilerHwEmu.cpp std::string protoFileName = "./" + bdName + "_behav.protoinst"; std::stringstream cmdLineOption; cmdLineOption << " --wdb " << wdbFileName << ".wdb" << " --protoinst " << protoFileName; launcherArgs = launcherArgs + cmdLineOption.str(); sim_path = binaryDirectory + "/behav_waveform/" + simulatorType; setSimPath(sim_path); std::string waveformDebugfilePath = sim_path + "/waveform_debug_enable.txt"; std::string generatedWcfgFileName = sim_path + "/" + bdName + "_behav.wcfg"; setenv("VITIS_LAUNCH_WAVEFORM_BATCH", "1", true); if (boost::filesystem::exists(waveformDebugfilePath) != false) { setenv("VITIS_WAVEFORM", generatedWcfgFileName.c_str(), true); setenv("VITIS_WAVEFORM_WDB_FILENAME", std::string(wdbFileName + ".wdb").c_str(), true); } else { std::string dMsg = "WARNING: [HW-EMU 08-2] None of the Kernels compiled in the waveform enabled mode to get the WDB file. Do run v++ link with the -g option"; logMessage(dMsg, 0); } setenv("VITIS_KERNEL_PROFILE_FILENAME", kernelProfileFileName.c_str(), true); setenv("VITIS_KERNEL_TRACE_FILENAME", kernelTraceFileName.c_str(), true); } if (lWaveform == xclemulation::debug_mode::off) { // NOTE: proto inst filename must match name in HPIKernelCompilerHwEmu.cpp std::string protoFileName = "./" + bdName + "_behav.protoinst"; std::stringstream cmdLineOption; cmdLineOption << " --wdb " << wdbFileName << ".wdb" << " --protoinst " << protoFileName; launcherArgs = launcherArgs + cmdLineOption.str(); sim_path = binaryDirectory + "/behav_waveform/" + simulatorType; setSimPath(sim_path); setenv("VITIS_LAUNCH_WAVEFORM_BATCH", "1", true); } /*if (lWaveform == xclemulation::debug_mode::gdb) { sim_path = binaryDirectory + "/behav_gdb/" + simulatorType; setSimPath(sim_path); }*/ if (userSpecifiedSimPath.empty() == false) { sim_path = userSpecifiedSimPath; setSimPath(sim_path); systemUtil::makeSystemCall(sim_path, systemUtil::systemOperation::PERMISSIONS, "777", std::to_string(__LINE__)); } else { if (sim_path.empty()) { sim_path = binaryDirectory + "/behav_waveform/" + simulatorType; setSimPath(sim_path); } // As gdb feature is unsupported for 2021.1, we removed this cross check. We will re-enable it once we have 2 possibilities /*if (boost::filesystem::exists(sim_path) == false) { if (lWaveform == xclemulation::debug_mode::gdb) { sim_path = binaryDirectory + "/behav_waveform/" + simulatorType; setSimPath(sim_path); std::string waveformDebugfilePath = sim_path + "/waveform_debug_enable.txt"; std::string dMsg = "WARNING: [HW-EMU 07] debug_mode is set to 'gdb' in INI file and none of kernels compiled in 'gdb' mode. Running simulation using waveform mode. Do run v++ link with -g and --xp param:hw_emu.debugMode=gdb options to launch simulation in 'gdb' mode"; logMessage(dMsg, 0); std::string protoFileName = "./" + bdName + "_behav.protoinst"; std::stringstream cmdLineOption; cmdLineOption << " --wdb " << wdbFileName << ".wdb" << " --protoinst " << protoFileName; launcherArgs = launcherArgs + cmdLineOption.str(); std::string generatedWcfgFileName = sim_path + "/" + bdName + "_behav.wcfg"; setenv("VITIS_LAUNCH_WAVEFORM_BATCH", "1", true); if (boost::filesystem::exists(waveformDebugfilePath) != false) { setenv("VITIS_WAVEFORM", generatedWcfgFileName.c_str(), true); setenv("VITIS_WAVEFORM_WDB_FILENAME", std::string(wdbFileName + ".wdb").c_str(), true); } // Commented to set these when debug_mode is set to gdb //setenv("VITIS_KERNEL_PROFILE_FILENAME", kernelProfileFileName.c_str(), true); //setenv("VITIS_KERNEL_TRACE_FILENAME", kernelTraceFileName.c_str(), true); } else { std::string dMsg; sim_path = binaryDirectory + "/behav_gdb/" + simulatorType; setSimPath(sim_path); if (lWaveform == xclemulation::debug_mode::gui) dMsg = "WARNING: [HW-EMU 07] debug_mode is set to 'gui' in ini file. Cannot enable simulator gui in this mode. Using " + sim_path + " as simulation directory."; else if (lWaveform == xclemulation::debug_mode::batch) dMsg = "WARNING: [HW-EMU 07] debug_mode is set to 'batch' in ini file. Using " + sim_path + " as simulation directory."; else dMsg = "WARNING: [HW-EMU 07] debug_mode is set to 'off' in ini file (or) considered by default. Using " + sim_path + " as simulation directory."; logMessage(dMsg, 0); } }*/ } if (mLogStream.is_open()) mLogStream << __func__ << " Preparing the launcher args and construction of proper simpath is complete sim_path: " << sim_path << std::endl; std::stringstream socket_id; socket_id << deviceName << "_" << binaryCounter << "_"; #ifndef _WINDOWS // TODO: Windows build support // getpid is defined in unistd.h // setenv is defined in stdlib.h socket_id << getpid(); setenv("EMULATION_SOCKETID", socket_id.str().c_str(), true); #endif if (mLogStream.is_open()) mLogStream << __func__ << " socket_id: " << socket_id.str().c_str() << " binaryCounter: " << binaryCounter << std::endl; binaryCounter++; } if(mHostMemAccessThreadStarted == false) { mHostMemAccessThread = std::thread(xclhwemhal2::hostMemAccessThread,this); } if (deviceDirectory.empty() == false) setenv("EMULATION_RUN_DIR", deviceDirectory.c_str(), true); // Create waveform config file // NOTE: see corresponding wdb file in saveWaveDataBase if (wdbFileName.empty() == false) { setenv("SDX_QUESTA_WLF_FILENAME", std::string(wdbFileName + ".wlf").c_str(), true); mBinaryDirectories[sim_path] = wdbFileName; } //launch simulation if (boost::filesystem::exists(sim_path) == true) { #ifndef _WINDOWS // TODO: Windows build support // pid_t, fork, chdir, execl is defined in unistd.h // this environment variable is added to disable the systemc copyright message setenv("SYSTEMC_DISABLE_COPYRIGHT_MESSAGE", "1", true); pid_t pid = fork(); assert(pid >= 0); if (mLogStream.is_open()) mLogStream << __func__ << " Child process created to launch the simulation process " << std::endl; if (pid == 0) { //I am child //Redirecting the XSIM log to a file FILE* nP = freopen("/dev/null", "w", stdout); if (!nP) { std::cerr << "FATAR ERROR : Unable to redirect simulation output " << std::endl; exit(1); } int rV = chdir(sim_path.c_str()); if (rV == -1){ std::cerr << "FATAL ERROR : Unable to go to simulation directory " << std::endl; exit(1); } // If the sdx server port was specified in the .ini file, // we need to pass this information to the spawned xsim process. if (xclemulation::config::getInstance()->getServerPort() != 0) { std::stringstream convert; convert << xclemulation::config::getInstance()->getServerPort(); setenv("XILINX_SDX_SERVER_PORT", convert.str().c_str(), 1); } if (mLogStream.is_open() && launcherArgs.empty() == false) mLogStream << __func__ << " xocc command line: " << launcherArgs << std::endl; const char* simMode = NULL; std::string userSpecifiedPreSimScript = xclemulation::config::getInstance()->getUserPreSimScript(); std::string userSpecifiedPostSimScript = xclemulation::config::getInstance()->getUserPostSimScript(); std::string wcfgFilePath = xclemulation::config::getInstance()->getWcfgFilePath(); if (userSpecifiedPreSimScript != "" && wcfgFilePath != "") { std::cout << "WARNING: [HW-EMU] Both user_pre_sim_script and wcfg_file_path are provided. Either one of the option is accepted. Giving predence for wcfg_file_path." << std::endl; } std::string pre_sim_script; if (wcfgFilePath != "") { createPreSimScript(wcfgFilePath, pre_sim_script); } if (args.m_emuData) { extractEmuData(sim_path, binaryCounter, args); //Assuming that we will have only one AIE Kernel, need to //update this logic when we have suport for multiple AIE Kernels if (fs::exists(sim_path + "/emulation_data/libsdf/cfg/aie.sim.config.txt")) { launcherArgs += " -emuData " + sim_path + "/emulation_data/libsdf/cfg/aie.sim.config.txt"; launcherArgs += " -aie-sim-config " + sim_path + "/emulation_data/libsdf/cfg/aie.sim.config.txt"; } else if (fs::exists(sim_path + "/emulation_data/libadf/cfg/aie.sim.config.txt")) { launcherArgs += " -emuData " + sim_path + "/emulation_data/libadf/cfg/aie.sim.config.txt"; launcherArgs += " -aie-sim-config " + sim_path + "/emulation_data/libadf/cfg/aie.sim.config.txt"; } else { launcherArgs += " -emuData " + sim_path + "/emulation_data/cfg/aie.sim.config.txt"; launcherArgs += " -aie-sim-config " + sim_path + "/emulation_data/cfg/aie.sim.config.txt"; } if (fs::exists(sim_path + "/emulation_data/BOOT_bh.bin")) { launcherArgs += " -boot-bh " + sim_path + "/emulation_data/BOOT_bh.bin"; } if (fs::exists(sim_path + "/emulation_data/qemu_ospi.bin")) { launcherArgs += " -ospi-image " + sim_path + "/emulation_data/qemu_ospi.bin"; } if (fs::exists(sim_path + "/emulation_data/qemu_qspi_low.bin")) { launcherArgs += " -qspi-low-image " + sim_path + "/emulation_data/qemu_qspi_low.bin"; } if (fs::exists(sim_path + "/emulation_data/qemu_qspi_high.bin")) { launcherArgs += " -qspi-high-image " + sim_path + "/emulation_data/qemu_qspi_high.bin"; } if (fs::exists(sim_path + "/emulation_data/qemu_args.txt")) { launcherArgs += " -qemu-args-file " + sim_path + "/emulation_data/qemu_args.txt"; } if (fs::exists(sim_path + "/emulation_data/pmc_args.txt")) { launcherArgs += " -pmc-args-file " + sim_path + "/emulation_data/pmc_args.txt"; } else if (fs::exists(sim_path + "/emulation_data/pmu_args.txt")) { launcherArgs += " -pmc-args-file " + sim_path + "/emulation_data/pmu_args.txt"; } else { std::cout << "ERROR: [HW-EMU] Unable to find either PMU/PMC args which are required to launch the emulation." << std::endl; } if (is_enable_debug) { launcherArgs += " -enable-debug "; } if (aie_sim_options != "") { launcherArgs += " -aie-sim-options " + aie_sim_options; } if (wcfgFilePath != "") { launcherArgs += " -user-pre-sim-script " + pre_sim_script; } else { if (userSpecifiedPreSimScript != "") { launcherArgs += " -user-pre-sim-script " + userSpecifiedPreSimScript; } } if (userSpecifiedPostSimScript != "") { launcherArgs += " -user-post-sim-script " + userSpecifiedPostSimScript; } } else { if (pre_sim_script != "" && wcfgFilePath != "") { setenv("USER_PRE_SIM_SCRIPT", pre_sim_script.c_str(), true); } } if (!launcherArgs.empty()) simMode = launcherArgs.c_str(); if (!file_exists(sim_file)) sim_file = "simulate.sh"; int r = execl(sim_file.c_str(), sim_file.c_str(), simMode, NULL); fclose(stdout); if (r == -1){ std::cerr << "FATAL ERROR : Simulation process did not launch" << std::endl; exit(1); } exit(0); } #endif } if (mLogStream.is_open()) mLogStream << __func__ << " Child process launched... " << std::endl; //if platform is a XPR platform, dont serilize ddr memory if (isXPR()) { mEnvironmentNameValueMap["enable_pr"] = "false"; } sock = new unix_socket; if (mLogStream.is_open()) mLogStream << __func__ << " Created the Unix socket." << std::endl; if (sock && mEnvironmentNameValueMap.empty() == false) { //send environment information to device bool ack = true; if (mLogStream.is_open()) mLogStream << __func__ << " Before RPC call xclSetEnvironment_RPC_CALL." << std::endl; xclSetEnvironment_RPC_CALL(xclSetEnvironment); if (!ack) { if (mLogStream.is_open()) mLogStream << __func__ << "Environment is NOT set properly" << std::endl; //std::cout<<"environment is not set properly"<<std::endl; } if (mLogStream.is_open()) mLogStream << __func__ << "Environment is set properly" << std::endl; } return 0; } bool HwEmShim::readEmuSettingsJsonFile(const std::string& emuSettingsFilePath) { if (emuSettingsFilePath.empty() || !boost::filesystem::exists(emuSettingsFilePath)) { return false; } try { std::ifstream emuSettingsFile(emuSettingsFilePath.c_str()); if (!emuSettingsFile.good()) { return false; } namespace pt = boost::property_tree; pt::ptree iroot; pt::read_json(emuSettingsFilePath, iroot); for (pt::ptree::value_type &iter : iroot.get_child("settings")) { std::string settingName = iter.first; std::string settingValue = iter.second.get_value<std::string>(); if (settingName == "defer_device_process") { mSimDontRun = (settingValue == "true") ? true : false; } } } catch (const boost::property_tree::ptree_error &e) { std::cerr << "property_tree error = " << e.what() << std::endl; return false; } catch (std::exception const& e) { std::cerr << "exception = " << e.what() << std::endl; return false; } return true; } void HwEmShim::createPreSimScript(const std::string& wcfgFilePath, std::string& preSimScriptPath) { char path[FILENAME_MAX]; size_t size = MAXPATHLEN; char* pPath = GetCurrentDir(path, size); preSimScriptPath = std::string(pPath) + "/pre_sim_script.tcl"; std::ofstream pssStrem; pssStrem.open(preSimScriptPath); pssStrem << "open_wave_config " << wcfgFilePath << std::endl; pssStrem.close(); } void HwEmShim::extractEmuData(const std::string& simPath, int binaryCounter, bitStreamArg args) { std::unique_ptr<char[]> emuDataFileName(new char[1024]); #ifndef _WINDOWS // TODO: Windows build support // getpid is defined in unistd.h std::sprintf(emuDataFileName.get(), "%s/emuDataFile_%d", mRunDeviceBinDir.c_str(), binaryCounter); #endif if ((args.m_emuData != nullptr) && (args.m_emuDataSize > 1)) { std::ofstream os(emuDataFileName.get()); os.write(args.m_emuData, args.m_emuDataSize); os.close(); std::string emuDataFilePath(emuDataFileName.get()); systemUtil::makeSystemCall(emuDataFilePath, systemUtil::systemOperation::UNZIP, simPath, std::to_string(__LINE__)); systemUtil::makeSystemCall(mRunDeviceBinDir, systemUtil::systemOperation::PERMISSIONS, "777", std::to_string(__LINE__)); } } size_t HwEmShim::xclWrite(xclAddressSpace space, uint64_t offset, const void *hostBuf, size_t size) { if (!simulator_started) return 0; if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << space << ", " << offset << ", " << hostBuf << ", " << size << std::endl; } offset = offset | mCuBaseAddress; switch (space) { case XCL_ADDR_SPACE_DEVICE_RAM: { const size_t totalSize = size; const size_t mod_size1 = offset % DDR_BUFFER_ALIGNMENT; const size_t mod_size2 = size % DDR_BUFFER_ALIGNMENT; if (mod_size1) { // Buffer not aligned at DDR_BUFFER_ALIGNMENT boundary, need to do Read-Modify-Write size_t returnVal = xclReadModifyWrite(offset, hostBuf, size); PRINTENDFUNC; return returnVal; } else if (mod_size2) { // Buffer not a multiple of DDR_BUFFER_ALIGNMENT, write out the initial block and // then perform a Read-Modify-Write for the remainder buffer const size_t blockSize = size - mod_size2; if (xclWrite(space, offset, hostBuf, blockSize) != blockSize) { PRINTENDFUNC; return -1; } offset += blockSize; hostBuf = static_cast<const char*>(hostBuf) + blockSize; if (xclReadModifyWrite(offset, hostBuf, mod_size2) != mod_size2) { PRINTENDFUNC; return -1; } PRINTENDFUNC; return totalSize; } const char *curr = (const char *)hostBuf; //Note: Adding PF and BAR ID valuesas 0, Once original values are avaiaable they get replaced xclWriteAddrSpaceDeviceRam_RPC_CALL(xclWriteAddrSpaceDeviceRam ,space,offset,curr,size,0,0); PRINTENDFUNC; return totalSize; } case XCL_ADDR_SPACE_DEVICE_PERFMON: { const char *curr = (const char *)hostBuf; std::map<uint64_t,std::pair<std::string,unsigned int>> offsetArgInfo; //Note: Adding PF and BAR ID valuesas 0, Once original values are avaiaable they get replaced xclWriteAddrKernelCtrl_RPC_CALL(xclWriteAddrKernelCtrl ,space,offset,curr,size,offsetArgInfo,0,0); PRINTENDFUNC; return size; } case XCL_ADDR_SPACE_DEVICE_CHECKER: { PRINTENDFUNC; return -1; } case XCL_ADDR_KERNEL_CTRL: { std::map<uint64_t,std::pair<std::string,unsigned int>> offsetArgInfo; std::string kernelName(""); uint32_t *hostBuf32 = ((uint32_t*)hostBuf); // if(hostBuf32[0] & CONTROL_AP_START) auto controlStreamItr = mOffsetInstanceStreamMap.find(offset); if(controlStreamItr != mOffsetInstanceStreamMap.end()) { std::ofstream* controlStream = (*controlStreamItr).second; if(hostBuf32[0] & CONTROL_AP_START) printMem(*controlStream,4, offset, (void*)hostBuf, 4 ); else printMem(*controlStream,4, offset, (void*)hostBuf, size ); } if(hostBuf32[0] & CONTROL_AP_START) { std::string dMsg ="INFO: [HW-EMU 04-0] Sending start signal to the kernel " + kernelName; logMessage(dMsg,1); } else { std::string dMsg ="INFO: [HW-EMU 03-0] Configuring registers for the kernel " + kernelName +" Started"; logMessage(dMsg,1); } //Note: Adding PF and BAR ID valuesas 0, Once original values are avaiaable they get replaced xclWriteAddrKernelCtrl_RPC_CALL(xclWriteAddrKernelCtrl,space,offset,hostBuf,size,offsetArgInfo,0,0); if(hostBuf32[0] & CONTROL_AP_START) { std::string dMsg ="INFO: [HW-EMU 04-1] Kernel " + kernelName +" is Started"; logMessage(dMsg,1); } else { std::string dMsg ="INFO: [HW-EMU 03-1] Configuring registers for the kernel " + kernelName +" Ended"; logMessage(dMsg,1); } PRINTENDFUNC; return size; } default: { PRINTENDFUNC; return -1; } } } size_t HwEmShim::xclRead(xclAddressSpace space, uint64_t offset, void *hostBuf, size_t size) { //if(tracecount_calls < xclemulation::config::getInstance()->getMaxTraceCount()) //{ // tracecount_calls = tracecount_calls + 1; // return 0; //} //tracecount_calls = 0; if (!simulator_started) return 0; if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << space << ", " << offset << ", " << hostBuf << ", " << size << std::endl; } offset = offset | mCuBaseAddress; switch (space) { case XCL_ADDR_SPACE_DEVICE_RAM: { const size_t mod_size1 = offset % DDR_BUFFER_ALIGNMENT; const size_t mod_size2 = size % DDR_BUFFER_ALIGNMENT; const size_t totalSize = size; if (mod_size1) { // Buffer not aligned at DDR_BUFFER_ALIGNMENT boundary, need to do Read-Skip-Copy size_t returnVal = xclReadSkipCopy(offset, hostBuf, size); PRINTENDFUNC; return returnVal; } else if (mod_size2) { // Buffer not a multiple of DDR_BUFFER_ALIGNMENT, read the initial block and // then perform a Read-Skip-Copy for the remainder buffer const size_t blockSize = size - mod_size2; if (xclRead(space, offset, hostBuf, blockSize) != blockSize) { PRINTENDFUNC; return -1; } offset += blockSize; hostBuf = static_cast<char*>(hostBuf) + blockSize; if (xclReadSkipCopy(offset, hostBuf, mod_size2) != mod_size2) { PRINTENDFUNC; return -1; } PRINTENDFUNC; return totalSize; } //const char *curr = (const char *)hostBuf; //Note: Adding PF and BAR ID valuesas 0, Once original values are avaiaable they get replaced xclReadAddrSpaceDeviceRam_RPC_CALL(xclReadAddrSpaceDeviceRam,space,offset,hostBuf,size,0,0); PRINTENDFUNC; return totalSize; } case XCL_ADDR_SPACE_DEVICE_PERFMON: { xclGetDebugMessages(); //Note: Adding PF and BAR ID valuesas 0, Once original values are avaiaable they get replaced xclReadAddrKernelCtrl_RPC_CALL(xclReadAddrKernelCtrl,space,offset,hostBuf,size,0,0); PRINTENDFUNC; return -1; } case XCL_ADDR_SPACE_DEVICE_CHECKER: { PRINTENDFUNC; return -1; } case XCL_ADDR_KERNEL_CTRL: { xclGetDebugMessages(); //Note: Adding PF and BAR ID valuesas 0, Once original values are avaiaable they get replaced xclReadAddrKernelCtrl_RPC_CALL(xclReadAddrKernelCtrl,space,offset,hostBuf,size,0,0); PRINTENDFUNC; return size; } default: { PRINTENDFUNC; return -1; } } } uint32_t HwEmShim::getAddressSpace (uint32_t topology) { if(mMembanks.size() <= topology) return 0; if(mMembanks[topology].tag.find("bank") != std::string::npos) { return 0; } if(mMembanks[topology].tag.find("HBM") != std::string::npos) { return 2; } return 1; } size_t HwEmShim::xclCopyBufferHost2Device(uint64_t dest, const void *src, size_t size, size_t seek, uint32_t topology) { if(!sock) { if(!mMemModel) mMemModel = new mem_model(deviceName); mMemModel->writeDevMem(dest,src,size); return size; } src = (unsigned char*)src + seek; if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << dest << ", " << src << ", " << size << ", " << seek << std::endl; } std::string dMsg ="INFO: [HW-EMU 02-0] Copying buffer from host to device started : size = " + std::to_string(size); logMessage(dMsg,1); void *handle = this; uint64_t messageSize = xclemulation::config::getInstance()->getPacketSize(); uint64_t c_size = messageSize; uint64_t processed_bytes = 0; while(processed_bytes < size){ if((size - processed_bytes) < messageSize){ c_size = size - processed_bytes; }else{ c_size = messageSize; } void* c_src = (((unsigned char*)(src)) + processed_bytes); uint64_t c_dest = dest + processed_bytes; #ifndef _WINDOWS // TODO: Windows build support // *_RPC_CALL uses unix_socket uint32_t space = getAddressSpace(topology); xclCopyBufferHost2Device_RPC_CALL(xclCopyBufferHost2Device,handle,c_dest,c_src,c_size,seek,space); #endif processed_bytes += c_size; } dMsg ="INFO: [HW-EMU 02-1] Copying buffer from host to device ended"; logMessage(dMsg,1); PRINTENDFUNC; printMem(mGlobalInMemStream, 16 , dest , (void*)src, size ); return size; } size_t HwEmShim::xclCopyBufferDevice2Host(void *dest, uint64_t src, size_t size, size_t skip, uint32_t topology) { dest = ((unsigned char*)dest) + skip; if(!sock) { if(!mMemModel) mMemModel = new mem_model(deviceName); mMemModel->readDevMem(src,dest,size); return size; } if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << dest << ", " << src << ", " << size << ", " << skip << std::endl; } std::string dMsg ="INFO: [HW-EMU 05-0] Copying buffer from device to host started. size := " + std::to_string(size); logMessage(dMsg,1); void *handle = this; uint64_t messageSize = xclemulation::config::getInstance()->getPacketSize(); uint64_t c_size = messageSize; uint64_t processed_bytes = 0; while(processed_bytes < size){ if((size - processed_bytes) < messageSize){ c_size = size - processed_bytes; }else{ c_size = messageSize; } void* c_dest = (((unsigned char*)(dest)) + processed_bytes); uint64_t c_src = src + processed_bytes; #ifndef _WINDOWS uint32_t space = getAddressSpace(topology); xclCopyBufferDevice2Host_RPC_CALL(xclCopyBufferDevice2Host,handle,c_dest,c_src,c_size,skip,space); #endif processed_bytes += c_size; } dMsg ="INFO: [HW-EMU 05-1] Copying buffer from device to host ended"; logMessage(dMsg,1); PRINTENDFUNC; printMem(mGlobalOutMemStream, 16 , src , dest , size ); return size; } uint64_t HwEmShim::xclAllocDeviceBuffer(size_t size) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << size << std::endl; } uint64_t origSize = size; if (size == 0) size = DDR_BUFFER_ALIGNMENT; unsigned int paddingFactor = xclemulation::config::getInstance()->getPaddingFactor(); uint64_t result = xclemulation::MemoryManager::mNull; for (auto i : mDDRMemoryManager) { result = i->alloc(size,paddingFactor); if (result != xclemulation::MemoryManager::mNull) break; } uint64_t finalValidAddress = result+(paddingFactor*size); uint64_t finalSize = size+(2*paddingFactor*size); mAddrMap[finalValidAddress] = finalSize; bool ack = false; if(sock) { bool noHostMemory= false; std::string sFileName(""); xclAllocDeviceBuffer_RPC_CALL(xclAllocDeviceBuffer,finalValidAddress,origSize,noHostMemory); PRINTENDFUNC; if(!ack) return 0; } return finalValidAddress; } uint64_t HwEmShim::xclAllocDeviceBuffer2(size_t& size, xclMemoryDomains domain, unsigned flags, bool noHostMemory, unsigned boFlags, std::string &sFileName, std::map<uint64_t,uint64_t>& chunks) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << size <<", "<<domain<<", "<< flags <<std::endl; } if (domain != XCL_MEM_DEVICE_RAM) { PRINTENDFUNC; return xclemulation::MemoryManager::mNull; } if (size == 0) size = DDR_BUFFER_ALIGNMENT; if (flags >= mDDRMemoryManager.size()) { PRINTENDFUNC; return xclemulation::MemoryManager::mNull; } uint64_t origSize = size; unsigned int paddingFactor = xclemulation::config::getInstance()->getPaddingFactor(); uint64_t result = -1; if (boFlags & XCL_BO_FLAGS_HOST_ONLY) { result = mDDRMemoryManager[host_sptag_idx]->alloc(size, paddingFactor, chunks); } else { result = mDDRMemoryManager[flags]->alloc(size, paddingFactor, chunks); } if (result == xclemulation::MemoryManager::mNull) { return result; } uint64_t finalValidAddress = result+(paddingFactor*size); uint64_t finalSize = size+(2*paddingFactor*size); mAddrMap[finalValidAddress] = finalSize; bool ack = false; if(sock) { if (boFlags & XCL_BO_FLAGS_HOST_ONLY) { // bypassed the xclAllocDeviceBuffer RPC call for Slave Bridge (host only buffer) } else { if(chunks.size()) { for (auto it:chunks) { xclAllocDeviceBuffer_RPC_CALL(xclAllocDeviceBuffer, it.first, it.second, noHostMemory); } } else { xclAllocDeviceBuffer_RPC_CALL(xclAllocDeviceBuffer, finalValidAddress, origSize, noHostMemory); } PRINTENDFUNC; if (!ack) return 0; } } return finalValidAddress; } void HwEmShim::xclFreeDeviceBuffer(uint64_t offset, bool sendtoxsim) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << offset << std::endl; } for (auto i : mDDRMemoryManager) { if (offset < i->start() + i->size()) { i->free(offset); } } bool ack = true; if(sock) { //Currently Versal platforms does not support buffer deallocation if(!mVersalPlatform && sendtoxsim) { xclFreeDeviceBuffer_RPC_CALL(xclFreeDeviceBuffer,offset); } } if(!ack) { PRINTENDFUNC; return; } PRINTENDFUNC; } void HwEmShim::logMessage(std::string& msg , int verbosity) { if( verbosity > xclemulation::config::getInstance()->getVerbosityLevel()) return; if ( mDebugLogStream.is_open()) mDebugLogStream << msg<<std::endl; if(xclemulation::config::getInstance()->isInfosToBePrintedOnConsole()) std::cout<<msg<<std::endl; } void HwEmShim::saveWaveDataBase() { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } xclemulation::debug_mode lWaveform = xclemulation::config::getInstance()->getLaunchWaveform(); // The following is evil--hardcoding. This name may change. // Is there a way we can determine the name from the directories or otherwise? std::string bdName("dr"); // Used to be opencldesign. This is new default. int i = 0; for(auto it :mBinaryDirectories) { std::string binaryDirectory = it.first; std::string fileName = it.second; char path[FILENAME_MAX]; size_t size = MAXPATHLEN; char* pPath = GetCurrentDir(path,size); if(pPath) { // Copy waveform database if (lWaveform != xclemulation::debug_mode::off) { std::string extension = "wdb"; if (boost::filesystem::exists(binaryDirectory+"/msim")) { extension = "wlf"; } std::string wdbFileName = binaryDirectory + "/" + fileName + "."+extension; std::string destPath = "'" + std::string(path) + "/" + fileName +"." + extension + "'"; systemUtil::makeSystemCall(wdbFileName, systemUtil::systemOperation::COPY,destPath, std::to_string(__LINE__)); // Copy waveform config std::string wcfgFilePath= binaryDirectory + "/" + bdName + "_behav.wcfg"; std::string destPath2 = "'" + std::string(path) + "/" + fileName + ".wcfg'"; systemUtil::makeSystemCall(wcfgFilePath, systemUtil::systemOperation::COPY, destPath2, std::to_string(__LINE__)); // Append to detailed kernel trace data mining results file std::string logFilePath= binaryDirectory + "/profile_kernels.csv"; std::string destPath3 = "'" + std::string(path) + "/profile_kernels.csv'"; systemUtil::makeSystemCall(logFilePath, systemUtil::systemOperation::APPEND, destPath3, std::to_string(__LINE__)); xclemulation::copyLogsFromOneFileToAnother(logFilePath, mDebugLogStream); // Append to detailed kernel trace "timeline" file std::string traceFilePath = binaryDirectory + "/timeline_kernels.csv"; std::string destPath4 = "'" + std::string(path) + "/timeline_kernels.csv'"; systemUtil::makeSystemCall(traceFilePath, systemUtil::systemOperation::APPEND, destPath4, std::to_string(__LINE__)); // Copy proto inst file std::string protoFilePath= binaryDirectory + "/" + bdName + "_behav.protoinst"; std::string destPath6 = "'" + std::string(path) + "/" + fileName + ".protoinst'"; systemUtil::makeSystemCall(protoFilePath, systemUtil::systemOperation::COPY, destPath6, std::to_string(__LINE__)); if (mLogStream.is_open()) mLogStream << "appended " << logFilePath << " to " << destPath3 << std::endl; } // Copy Simulation Log file std::string simulationLogFilePath= binaryDirectory + "/" + "simulate.log"; std::string destPath5 = "'" + std::string(path) + "/" + fileName + "_simulate.log'"; systemUtil::makeSystemCall(simulationLogFilePath, systemUtil::systemOperation::COPY, destPath5, std::to_string(__LINE__)); // Copy xsc_report Log file std::string xscReportLogFilePath= binaryDirectory + "/" + "xsc_report.log"; std::string destPath8 = "'" + std::string(path) + "/" + fileName + "_xsc_report.log'"; systemUtil::makeSystemCall(xscReportLogFilePath, systemUtil::systemOperation::COPY, destPath8, std::to_string(__LINE__)); } i++; } mBinaryDirectories.clear(); PRINTENDFUNC; if (mLogStream.is_open()) { mLogStream.close(); } } void HwEmShim::xclClose() { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } parseLog(); for (auto& it: mFdToFileNameMap) { int fd=it.first; int sSize = std::get<1>(it.second); void* addr = std::get<2>(it.second); munmap(addr,sSize); close(fd); } mFdToFileNameMap.clear(); // Shim object is not deleted as part of closing device. // The core device must correspond to open and close, so // reset here rather than in destructor xdp::hw_emu::flush_device(this); mCoreDevice.reset(); device_handles::remove(this); if (!sock) { if (xclemulation::config::getInstance()->isKeepRunDirEnabled() == false) { systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::REMOVE, "", std::to_string(__LINE__)); } if(mMBSch && mCore) { mMBSch->fini_scheduler_thread(); delete mCore; mCore = NULL; delete mMBSch; mMBSch = NULL; } if(m_scheduler) { delete m_scheduler; m_scheduler = nullptr; } if(m_xgq) { delete m_xgq; m_xgq = nullptr; } PRINTENDFUNC; if (mLogStream.is_open()) { mLogStream.close(); } return; } resetProgram(false); int status = 0; xclemulation::debug_mode lWaveform = xclemulation::config::getInstance()->getLaunchWaveform(); if(( lWaveform == xclemulation::debug_mode::gui || lWaveform == xclemulation::debug_mode::batch || lWaveform == xclemulation::debug_mode::off) && xclemulation::config::getInstance()->isInfoSuppressed() == false) { std::string waitingMsg ="INFO: [HW-EMU 06-0] Waiting for the simulator process to exit"; logMessage(waitingMsg); } //bool simDontRun = xclemulation::config::getInstance()->isDontRun(); if(!mSimDontRun) while (-1 == waitpid(0, &status, 0)); if(( lWaveform == xclemulation::debug_mode::gui || lWaveform == xclemulation::debug_mode::batch || lWaveform == xclemulation::debug_mode::off) && xclemulation::config::getInstance()->isInfoSuppressed() == false) { std::string waitingMsg ="INFO: [HW-EMU 06-1] All the simulator processes exited successfully"; logMessage(waitingMsg); std::string consoleMsg = "INFO: [HW-EMU 07-0] Please refer the path \"" + getSimPath() + "/simulate.log\" for more detailed simulation infos, errors and warnings."; logMessage(consoleMsg); } saveWaveDataBase(); if( xclemulation::config::getInstance()->isKeepRunDirEnabled() == false) systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::REMOVE, "", std::to_string(__LINE__)); google::protobuf::ShutdownProtobufLibrary(); PRINTENDFUNC; if (mLogStream.is_open()) { mLogStream.close(); } } int HwEmShim::resetProgram(bool saveWdb) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } for (auto& it: mFdToFileNameMap) { int fd=it.first; int sSize = std::get<1>(it.second); void* addr = std::get<2>(it.second); munmap(addr,sSize); close(fd); } mFdToFileNameMap.clear(); if(!sock) { PRINTENDFUNC; if(mMBSch && mCore) { mMBSch->fini_scheduler_thread(); delete mCore; mCore = NULL; delete mMBSch; mMBSch = NULL; } if(m_scheduler) { delete m_scheduler; m_scheduler = nullptr; } if(m_xgq) { delete m_xgq; m_xgq = nullptr; } return 0; } #ifndef _WINDOWS // TODO: Windows build support // *_RPC_CALL uses unix_socket #endif Event eventObj; uint32_t numSlots = getPerfMonNumberSlots(XCL_PERF_MON_MEMORY); bool ack = true; for(unsigned int counter = 0 ; counter < numSlots; counter++) { unsigned int samplessize = 0; if (counter == XPAR_AIM0_HOST_SLOT) continue; char slotname[128]; getPerfMonSlotName(XCL_PERF_MON_MEMORY,counter,slotname,128); if (simulator_started == true) { #ifndef _WINDOWS // TODO: Windows build support // *_RPC_CALL uses unix_socket do { bool accel=false; xclPerfMonReadTrace_RPC_CALL(xclPerfMonReadTrace,ack,samplessize,slotname,accel); #endif for(unsigned int i = 0; i<samplessize ; i++) { #ifndef _WINDOWS // TODO: Windows build support // r_msg is defined as part of *RPC_CALL definition const xclPerfMonReadTrace_response::events &event = r_msg.output_data(i); eventObj.timestamp = event.timestamp(); eventObj.eventflags = event.eventflags(); eventObj.arlen = event.arlen(); eventObj.awlen = event.awlen(); eventObj.host_timestamp = event.host_timestamp(); eventObj.readBytes = event.rd_bytes(); eventObj.writeBytes = event.wr_bytes(); list_of_events[counter].push_back(eventObj); #endif } } while (samplessize != 0); } } xclGetDebugMessages(true); mPrintMessagesLock.lock(); fetchAndPrintMessages(); simulator_started = false; mPrintMessagesLock.unlock(); std::string socketName = sock->get_name(); if(socketName.empty() == false)// device is active if socketName is non-empty { #ifndef _WINDOWS xclClose_RPC_CALL(xclClose,this); #endif closemMessengerThread(); //clean up directories which are created inside the driver systemUtil::makeSystemCall(socketName, systemUtil::systemOperation::REMOVE, "", std::to_string(__LINE__)); } if(saveWdb) { int status = 0; xclemulation::debug_mode lWaveform = xclemulation::config::getInstance()->getLaunchWaveform(); if(( lWaveform == xclemulation::debug_mode::gui || lWaveform == xclemulation::debug_mode::batch || lWaveform == xclemulation::debug_mode::off ) && xclemulation::config::getInstance()->isInfoSuppressed() == false) { std::string waitingMsg ="INFO: [HW-EMU 06-0] Waiting for the simulator process to exit"; logMessage(waitingMsg); } //bool simDontRun = xclemulation::config::getInstance()->isDontRun(); if (!mSimDontRun) while (-1 == waitpid(0, &status, 0)); if(( lWaveform == xclemulation::debug_mode::gui || lWaveform == xclemulation::debug_mode::batch || lWaveform == xclemulation::debug_mode::off ) && xclemulation::config::getInstance()->isInfoSuppressed() == false) { std::string waitingMsg ="INFO: [HW-EMU 06-1] All the simulator processes exited successfully"; logMessage(waitingMsg); } saveWaveDataBase(); } //ProfilerStop(); delete sock; sock = NULL; PRINTENDFUNC; if(mMBSch && mCore) { mMBSch->fini_scheduler_thread(); delete mCore; mCore = NULL; delete mMBSch; mMBSch = NULL; } if(m_scheduler) { delete m_scheduler; m_scheduler = nullptr; } if(m_xgq) { delete m_xgq; m_xgq = nullptr; } return 0; } HwEmShim *HwEmShim::handleCheck(void *handle) { if (!handle) return 0; return (HwEmShim *)handle; } HwEmShim::~HwEmShim() { free(ci_buf); free(ri_buf); free(buf); parsedMsgs.clear(); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; mLogStream.close(); } if (xclemulation::config::getInstance()->isMemLogsEnabled()) { mGlobalInMemStream.close(); mGlobalOutMemStream.close(); } for(auto controlStreamItr : mOffsetInstanceStreamMap) { std::ofstream* os = controlStreamItr.second; if(os) { os->close(); delete os; os=NULL; } } if(mMBSch && mCore) { mMBSch->fini_scheduler_thread(); delete mCore; mCore = NULL; delete mMBSch; mMBSch = NULL; } if(m_scheduler) { delete m_scheduler; m_scheduler = nullptr; } if(m_xgq) { delete m_xgq; m_xgq = nullptr; } if(mDataSpace) { delete mDataSpace; mDataSpace = NULL; } closemMessengerThread(); } void HwEmShim::initMemoryManager(std::list<xclemulation::DDRBank>& DDRBankList) { std::list<xclemulation::DDRBank>::iterator start = DDRBankList.begin(); std::list<xclemulation::DDRBank>::iterator end = DDRBankList.end(); uint64_t base = 0; for(;start != end; start++) { const uint64_t bankSize = (*start).ddrSize; mDdrBanks.push_back(*start); mDDRMemoryManager.push_back(new xclemulation::MemoryManager(bankSize, base , getpagesize())); base += bankSize; } } std::string HwEmShim::getSimulatorType(const std::string& binaryDirectory) { std::string simulator; std::string sim_path1 = binaryDirectory + "/behav_waveform/xsim"; std::string sim_path2 = binaryDirectory + "/behav_gdb/xsim"; std::string sim_path3 = binaryDirectory + "/behav_waveform/questa"; std::string sim_path4 = binaryDirectory + "/behav_waveform/xcelium"; std::string sim_path5 = binaryDirectory + "/behav_waveform/vcs"; if (boost::filesystem::exists(sim_path1) || boost::filesystem::exists(sim_path2)) { simulator = "xsim"; } else if (boost::filesystem::exists(sim_path3)) { simulator = "questa"; } else if (boost::filesystem::exists(sim_path4)) { simulator = "xcelium"; } else if (boost::filesystem::exists(sim_path5)) { simulator = "vcs"; } if (!boost::filesystem::exists(sim_path1) && !boost::filesystem::exists(sim_path2) && !boost::filesystem::exists(sim_path3) && !boost::filesystem::exists(sim_path4) && !boost::filesystem::exists(sim_path5)) { std::string dMsg = "ERROR: [HW-EMU 11] UNZIP operation failed. Not to able to get the required simulation binaries from xclbin"; logMessage(dMsg, 0); } return simulator; } void HwEmShim::fillDeviceInfo(xclDeviceInfo2* dest, xclDeviceInfo2* src) { std::strcpy(dest->mName, src->mName); dest->mMagic = src->mMagic ; dest->mHALMajorVersion = src->mHALMajorVersion; dest->mHALMinorVersion = src->mHALMinorVersion; dest->mVendorId = src->mVendorId; dest->mDeviceId = src->mDeviceId; dest->mSubsystemVendorId = src->mSubsystemVendorId; dest->mDeviceVersion = src->mDeviceVersion; dest->mDDRSize = src->mDDRSize; dest->mDataAlignment = src->mDataAlignment; dest->mDDRBankCount = src->mDDRBankCount; uint32_t numCdma = 0; if(isCdmaEnabled()) { for(unsigned int i =0 ; i < 4; i++) { if ( getCdmaBaseAddress(i) != 0) { numCdma++; } } } dest->mNumCDMA = numCdma; for(unsigned int i = 0; i < 4 ;i++) dest->mOCLFrequency[i] = src->mOCLFrequency[i]; } HwEmShim::HwEmShim(unsigned int deviceIndex, xclDeviceInfo2 &info, std::list<xclemulation::DDRBank>& DDRBankList, bool _unified, bool _xpr, FeatureRomHeader &fRomHeader, const boost::property_tree::ptree& platformData) :mRAMSize(info.mDDRSize) ,mCoalesceThreshold(4) ,mDSAMajorVersion(DSA_MAJOR_VERSION) ,mDSAMinorVersion(DSA_MINOR_VERSION) ,mDeviceIndex(deviceIndex) ,mCuIndx(0) { simulator_started = false; tracecount_calls = 0; mReqCounter = 0; simulatorType = "xsim"; sim_path = ""; mSimDontRun = false; ci_msg.set_size(0); ci_msg.set_xcl_api(0); #if GOOGLE_PROTOBUF_VERSION < 3006001 ci_buf = malloc(ci_msg.ByteSize()); #else ci_buf = malloc(ci_msg.ByteSizeLong()); #endif ri_msg.set_size(0); #if GOOGLE_PROTOBUF_VERSION < 3006001 ri_buf = malloc(ri_msg.ByteSize()); #else ri_buf = malloc(ri_msg.ByteSizeLong()); #endif buf = nullptr; buf_size = 0; binaryCounter = 0; host_sptag_idx = -1; sock = nullptr; mCURangeMap.clear(); deviceName = "device"+std::to_string(deviceIndex); deviceDirectory = xclemulation::getRunDirectory() +"/" + std::to_string(getpid())+"/hw_em/"+deviceName; systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::CREATE, "", std::to_string(__LINE__)); systemUtil::makeSystemCall(deviceDirectory, systemUtil::systemOperation::PERMISSIONS, "777", std::to_string(__LINE__)); mPlatformData = platformData; constructQueryTable(); std::memset(&mDeviceInfo, 0, sizeof(xclDeviceInfo2)); fillDeviceInfo(&mDeviceInfo,&info); initMemoryManager(DDRBankList); std::memset(&mFeatureRom, 0, sizeof(FeatureRomHeader)); std::memcpy(&mFeatureRom, &fRomHeader, sizeof(FeatureRomHeader)); last_clk_time = clock(); mCloseAll = false; mMemModel = nullptr; // Delete detailed kernel trace data mining results file // NOTE: do this only if we're going to write a new one xclemulation::debug_mode lWaveform = xclemulation::config::getInstance()->getLaunchWaveform(); if (lWaveform == xclemulation::debug_mode::gui || lWaveform == xclemulation::debug_mode::batch || lWaveform == xclemulation::debug_mode::off) { char path[FILENAME_MAX]; size_t size = MAXPATHLEN; char* pPath = GetCurrentDir(path,size); if(pPath) { std::string sdxProfileKernelFile = std::string(path) + "/profile_kernels.csv"; systemUtil::makeSystemCall(sdxProfileKernelFile, systemUtil::systemOperation::REMOVE, "", std::to_string(__LINE__)); std::string sdxTraceKernelFile = std::string(path) + "/timeline_kernels.csv"; systemUtil::makeSystemCall(sdxTraceKernelFile, systemUtil::systemOperation::REMOVE, "", std::to_string(__LINE__)); } } bUnified = _unified; bXPR = _xpr; mCore = nullptr; mMBSch = nullptr; m_scheduler = nullptr; m_xgq = nullptr; mIsDebugIpLayoutRead = false; mIsDeviceProfiling = false; mMemoryProfilingNumberSlots = 0; mAccelProfilingNumberSlots = 0; mStallProfilingNumberSlots = 0; mStreamProfilingNumberSlots = 0; mPerfMonFifoCtrlBaseAddress = 0; mPerfMonFifoReadBaseAddress = 0; mTraceFunnelAddress = 0; mDataSpace = new xclemulation::MemoryManager(0x10000000, 0, getpagesize()); mCuBaseAddress = 0x0; mMessengerThreadStarted = false; mIsTraceHubAvailable = false; mVersalPlatform=false; mHostMemAccessThreadStarted = false; } bool HwEmShim::isMBSchedulerEnabled() { if (xclemulation::config::getInstance()->getIsPlatformEnabled()) { if (mPlatformData.get_optional<std::string>("plp.ert").is_initialized()) { std::string ertStr = mPlatformData.get<std::string>("plp.ert"); return (ertStr == "enabled" ? true : false); } } bool mbSchEnabled = mFeatureRom.FeatureBitMap & FeatureBitMask::MB_SCHEDULER; bool QDMAPlatform = (getDsaVersion() == 60) ? true : false; return mbSchEnabled && !QDMAPlatform; } void HwEmShim::constructQueryTable() { if (xclemulation::config::getInstance()->getIsPlatformEnabled()) { if (mPlatformData.get_optional<std::string>("plp.m2m").is_initialized()) { mQueryTable[key_type::m2m] = mPlatformData.get<std::string>("plp.m2m"); } if (mPlatformData.get_optional<std::string>("plp.dma").is_initialized()) { std::string dmaVal = mPlatformData.get<std::string>("plp.dma"); mQueryTable[key_type::nodma] = (dmaVal == "none" ? "enabled" : "disabled"); } } } // New API's for device query - m2m and no-dma int HwEmShim::deviceQuery(key_type queryKey) { if (mQueryTable.find(queryKey) != mQueryTable.end()) return (mQueryTable[queryKey] == "enabled" ? 1 : 0); return 0; } std::string HwEmShim::getERTVersion() { if (xclemulation::config::getInstance()->getIsPlatformEnabled()) { if (mPlatformData.get_optional<std::string>("plp.ertVersion").is_initialized()) { return (mPlatformData.get<std::string>("plp.ertVersion")); } } return "10"; } uint64_t HwEmShim::getM2MAddress() { if (xclemulation::config::getInstance()->getIsPlatformEnabled()) { if (mPlatformData.get_optional<std::string>("plp.m2m_address").is_initialized()) { std::stringstream streamSS; streamSS << std::hex << mPlatformData.get<std::string>("plp.m2m_address"); uint64_t baseAddr_u; streamSS >> baseAddr_u; return baseAddr_u; } } return 0; } uint64_t HwEmShim::getErtCmdQAddress() { if (xclemulation::config::getInstance()->getIsPlatformEnabled()) { if (mPlatformData.get_optional<std::string>("plp.ertCmdqBaseAddr").is_initialized()) { std::stringstream streamSS ; streamSS << std::hex << mPlatformData.get<std::string>("plp.ertCmdqBaseAddr"); uint64_t baseAddr_u; streamSS >> baseAddr_u; return baseAddr_u; } } return 0; } uint64_t HwEmShim::getErtBaseAddress() { if (xclemulation::config::getInstance()->getIsPlatformEnabled()) { if (mPlatformData.get_optional<std::string>("plp.ertBaseAddr").is_initialized()) { std::stringstream streamSS ; streamSS << std::hex << mPlatformData.get<std::string>("plp.ertBaseAddr"); uint64_t baseAddr_u; streamSS >> baseAddr_u; return baseAddr_u; } } return 0; } std::shared_ptr<xrt_core::device> HwEmShim::getMCoreDevice() { return mCoreDevice; } bool HwEmShim::isLegacyErt() { if(xclemulation::config::getInstance()->getLegacyErt() == xclemulation::ertmode::legacy) return true; else if(xclemulation::config::getInstance()->getLegacyErt() == xclemulation::ertmode::updated) return false; //Following platforms uses legacyErt As per Emulation team. //There is no other way to get whether platform uses legacy ERT or not std::string vbnv = mDeviceInfo.mName; if(!vbnv.empty() && ( vbnv.find("u200_xdma-gen3x4_201830") != std::string::npos || vbnv.find("u200_xdma_201830") != std::string::npos || vbnv.find("u250_qep_201910") != std::string::npos || vbnv.find("u250_xdma_201830") != std::string::npos || vbnv.find("u280_xdma_201920") != std::string::npos || vbnv.find("u50_xdma_201910") != std::string::npos || vbnv.find("u50_xdma_201920") != std::string::npos)) return true; return false; } bool HwEmShim::isCdmaEnabled() { if (xclemulation::config::getInstance()->getIsPlatformEnabled()) { if (mPlatformData.get_optional<std::string>("plp.numCdma").is_initialized()) { int numCdma = std::stoi(mPlatformData.get<std::string>("plp.numCdma")); return (numCdma > 0 ? true : false); } } return mFeatureRom.FeatureBitMap & FeatureBitMask::CDMA; } uint64_t HwEmShim::getCdmaBaseAddress(unsigned int index) { if (xclemulation::config::getInstance()->getIsPlatformEnabled()) { std::string cdmaAddrStr = "plp.cdmaBaseAddress" + std::to_string(index); if (mPlatformData.get_optional<std::string>(cdmaAddrStr).is_initialized()) { std::stringstream streamSS ; streamSS << std::hex << mPlatformData.get<std::string>(cdmaAddrStr); uint64_t baseAddr_u; streamSS >> baseAddr_u; return baseAddr_u; } } return mFeatureRom.CDMABaseAddress[index]; } //following code is copied from core/pcie/driver/linux/xocl/subdev/feature_rom.c unsigned int HwEmShim::getDsaVersion() { std::string vbnv = mDeviceInfo.mName; if(vbnv.empty()) return 52; if (vbnv.find("5_0") != std::string::npos) return 50; else if (vbnv.find("qdma") != std::string::npos) return 60; else if ( (vbnv.find("5_1") != std::string::npos) || (vbnv.find("u200_xdma_201820_1") != std::string::npos)) return 51; else if ((vbnv.find("5_2") != std::string::npos) || (vbnv.find("u200_xdma_201820_2") != std::string::npos ) || (vbnv.find("u250_xdma_201820_1") != std::string::npos ) || (vbnv.find("201830") != std::string::npos)) return 52; else if (vbnv.find("5_3") != std::string::npos) return 53; else if (vbnv.find("6_0") != std::string::npos) return 60; return 52; } size_t HwEmShim::xclGetDeviceTimestamp() { bool ack = true; size_t deviceTimeStamp = 0; xclGetDeviceTimestamp_RPC_CALL(xclGetDeviceTimestamp,ack,deviceTimeStamp); return deviceTimeStamp; } void HwEmShim::xclReadBusStatus(xclPerfMonType type) { bool is_bus_idle = true; uint64_t l_idle_bus_cycles = 0; uint64_t idle_bus_cycles = 0; time_t currentTime; struct tm *localTime; time( &currentTime ); localTime = localtime( &currentTime ); std::string time_s = "[Time: " + std::to_string(localTime->tm_hour) + ":" + std::to_string(localTime->tm_min) + "]"; for(uint32_t slot_n = 0; slot_n < getPerfMonNumberSlots(type)-1; slot_n++) { xclReadBusStatus_RPC_CALL(xclReadBusStatus,idle_bus_cycles,slot_n); is_bus_idle = is_bus_idle & (idle_bus_cycles > 0); if(idle_bus_cycles > 0) { l_idle_bus_cycles = idle_bus_cycles; } } if(is_bus_idle) { std::cout << "INFO " << time_s <<" There is no traffic between DDR Memory and Kernel for last " << l_idle_bus_cycles << " clock cycles" << std::endl; } else { if ((clock() - last_clk_time)/CLOCKS_PER_SEC > 60*5) { last_clk_time = clock(); std::cout << "INFO " << time_s<<" Hardware Emulation is in progress..." << std::endl; } } } void HwEmShim::xclGetDebugMessages(bool force) { if(xclemulation::config::getInstance()->isSystemDPAEnabled() == true) { return; } if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } bool ack = true; std::string displayMsgs; std::string logMsgs; std::string stopMsgs; xclGetDebugMessages_RPC_CALL(xclGetDebugMessages,ack,force,displayMsgs,logMsgs,stopMsgs); if(mDebugLogStream.is_open() && logMsgs.empty() == false) { mDebugLogStream <<logMsgs; mDebugLogStream.flush(); } if(displayMsgs.empty() == false) { std::cout<<displayMsgs; std::cout.flush(); } PRINTENDFUNC; } size_t HwEmShim::xclReadSkipCopy(uint64_t offset, void *hostBuf, size_t size) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << offset << ", " << hostBuf << ", " << size << std::endl; } const size_t mod_size = offset % DDR_BUFFER_ALIGNMENT; // Need to do Read-Modify-Read #ifndef _WINDOWS // TODO: Windows build support // alignas is defined in c++11 alignas(DDR_BUFFER_ALIGNMENT) char buffer[DDR_BUFFER_ALIGNMENT]; #else char buffer[DDR_BUFFER_ALIGNMENT]; #endif // Read back one full aligned block starting from preceding aligned address const uint64_t mod_offset = offset - mod_size; if (xclRead(XCL_ADDR_SPACE_DEVICE_RAM, mod_offset, buffer, DDR_BUFFER_ALIGNMENT) != DDR_BUFFER_ALIGNMENT) { PRINTENDFUNC; return -1; } const size_t copy_size = (size + mod_size > DDR_BUFFER_ALIGNMENT) ? DDR_BUFFER_ALIGNMENT - mod_size : size; // Update the user buffer with partial read std::memcpy(hostBuf, buffer + mod_size, copy_size); // Update the remainder of user buffer if (size + mod_size > DDR_BUFFER_ALIGNMENT) { const size_t read_size = xclRead(XCL_ADDR_SPACE_DEVICE_RAM, mod_offset + DDR_BUFFER_ALIGNMENT, (char *)hostBuf + copy_size, size - copy_size); if (read_size != (size - copy_size)) { PRINTENDFUNC; return -1; } } PRINTENDFUNC; return size; } size_t HwEmShim::xclReadModifyWrite(uint64_t offset, const void *hostBuf, size_t size) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << offset << ", " << hostBuf << ", " << size << std::endl; } #ifndef _WINDOWS // TODO: Windows build support // alignas is defined in c++11 alignas(DDR_BUFFER_ALIGNMENT) char buffer[DDR_BUFFER_ALIGNMENT]; #else char buffer[DDR_BUFFER_ALIGNMENT]; #endif const size_t mod_size = offset % DDR_BUFFER_ALIGNMENT; // Read back one full aligned block starting from preceding aligned address const uint64_t mod_offset = offset - mod_size; if (xclRead(XCL_ADDR_SPACE_DEVICE_RAM, mod_offset, buffer, DDR_BUFFER_ALIGNMENT) != DDR_BUFFER_ALIGNMENT) { PRINTENDFUNC; return -1; } // Update the local copy of buffer with user requested data const size_t copy_size = (size + mod_size > DDR_BUFFER_ALIGNMENT) ? DDR_BUFFER_ALIGNMENT - mod_size : size; std::memcpy(buffer + mod_size, hostBuf, copy_size); // Write back the updated aligned block if (xclWrite(XCL_ADDR_SPACE_DEVICE_RAM, mod_offset, buffer, DDR_BUFFER_ALIGNMENT) != DDR_BUFFER_ALIGNMENT) { PRINTENDFUNC; return -1; } // Write any remaining blocks over DDR_BUFFER_ALIGNMENT size if (size + mod_size > DDR_BUFFER_ALIGNMENT) { size_t write_size = xclWrite(XCL_ADDR_SPACE_DEVICE_RAM, mod_offset + DDR_BUFFER_ALIGNMENT, (const char *)hostBuf + copy_size, size - copy_size); if (write_size != (size - copy_size)) { PRINTENDFUNC; return -1; } } PRINTENDFUNC; return size; } int HwEmShim::xclGetDeviceInfo2(xclDeviceInfo2 *info) { std::memset(info, 0, sizeof(xclDeviceInfo2)); fillDeviceInfo(info,&mDeviceInfo); for (auto i : mDDRMemoryManager) { info->mDDRFreeSize += i->freeSize(); } return 0; } //TODO::SPECIFIC TO LINUX //Need to modify for windows void HwEmShim::xclOpen(const char* logfileName) { //populate environment information in driver xclemulation::config::getInstance()->populateEnvironmentSetup(mEnvironmentNameValueMap); char path[FILENAME_MAX]; size_t size = MAXPATHLEN; char* pPath = GetCurrentDir(path,size); if(pPath) { std::string sdxProfileKernelFile = std::string(path) + "/profile_kernels.csv"; systemUtil::makeSystemCall(sdxProfileKernelFile, systemUtil::systemOperation::REMOVE, "", std::to_string(__LINE__)); std::string sdxTraceKernelFile = std::string(path) + "/timeline_kernels.csv"; systemUtil::makeSystemCall(sdxTraceKernelFile, systemUtil::systemOperation::REMOVE, "", std::to_string(__LINE__)); } std::string logFilePath = xrt_core::config::get_hal_logging(); if (!logFilePath.empty()) { mLogStream.open(logFilePath); mLogStream << "FUNCTION, THREAD ID, ARG..." << std::endl; mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } if (xclemulation::config::getInstance()->isMemLogsEnabled()) { mGlobalInMemStream.open("global_in.mem"); mGlobalOutMemStream.open("global_out.mem"); } // Shim object creation doesn't follow xclOpen/xclClose. // The core device must correspond to open and close, so // create here rather than in constructor mCoreDevice = xrt_core::hwemu::get_userpf_device(this, mDeviceIndex); device_handles::add(this); } /**********************************************HAL2 API's START HERE **********************************************/ /*********************************** Utility ******************************************/ static bool check_bo_user_flags(HwEmShim* dev, unsigned flags) { const unsigned ddr_count = dev->xocl_ddr_channel_count(); unsigned ddr; if(ddr_count == 0) return false; if (flags == XOCL_MEM_BANK_MSK) return true; ddr = xclemulation::xocl_bo_ddr_idx(flags,false); if (ddr > ddr_count) return false; return true; } xclemulation::drm_xocl_bo* HwEmShim::xclGetBoByHandle(unsigned int boHandle) { auto it = mXoclObjMap.find(boHandle); if(it == mXoclObjMap.end()) return nullptr; xclemulation::drm_xocl_bo* bo = (*it).second; return bo; } inline unsigned short HwEmShim::xocl_ddr_channel_count() { if(mMembanks.size() > 0) return mMembanks.size(); return mDeviceInfo.mDDRBankCount; } inline unsigned long long HwEmShim::xocl_ddr_channel_size() { return 0; } int HwEmShim::xclGetBOProperties(unsigned int boHandle, xclBOProperties *properties) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if (!bo) { PRINTENDFUNC; return -1; } properties->handle = bo->handle; properties->flags = bo->flags; properties->size = bo->size; properties->paddr = bo->base; PRINTENDFUNC; return 0; } /*****************************************************************************************/ /******************************** xclAllocBO *********************************************/ uint64_t HwEmShim::xoclCreateBo(xclemulation::xocl_create_bo* info) { size_t size = info->size; unsigned ddr = xclemulation::xocl_bo_ddr_idx(info->flags,false); if (!size) { return -1; } /* Either none or only one DDR should be specified */ if (!check_bo_user_flags(this, info->flags)) { return -1; } auto xobj = std::make_unique<xclemulation::drm_xocl_bo>(); xobj->flags=info->flags; /* check whether buffer is p2p or not*/ bool noHostMemory = xclemulation::no_host_memory(xobj.get()); std::string sFileName(""); if(xobj->flags & XCL_BO_FLAGS_EXECBUF) { uint64_t result = mDataSpace->alloc(size,1); xobj->base = result; } else { xobj->base = xclAllocDeviceBuffer2(size, XCL_MEM_DEVICE_RAM, ddr, noHostMemory, info->flags, sFileName, xobj->chunks); } xobj->filename = sFileName; xobj->size = size; xobj->userptr = NULL; xobj->buf = NULL; xobj->topology=ddr; xobj->fd = -1; if(xobj->base == xclemulation::MemoryManager::mNull) { return xclemulation::MemoryManager::mNull; } info->handle = mBufferCount; mXoclObjMap[mBufferCount++] = xobj.release(); return 0; } unsigned int HwEmShim::xclAllocBO(size_t size, int unused, unsigned flags) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << size << std::dec << " , "<< unused <<" , "<< flags << std::endl; } xclemulation::xocl_create_bo info = {size, mNullBO, flags}; uint64_t result = xoclCreateBo(&info); PRINTENDFUNC; return result ? mNullBO : info.handle; } /***************************************************************************************/ /******************************** xclAllocUserPtrBO ************************************/ unsigned int HwEmShim::xclAllocUserPtrBO(void *userptr, size_t size, unsigned flags) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << userptr <<", " << std::hex << size << std::dec <<" , "<< flags << std::endl; } xclemulation::xocl_create_bo info = {size, mNullBO, flags}; uint64_t result = xoclCreateBo(&info); xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(info.handle); if (bo) { bo->userptr = userptr; } PRINTENDFUNC; return result ? mNullBO : info.handle; } /***************************************************************************************/ /******************************** xclExportBO *******************************************/ int HwEmShim::xclExportBO(unsigned int boHandle) { //TODO if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) return -1; std::string sFileName = bo->filename; if(sFileName.empty()) { std::cout<<"Exported Buffer is not P2P "<<std::endl; PRINTENDFUNC; return -1; } uint64_t size = bo->size; int fd = open(sFileName.c_str(), (O_CREAT | O_RDWR), 0666); if (fd == -1) { printf("Error opening exported BO file.\n"); PRINTENDFUNC; return -1; }; char* data = (char*) mmap(0, bo->size , PROT_READ |PROT_WRITE |PROT_EXEC , MAP_SHARED, fd, 0); if(!data) { PRINTENDFUNC; return -1; } int rf = ftruncate(fd, bo->size); if(rf == -1 ) { close(fd); munmap(data,size); return -1; } mFdToFileNameMap [fd] = std::make_tuple(sFileName,size,(void*)data,bo->flags); PRINTENDFUNC; return fd; } /***************************************************************************************/ /******************************** xclImportBO *******************************************/ unsigned int HwEmShim::xclImportBO(int boGlobalHandle, unsigned flags) { //TODO if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boGlobalHandle << std::endl; } auto itr = mFdToFileNameMap.find(boGlobalHandle); if(itr != mFdToFileNameMap.end()) { int size = std::get<1>((*itr).second); unsigned boFlags = std::get<3>((*itr).second); unsigned int importedBo = xclAllocBO(size, 0, boFlags); xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(importedBo); if(!bo) { std::cout<<"ERROR HERE in importBO "<<std::endl; return -1; } mImportedBOs.insert(importedBo); bo->fd = boGlobalHandle; return importedBo; } PRINTENDFUNC; return -1; } /***************************************************************************************/ /******************************** xclCopyBO *******************************************/ int HwEmShim::xclCopyBO(unsigned int dst_boHandle, unsigned int src_boHandle, size_t size, size_t dst_offset, size_t src_offset) { std::lock_guard<std::mutex> lk(mApiMtx); //TODO if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << dst_boHandle << ", "<< src_boHandle << ", "<< size << ", " << dst_offset << ", " << src_offset<< std::endl; } xclemulation::drm_xocl_bo* sBO = xclGetBoByHandle(src_boHandle); if(!sBO) { PRINTENDFUNC; return -1; } xclemulation::drm_xocl_bo* dBO = xclGetBoByHandle(dst_boHandle); if(!dBO) { PRINTENDFUNC; return -1; } // Copy buffer thru the M2M. if ((deviceQuery(key_type::m2m) && getM2MAddress() != 0) && !((sBO->fd >= 0) || (dBO->fd >= 0))) { char hostBuf[M2M_KERNEL_ARGS_SIZE]; std::memset(hostBuf, 0, M2M_KERNEL_ARGS_SIZE); //src and dest addresses construction uint64_t src_addr = sBO->base + src_offset; uint64_t dest_addr = dBO->base + dst_offset; //fill the hostbuf with the src offset and dest offset and size offset std::memcpy(hostBuf + 0x10, (unsigned char*)&src_addr, 8); //copying the src address to the hostbuf to the specified offset by M2M IP std::memcpy(hostBuf + 0x18, (unsigned char*)&dest_addr, 8); //copying the dest address to the hostbuf to the specified offset by M2M IP std::memcpy(hostBuf + 0x20, (unsigned char*)&size, 4); //copying the size address to the hostbuf to the specified offset by M2M IP //Configuring the kernel with hostbuf by providing the Base address of the IP if (xclWrite(XCL_ADDR_KERNEL_CTRL, getErtBaseAddress() + 0x20000, hostBuf, M2M_KERNEL_ARGS_SIZE) != M2M_KERNEL_ARGS_SIZE) { std::cerr << "ERROR: Failed to write to args to the m2m IP" << std::endl; } hostBuf[0] = 0x1; //filling the hostbuf with the start info //Starting the kernel if (xclWrite(XCL_ADDR_KERNEL_CTRL, getErtBaseAddress() + 0x20000, hostBuf, 4) != 4) { std::cerr << "ERROR: Failed to start the m2m kernel" << std::endl; } do { //Read the status of the kernel by polling the hostBuf[0] //check for the base_address is either 4 or 6 xclRead(XCL_ADDR_KERNEL_CTRL, getErtBaseAddress() + 0x20000, hostBuf, 4); } while (!(hostBuf[0] & (CONTROL_AP_DONE | CONTROL_AP_IDLE))); PRINTENDFUNC; return 0; } // source buffer is host_only and destination buffer is device_only if (isHostOnlyBuffer(sBO) && !xclemulation::xocl_bo_p2p(sBO) && xclemulation::xocl_bo_dev_only(dBO)) { unsigned char* host_only_buffer = (unsigned char*)(sBO->buf) + src_offset; if (xclCopyBufferHost2Device(dBO->base, (void*)host_only_buffer, size, dst_offset, dBO->topology) != size) { return -1; } } // source buffer is device_only and destination buffer is host_only else if (isHostOnlyBuffer(dBO) && !xclemulation::xocl_bo_p2p(dBO) && xclemulation::xocl_bo_dev_only(sBO)) { unsigned char* host_only_buffer = (unsigned char*)(dBO->buf) + dst_offset; if (xclCopyBufferDevice2Host((void*)host_only_buffer, sBO->base, size, src_offset, sBO->topology) != size) { return -1; } }// source and destination buffers are device_only else if (!isHostOnlyBuffer(sBO) && !isHostOnlyBuffer(dBO) && (dBO->fd < 0) && (sBO->fd < 0)) { unsigned char temp_buffer[size]; // copy data from source buffer to temp buffer if (xclCopyBufferDevice2Host((void*)temp_buffer, sBO->base, size, src_offset, sBO->topology) != size) { std::cerr << "ERROR: copy buffer from device to host failed " << std::endl; return -1; } // copy data from temp buffer to destination buffer if (xclCopyBufferHost2Device(dBO->base, (void*)temp_buffer, size, dst_offset, dBO->topology) != size) { std::cerr << "ERROR: copy buffer from host to device failed " << std::endl; return -1; } } else if((sBO->fd >=0) && (dBO->fd >= 0)) { //Both source & destination P2P buffer // CR-1113695 Copy data from source P2P to Dest P2P unsigned char temp_buffer[size]; int bytes_read = read(sBO->fd, temp_buffer, size); if (bytes_read) { if (mLogStream.is_open()) { mLogStream << __func__ << ", data read successfully from the src fd to local buffer." << std::endl; } } int bytes_write = write(dBO->fd, temp_buffer, size); if (bytes_write) { if (mLogStream.is_open()) { mLogStream << __func__ << ", data written successfully from local buffer to dest fd." << std::endl; } } } else if(dBO->fd >= 0){ //destination p2p buffer // CR-1113695 Copy data from temp buffer to exported fd unsigned char temp_buffer[size]; if (xclCopyBufferDevice2Host((void*)temp_buffer, sBO->base, size, src_offset, sBO->topology) != size) { std::cerr << "ERROR: copy buffer from device to host failed " << std::endl; return -1; } int bytes_write = write(dBO->fd, temp_buffer, size); if (bytes_write) { if (mLogStream.is_open()) { mLogStream << __func__ << ", data written successfully from local buffer to dest fd." << std::endl; } } } else if (sBO->fd >= 0) { //source p2p buffer // CR-1112934 Copy data from exported fd to temp buffer using read API unsigned char temp_buffer[size]; int bytes_read = read(sBO->fd, temp_buffer, size); if (bytes_read) { if (mLogStream.is_open()) { mLogStream << __func__ << ", data read successfully from the src fd to local buffer." << std::endl; } } // copy data from temp buffer to destination buffer if (xclCopyBufferHost2Device(dBO->base, (void*)temp_buffer, size, dst_offset, dBO->topology) != size) { std::cerr << "ERROR: copy buffer from host to device failed " << std::endl; return -1; } } else{ std::cerr << "ERROR: Copy buffer from source to destination failed" << std::endl; return -1; } PRINTENDFUNC; return 0; } /***************************************************************************************/ /******************************** xclMapBO *********************************************/ void *HwEmShim::xclMapBO(unsigned int boHandle, bool write) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , " << write << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if (!bo) { PRINTENDFUNC; return nullptr; } std::string sFileName = bo->filename; if(!sFileName.empty() ) // In case of peer-to-peer { int fd = open(sFileName.c_str(), (O_CREAT | O_RDWR), 0666); if (fd == -1) { printf("Error opening exported BO file.\n"); return nullptr; }; char* data = (char*) mmap(0, bo->size , PROT_READ |PROT_WRITE |PROT_EXEC , MAP_SHARED, fd, 0); if(!data) return nullptr; int rf = ftruncate(fd, bo->size); if(rf == -1) { close(fd); munmap(data,bo->size); return nullptr; } mFdToFileNameMap [fd] = std::make_tuple(sFileName,bo->size,(void*)data, bo->flags); bo->buf = data; PRINTENDFUNC; return data; } void *pBuf=nullptr; if (posix_memalign(&pBuf, getpagesize(), bo->size)) { if (mLogStream.is_open()) mLogStream << "posix_memalign failed" << std::endl; pBuf=nullptr; return pBuf; } memset(pBuf, 0, bo->size); bo->buf = pBuf; //For Slave Bridge scenario, maintaining the map for base vs pBuf pointer if (isHostOnlyBuffer(bo)) { mHostOnlyMemMap[bo->base] = std::make_pair(pBuf, bo->size); } PRINTENDFUNC; return pBuf; } int HwEmShim::xclUnmapBO(unsigned int boHandle, void* addr) { std::lock_guard<std::mutex> lk(mApiMtx); auto bo = xclGetBoByHandle(boHandle); return bo ? munmap(addr, bo->size) : -1; } /**************************************************************************************/ /******************************** xclSyncBO *******************************************/ int HwEmShim::xclSyncBO(unsigned int boHandle, xclBOSyncDirection dir, size_t size, size_t offset) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , " << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) { PRINTENDFUNC; return -1; } int returnVal = 0; if (!isHostOnlyBuffer(bo)) { // bypassed the xclCopyBufferDevice2Host/Host2Device RPC calls for Slave Bridge (host only buffer scenario) void* buffer = bo->userptr ? bo->userptr : bo->buf; if (dir == XCL_BO_SYNC_BO_TO_DEVICE) { if (xclCopyBufferHost2Device(bo->base, buffer, size, offset, bo->topology) != size) { returnVal = EIO; } } else { if (xclCopyBufferDevice2Host(buffer, bo->base, size, offset, bo->topology) != size) { returnVal = EIO; } } } PRINTENDFUNC; return returnVal; } /***************************************************************************************/ /******************************** xclFreeBO *******************************************/ void HwEmShim::xclFreeBO(unsigned int boHandle) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << std::endl; } auto it = mXoclObjMap.find(boHandle); if(it == mXoclObjMap.end()) { PRINTENDFUNC; return; } xclemulation::drm_xocl_bo* bo = (*it).second;; if(bo) { bool bSendToSim = true; if(bo->flags & XCL_BO_FLAGS_EXECBUF) bSendToSim = false; if(bo->chunks.size()) { for(auto it: bo->chunks) xclFreeDeviceBuffer(it.first,bSendToSim); } else { xclFreeDeviceBuffer(bo->base, bSendToSim); } mXoclObjMap.erase(it); } PRINTENDFUNC; } /***************************************************************************************/ /******************************** xclWriteBO *******************************************/ size_t HwEmShim::xclWriteBO(unsigned int boHandle, const void *src, size_t size, size_t seek) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , "<< src <<" , "<< size << ", " << seek << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) { PRINTENDFUNC; return -1; } size_t returnVal = 0; if (xclCopyBufferHost2Device(bo->base, src, size, seek, bo->topology) != size) { returnVal = EIO; } PRINTENDFUNC; return returnVal; } /***************************************************************************************/ /******************************** xclReadBO *******************************************/ size_t HwEmShim::xclReadBO(unsigned int boHandle, void *dst, size_t size, size_t skip) { std::lock_guard<std::mutex> lk(mApiMtx); if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << std::hex << boHandle << " , "<< dst <<" , "<< size << ", " << skip << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(boHandle); if(!bo) { PRINTENDFUNC; return -1; } size_t returnVal = 0; if (xclCopyBufferDevice2Host(dst, bo->base, size, skip, bo->topology) != size) { returnVal = EIO; } PRINTENDFUNC; return returnVal; } /***************************************************************************************/ int HwEmShim::xclExecBuf(unsigned int cmdBO) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << cmdBO << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(cmdBO); int ret=-1; if(xclemulation::config::getInstance()->isNewMbscheduler()) { if(!m_scheduler || !bo) { PRINTENDFUNC; return ret; } ret = m_scheduler->add_exec_buffer(bo); PRINTENDFUNC; return ret; } else if (xclemulation::config::getInstance()->isXgqMode()) { if (!m_xgq || !bo) { PRINTENDFUNC; return ret; } ret = m_xgq->add_exec_buffer(bo); PRINTENDFUNC; return ret; } else { if(!mMBSch || !bo) { PRINTENDFUNC; return ret; } ret = mMBSch->add_exec_buffer(mCore, bo); PRINTENDFUNC; } return ret; } /* * xclExecBuf() */ int HwEmShim::xclExecBuf(unsigned int cmdBO, size_t num_bo_in_wait_list, unsigned int *bo_wait_list) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << cmdBO << ", " << num_bo_in_wait_list << ", " << bo_wait_list << std::endl; } xclemulation::drm_xocl_bo* bo = xclGetBoByHandle(cmdBO); xcl_LogMsg(XRT_INFO, "", "%s, cmdBO: %d, num_bo_in_wait_list: %d, bo_wait_list: %d", __func__, cmdBO, num_bo_in_wait_list, bo_wait_list); if (num_bo_in_wait_list > MAX_DEPS) { xcl_LogMsg(XRT_ERROR, "", "%s, Incorrect argument. Max num of BOs in wait_list: %d", __func__, MAX_DEPS); return -EINVAL; } /*int ret; unsigned int bwl[8] = {0}; std::memcpy(bwl,bo_wait_list,num_bo_in_wait_list*sizeof(unsigned int)); drm_xocl_execbuf exec = {0, cmdBO, bwl[0],bwl[1],bwl[2],bwl[3],bwl[4],bwl[5],bwl[6],bwl[7]}; ret = mDev->ioctl(mUserHandle, DRM_IOCTL_XOCL_EXECBUF, &exec); return ret ? -errno : ret;*/ int ret=-1; if(xclemulation::config::getInstance()->isNewMbscheduler()) { if(!m_scheduler || !bo) { PRINTENDFUNC; return ret; } ret = m_scheduler->add_exec_buffer(bo); PRINTENDFUNC; } else { ret = mMBSch->add_exec_buffer(mCore, bo); PRINTENDFUNC; } return ret; } int HwEmShim::xclRegisterEventNotify(unsigned int userInterrupt, int fd) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << userInterrupt <<", "<< fd << std::endl; } PRINTENDFUNC; return 0; } int HwEmShim::xclExecWait(int timeoutMilliSec) { if (mLogStream.is_open()) { // mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << timeoutMilliSec << std::endl; } unsigned int tSec = 0; static bool bConfig = true; tSec = timeoutMilliSec/1000; if(bConfig) { tSec = timeoutMilliSec/100; bConfig = false; } sleep(tSec); //PRINTENDFUNC; return 1; } ssize_t HwEmShim::xclUnmgdPwrite(unsigned flags, const void *buf, size_t count, uint64_t offset) { if (flags) return -EINVAL; return xclCopyBufferHost2Device(offset, buf, count, 0 ,0); } ssize_t HwEmShim::xclUnmgdPread(unsigned flags, void *buf, size_t count, uint64_t offset) { if (flags) return -EINVAL; return xclCopyBufferDevice2Host(buf, offset, count, 0 , 0); } int HwEmShim::xclGetDebugIPlayoutPath(char* layoutPath, size_t size) { // get path of the debug_ip_layout (in binary format) created in the HW Emu run directory if(mRunDeviceBinDir.empty()) return -1; std::string debugIPlayoutPath = mRunDeviceBinDir + "/debug_ip_layout"; if(debugIPlayoutPath.size() >= size) return -1; strncpy(layoutPath, debugIPlayoutPath.c_str(), size); return 0; } int HwEmShim::xclGetTraceBufferInfo(uint32_t nSamples, uint32_t& traceSamples, uint32_t& traceBufSz) { uint32_t bytesPerSample = (XPAR_AXI_PERF_MON_0_TRACE_WORD_WIDTH / 8); traceBufSz = MAX_TRACE_NUMBER_SAMPLES * bytesPerSample; /* Buffer size in bytes */ traceSamples = nSamples; return 0; } int HwEmShim::xclReadTraceData(void* traceBuf, uint32_t traceBufSz, uint32_t numSamples, uint64_t ipBaseAddress, uint32_t& wordsPerSample) { // Create trace buffer on host (requires alignment) const int traceBufWordSz = traceBufSz / 4; // traceBufSz is in number of bytes uint32_t size = 0; wordsPerSample = (XPAR_AXI_PERF_MON_0_TRACE_WORD_WIDTH / 32); uint32_t numWords = numSamples * wordsPerSample; // alignas is defined in c++11 #ifndef _WINDOWS /* Alignment is limited to 16 by PPC64LE : so , should it be alignas(16) uint32_t hostbuf[traceBufSzInWords]; */ alignas(AXI_FIFO_RDFD_AXI_FULL) uint32_t hostbuf[traceBufWordSz]; #else xrt_core::AlignedAllocator<uint32_t> alignedBuffer(AXI_FIFO_RDFD_AXI_FULL, traceBufWordSz); uint32_t* hostbuf = alignedBuffer.getBuffer(); #endif // Now read trace data memset((void *)hostbuf, 0, traceBufSz); // Iterate over chunks // NOTE: AXI limits this to 4K bytes per transfer uint32_t chunkSizeWords = 256 * wordsPerSample; if (chunkSizeWords > 1024) chunkSizeWords = 1024; uint32_t chunkSizeBytes = 4 * chunkSizeWords; uint32_t words=0; // Read trace a chunk of bytes at a time if (numWords > chunkSizeWords) { for (; words < (numWords-chunkSizeWords); words += chunkSizeWords) { if(mLogStream.is_open()) mLogStream << __func__ << ": reading " << chunkSizeBytes << " bytes from 0x" << std::hex << ipBaseAddress /*fifoReadAddress[0] or AXI_FIFO_RDFD*/ << " and writing it to 0x" << (void *)(hostbuf + words) << std::dec << std::endl; xclUnmgdPread(0 /*flags*/, (void *)(hostbuf + words) /*buf*/, chunkSizeBytes /*count*/, ipBaseAddress /*offset : or AXI_FIFO_RDFD*/); size += chunkSizeBytes; } } // Read remainder of trace not divisible by chunk size if (words < numWords) { chunkSizeBytes = 4 * (numWords - words); if(mLogStream.is_open()) { mLogStream << __func__ << ": reading " << chunkSizeBytes << " bytes from 0x" << std::hex << ipBaseAddress /*fifoReadAddress[0]*/ << " and writing it to 0x" << (void *)(hostbuf + words) << std::dec << std::endl; } xclUnmgdPread(0 /*flags*/, (void *)(hostbuf + words) /*buf*/, chunkSizeBytes /*count*/, ipBaseAddress /*offset : or AXI_FIFO_RDFD*/); size += chunkSizeBytes; } if(mLogStream.is_open()) mLogStream << __func__ << ": done reading " << size << " bytes " << std::endl; memcpy((char*)traceBuf, (char*)hostbuf, traceBufSz); return size; } double HwEmShim::xclGetDeviceClockFreqMHz() { //return 1.0; double clockSpeed; //300.0 MHz clockSpeed = 300.0; return clockSpeed; } // For PCIe gen 3x16 or 4x8: // Max BW = 16.0 * (128b/130b encoding) = 15.75385 GB/s double HwEmShim::xclGetHostReadMaxBandwidthMBps() { return 15753.85; } // For PCIe gen 3x16 or 4x8: // Max BW = 16.0 * (128b/130b encoding) = 15.75385 GB/s double HwEmShim::xclGetHostWriteMaxBandwidthMBps() { return 15753.85; } // For DDR4: Typical Max BW = 19.25 GB/s double HwEmShim::xclGetKernelReadMaxBandwidthMBps() { return 19250.00; } // For DDR4: Typical Max BW = 19.25 GB/s double HwEmShim::xclGetKernelWriteMaxBandwidthMBps() { return 19250.00; } uint32_t HwEmShim::getPerfMonNumberSlots(xclPerfMonType type) { if (type == XCL_PERF_MON_MEMORY) return mMemoryProfilingNumberSlots; if (type == XCL_PERF_MON_ACCEL) return mAccelProfilingNumberSlots; if (type == XCL_PERF_MON_STALL) return mStallProfilingNumberSlots; if (type == XCL_PERF_MON_HOST) return 1; if (type == XCL_PERF_MON_STR) return mStreamProfilingNumberSlots; return 0; } // Get slot name void HwEmShim::getPerfMonSlotName(xclPerfMonType type, uint32_t slotnum, char* slotName, uint32_t length) { std::string str = ""; if (type == XCL_PERF_MON_MEMORY) { str = (slotnum < XAIM_MAX_NUMBER_SLOTS) ? mPerfMonSlotName[slotnum] : ""; } if (type == XCL_PERF_MON_ACCEL) { str = (slotnum < XAM_MAX_NUMBER_SLOTS) ? mAccelMonSlotName[slotnum] : ""; } if (type == XCL_PERF_MON_STR) { str = (slotnum < XASM_MAX_NUMBER_SLOTS) ? mStreamMonSlotName[slotnum] : ""; } if(str.length() < length) { strncpy(slotName, str.c_str(), length); } else { strncpy(slotName, str.c_str(), length-1); slotName[length-1] = '\0'; } } /********************************************** QDMA APIs IMPLEMENTATION START **********************************************/ /* * xclCreateWriteQueue() */ int HwEmShim::xclCreateWriteQueue(xclQueueContext *q_ctx, uint64_t *q_hdl) { if (mLogStream.is_open()) mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; uint64_t q_handle = 0; xclCreateQueue_RPC_CALL(xclCreateQueue,q_ctx,true); if(q_handle <= 0) { if (mLogStream.is_open()) mLogStream << " unable to create write queue "<<std::endl; PRINTENDFUNC; return -1; } *q_hdl = q_handle; PRINTENDFUNC; return 0; } /* * xclCreateReadQueue() */ int HwEmShim::xclCreateReadQueue(xclQueueContext *q_ctx, uint64_t *q_hdl) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } uint64_t q_handle = 0; xclCreateQueue_RPC_CALL(xclCreateQueue,q_ctx,false); if(q_handle <= 0) { if (mLogStream.is_open()) mLogStream << " unable to create read queue "<<std::endl; PRINTENDFUNC; return -1; } *q_hdl = q_handle; PRINTENDFUNC; return 0; } /* * xclDestroyQueue() */ int HwEmShim::xclDestroyQueue(uint64_t q_hdl) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } uint64_t q_handle = q_hdl; bool success = false; xclDestroyQueue_RPC_CALL(xclDestroyQueue, q_handle); if(!success) { if (mLogStream.is_open()) mLogStream <<" unable to destroy the queue"<<std::endl; PRINTENDFUNC; return -1; } PRINTENDFUNC; return 0; } /* * xclWriteQueue() */ ssize_t HwEmShim::xclWriteQueue(uint64_t q_hdl, xclQueueRequest *wr) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } bool eot = false; if(wr->flag & XCL_QUEUE_REQ_EOT) eot = true; bool nonBlocking = false; if (wr->flag & XCL_QUEUE_REQ_NONBLOCKING) { std::map<uint64_t,uint64_t> vaLenMap; for (unsigned i = 0; i < wr->buf_num; i++) { //vaLenMap[wr->bufs[i].va] = wr->bufs[i].len; vaLenMap[wr->bufs[i].va] = 0;//for write we should not read the data back } mReqList.push_back(std::make_tuple(mReqCounter, wr->priv_data, vaLenMap)); nonBlocking = true; } uint64_t fullSize = 0; for (unsigned i = 0; i < wr->buf_num; i++) { xclWriteQueue_RPC_CALL(xclWriteQueue,q_hdl, wr->bufs[i].va, wr->bufs[i].len); fullSize += written_size; } PRINTENDFUNC; mReqCounter++; return fullSize; } /* * xclReadQueue() */ ssize_t HwEmShim::xclReadQueue(uint64_t q_hdl, xclQueueRequest *rd) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } bool eot = false; if(rd->flag & XCL_QUEUE_REQ_EOT) eot = true; bool nonBlocking = false; if (rd->flag & XCL_QUEUE_REQ_NONBLOCKING) { nonBlocking = true; std::map<uint64_t,uint64_t> vaLenMap; for (unsigned i = 0; i < rd->buf_num; i++) { vaLenMap[rd->bufs[i].va] = rd->bufs[i].len; } mReqList.push_back(std::make_tuple(mReqCounter,rd->priv_data, vaLenMap)); } void *dest; uint64_t fullSize = 0; for (unsigned i = 0; i < rd->buf_num; i++) { dest = (void *)rd->bufs[i].va; uint64_t read_size = 0; do { xclReadQueue_RPC_CALL(xclReadQueue,q_hdl, dest , rd->bufs[i].len); } while (read_size == 0 && !nonBlocking); fullSize += read_size; } mReqCounter++; PRINTENDFUNC; return fullSize; } /* * xclPollCompletion */ int HwEmShim::xclPollCompletion(int min_compl, int max_compl, xclReqCompletion *comps, int* actual, int timeout) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << " , "<< max_compl <<", "<<min_compl<<" ," << *actual <<" ," << timeout << std::endl; } xclemulation::TIMEOUT_SCALE timeout_scale=xclemulation::config::getInstance()->getTimeOutScale(); if(timeout_scale==xclemulation::TIMEOUT_SCALE::NA) { std::string dMsg = "WARNING: [HW-EMU 10] xclPollCompletion : Timeout is not enabled in emulation by default.Please use xrt.ini (key: timeout_scale=ms|sec|min) to enable"; logMessage(dMsg, 0); } xclemulation::ApiWatchdog watch(timeout_scale,timeout); watch.reset(); *actual = 0; while(*actual < min_compl) { std::list<std::tuple<uint64_t ,void*, std::map<uint64_t,uint64_t> > >::iterator it = mReqList.begin(); while ( it != mReqList.end() ) { unsigned numBytesProcessed = 0; uint64_t reqCounter = std::get<0>(*it); void* priv_data = std::get<1>(*it); std::map<uint64_t,uint64_t>vaLenMap = std::get<2>(*it); xclPollCompletion_RPC_CALL(xclPollCompletion,reqCounter,vaLenMap); if(numBytesProcessed > 0) { comps[*actual].priv_data = priv_data; comps[*actual].nbytes = numBytesProcessed; (*actual)++; mReqList.erase(it++); if(*actual >= max_compl) { PRINTENDFUNC; return (*actual); } } else { it++; } if(watch.isTimeout()) { PRINTENDFUNC; if (*actual <=0) { return -ETIMEDOUT; } else { return *actual; } } } } PRINTENDFUNC; return (*actual); } /* * xclAllocQDMABuf() */ void * HwEmShim::xclAllocQDMABuf(size_t size, uint64_t *buf_hdl) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } void *pBuf=nullptr; if (posix_memalign(&pBuf, getpagesize(), size)) { if (mLogStream.is_open()) mLogStream << "posix_memalign failed" << std::endl; pBuf=nullptr; return pBuf; } memset(pBuf, 0, size); return pBuf; } /* * xclFreeQDMABuf() */ int HwEmShim::xclFreeQDMABuf(uint64_t buf_hdl) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << std::endl; } PRINTENDFUNC; return 0;//TODO } int HwEmShim::xcl_LogMsg(xrtLogMsgLevel level, const char* tag, const char* format, ...) { va_list args; va_start(args, format); int ret = xclLogMsg(level, tag, format, args); va_end(args); return ret; } /* * xclLogMsg() */ int HwEmShim::xclLogMsg(xrtLogMsgLevel level, const char* tag, const char* format, va_list args1) { int len = std::vsnprintf(nullptr, 0, format, args1); if (len < 0) { //illegal arguments std::string err_str = "ERROR: Illegal arguments in log format string. "; err_str.append(std::string(format)); xrt_core::message::send((xrt_core::message::severity_level)level, tag, err_str.c_str()); return len; } len++; //To include null terminator std::vector<char> buf(len); len = std::vsnprintf(buf.data(), len, format, args1); if (len < 0) { //error processing arguments std::string err_str = "ERROR: When processing arguments in log format string. "; err_str.append(std::string(format)); xrt_core::message::send((xrt_core::message::severity_level)level, tag, err_str.c_str()); return len; } xrt_core::message::send((xrt_core::message::severity_level)level, tag, buf.data()); return 0; } void HwEmShim::closemMessengerThread() { if (mMessengerThreadStarted) { mMessengerThread.join(); mMessengerThreadStarted = false; } if (mHostMemAccessThreadStarted) { mHostMemAccessThreadStarted = false; if (mHostMemAccessThread.joinable()) { mHostMemAccessThread.join(); } } } //CU register space for xclRegRead/Write() int HwEmShim::xclRegRW(bool rd, uint32_t cu_index, uint32_t offset, uint32_t *datap) { if (mLogStream.is_open()) { mLogStream << __func__ << ", " << std::this_thread::get_id() << ", " << "CU Idx : " << cu_index << " Offset : " << offset << " Datap : " << (*datap) << std::endl; } // get sorted cu addresses to match up with cu_index const auto& cuidx2addr = mCoreDevice->get_cus(); if (cu_index >= cuidx2addr.size()) { std::string strMsg = "ERROR: [HW-EMU 20] xclRegRW - invalid CU index: " + std::to_string(cu_index); logMessage(strMsg); return -EINVAL; } uint64_t cuAddRange = 64 * 1024; for (auto cuInfo : mCURangeMap) { std::string instName = cuInfo.first; int cuIdx = static_cast<int>(cu_index); int tmpCuIdx = xclIPName2Index(instName.c_str()); if (tmpCuIdx == cuIdx) { cuAddRange = cuInfo.second; } } if (offset >= cuAddRange || (offset & (sizeof(uint32_t) - 1)) != 0) { std::string strMsg = "ERROR: [HW-EMU 21] xclRegRW - invalid CU offset: " + std::to_string(offset); logMessage(strMsg); return -EINVAL; } std::array<char, REG_BUFF_SIZE> buff; uint64_t baseAddr = cuidx2addr[cu_index] + offset; if (rd) { if (xclRead(XCL_ADDR_KERNEL_CTRL, baseAddr, buff.data(), REG_BUFF_SIZE) != REG_BUFF_SIZE) { std::string strMsg = "ERROR: [HW-EMU 22] xclRegRW - xclRead failed for CU: " + std::to_string(cu_index); logMessage(strMsg); return -EINVAL; } auto tmp_buff = reinterpret_cast<uint32_t*>(buff.data()); *datap = tmp_buff[0]; } else { uint32_t * tmp_buff = reinterpret_cast<uint32_t*>(buff.data()); tmp_buff[0] = *datap; if (xclWrite(XCL_ADDR_KERNEL_CTRL, baseAddr, tmp_buff, REG_BUFF_SIZE) != REG_BUFF_SIZE) { std::string strMsg = "ERROR: [HW-EMU 23] xclRegRW - xclWrite failed for CU: " + std::to_string(cu_index); logMessage(strMsg); return -EINVAL; } } return 0; } int HwEmShim::xclRegRead(uint32_t cu_index, uint32_t offset, uint32_t *datap) { return xclRegRW(true, cu_index, offset, datap); } int HwEmShim::xclRegWrite(uint32_t cu_index, uint32_t offset, uint32_t data) { return xclRegRW(false, cu_index, offset, &data); } //Get CU index from IP_LAYOUT section for corresponding kernel name int HwEmShim::xclIPName2Index(const char *name) { //Get IP_LAYOUT buffer from xclbin auto buffer = mCoreDevice->get_axlf_section(IP_LAYOUT); return xclemulation::getIPName2Index(name, buffer.first); } volatile bool HwEmShim::get_mHostMemAccessThreadStarted() { return mHostMemAccessThreadStarted; } volatile void HwEmShim::set_mHostMemAccessThreadStarted(bool val) { mHostMemAccessThreadStarted = val; } /********************************************** QDMA APIs IMPLEMENTATION END**********************************************/ /**********************************************HAL2 API's END HERE **********************************************/ /********************************************** Q2H_helper class implementation starts **********************************************/ /** * Function: device2xrt_rd_trans_cb * Description : Its a Read request from Device to HOST Buffer Call back function which gets read Address, * size and Data pointer to be filled. * Arguments: * 1. addr: Read request addr * 2. data_ptr: container of read data which gets filled by Host. size of this container * is = size rgument of this function * 3. size: size of read request * Return Value: This funtion returns boolean value. Incase of successful read from Host * it will return true or else false. * **/ bool HwEmShim::device2xrt_rd_trans_cb(unsigned long int addr, void* const data_ptr,unsigned long int size) { auto itStart = mHostOnlyMemMap.begin(); auto itEnd = mHostOnlyMemMap.end(); while (itStart != itEnd) { uint64_t baseAddress = (*itStart).first; std::pair<void*, uint64_t> osAddressSizePair = (*itStart).second; void* startOSAddress = osAddressSizePair.first; uint64_t buf_size = osAddressSizePair.second; if (addr >= baseAddress && addr < baseAddress + buf_size) { unsigned char* finalOsAddress = (unsigned char*)startOSAddress + (addr - baseAddress); if ((addr + size) > (baseAddress + buf_size)) { std::string dMsg = "ERROR: [HW-EMU 24] Host Memory - Accessing the invalid address range which is not within the boundary. Valid address range is " + std::to_string(baseAddress) + " - " + std::to_string(baseAddress + buf_size) + ". Whereas requested address range is " + std::to_string(addr) + " - " + std::to_string(addr+size); logMessage(dMsg, 0); return false; } std::memcpy((unsigned char*)data_ptr, finalOsAddress, size); break; } itStart++; } return true; } /** * Function: device2xrt_wr_trans_cb * Description : Its a Write request from Device to HOST Buffer Call back function which gets Write address, * size and Data pointer of written data. * Arguments: * 1. addr: Read request addr * 2. data_ptr: container which holds write data which is already filled by deivce. size of this container * is = size rgument of this function * 3. size: size of Write request * Return Value: This funtion returns boolean value. Incase of successful write to Host Buffer * it will return true or else false. * **/ bool HwEmShim::device2xrt_wr_trans_cb(unsigned long int addr, void const* data_ptr,unsigned long int size) { auto itStart = mHostOnlyMemMap.begin(); auto itEnd = mHostOnlyMemMap.end(); while (itStart != itEnd) { uint64_t baseAddress = (*itStart).first; std::pair<void*, uint64_t> osAddressSizePair = (*itStart).second; void* startOSAddress = osAddressSizePair.first; uint64_t buf_size = osAddressSizePair.second; if (addr >= baseAddress && addr < baseAddress + buf_size) { unsigned char* finalOsAddress = (unsigned char*)startOSAddress + (addr - baseAddress); if ((addr + size) > (baseAddress + buf_size)) { std::string dMsg = "ERROR: [HW-EMU 25] Host Memory - Accessing the invalid address range which is not within the boundary. Valid address range is " + std::to_string(baseAddress) + " - " + std::to_string(baseAddress + buf_size) + ". Whereas requested address range is " + std::to_string(addr) + " - " + std::to_string(addr + size); logMessage(dMsg, 0); return false; } std::memcpy(finalOsAddress, (unsigned char*)data_ptr, size); break; } itStart++; } return true; } bool HwEmShim::device2xrt_irq_trans_cb(uint32_t,unsigned long int) { // TODO: We need to return a ERROR here as we are not supporting this. Its helps users to get notified return true; } Q2H_helper :: Q2H_helper(xclhwemhal2::HwEmShim* _inst) { header = std::make_unique<call_packet_info>(); response_header = std::make_unique<response_packet_info>(); inst = _inst; Q2h_sock = NULL; header->set_size(0); header->set_xcl_api(0); response_header->set_size(0); response_header->set_xcl_api(0); #if GOOGLE_PROTOBUF_VERSION < 3006001 i_len = header->ByteSize(); ri_len = response_header->ByteSize(); #else i_len = header->ByteSizeLong(); ri_len = response_header->ByteSizeLong(); #endif } Q2H_helper::~Q2H_helper() { delete Q2h_sock; Q2h_sock = 0; } /** * Pooling on socket for any memory or interrupt requests from SIM_QDMA * */ int Q2H_helper::poolingon_Qdma() { //Getting incoming header packet from sim_qdma auto raw_header = std::make_unique<char[]>(i_len); int r = Q2h_sock->sk_read((void*)raw_header.get(), i_len); if (r <= 0) { return r; } assert(i_len == (uint32_t)r); //deserializing protobuf message header->ParseFromArray((void*)raw_header.get(), i_len); if (header->xcl_api() == xclClose_n) { return -1; } //Getting incoming header packet from sim_qdma auto raw_payload = std::make_unique<char[]>(header->size()); r = Q2h_sock->sk_read((void*)raw_payload.get(), header->size()); assert((uint32_t)r == header->size()); //processing payload and sending the response message back to sim_qdma if (header->xcl_api() == xclQdma2HostReadMem_n) { xclSlaveReadReq_call payload; xclSlaveReadReq_response response_payload; payload.ParseFromArray((void*)raw_payload.get(), r); auto data = std::make_unique<char[]>(payload.size()); bool resp = inst->device2xrt_rd_trans_cb((unsigned long int)payload.addr(),(void* const)data.get(),(unsigned long int)payload.size()); response_payload.set_valid(resp); response_payload.set_data((void*)data.get(),payload.size()); #if GOOGLE_PROTOBUF_VERSION < 3006001 auto r_len = response_payload.ByteSize(); #else auto r_len = response_payload.ByteSizeLong(); #endif SEND_RESP2QDMA() } if (header->xcl_api() == xclQdma2HostWriteMem_n) { xclSlaveWriteReq_call payload; xclSlaveWriteReq_response response_payload; payload.ParseFromArray((void*)raw_payload.get(), r); bool resp = inst->device2xrt_wr_trans_cb((unsigned long int)payload.addr(),(void const*)payload.data().c_str(),(unsigned long int)payload.size()); response_payload.set_valid(resp); #if GOOGLE_PROTOBUF_VERSION < 3006001 auto r_len = response_payload.ByteSize(); #else auto r_len = response_payload.ByteSizeLong(); #endif SEND_RESP2QDMA() } if (header->xcl_api() == xclQdma2HostInterrupt_n) { xclInterruptOccured_call payload; xclInterruptOccured_response response_payload; payload.ParseFromArray((void*)raw_payload.get(), r); uint32_t interrupt_line = payload.interrupt_line(); bool resp = inst->device2xrt_irq_trans_cb(interrupt_line,4); response_payload.set_valid(resp); #if GOOGLE_PROTOBUF_VERSION < 3006001 auto r_len = response_payload.ByteSize(); #else auto r_len = response_payload.ByteSizeLong(); #endif SEND_RESP2QDMA() } return 1; } bool Q2H_helper::connect_sock() { std::string sock_name; if (getenv("EMULATION_SOCKETID")) { sock_name = "D2X_unix_sock_" + std::string(getenv("EMULATION_SOCKETID")); } else { sock_name = "D2X_unix_sock"; } if(Q2h_sock == NULL) { Q2h_sock = new unix_socket("EMULATION_SOCKETID", sock_name, 5, false); } else if (!Q2h_sock->server_started) { Q2h_sock->start_server(5,false); } return Q2h_sock->server_started; } void hostMemAccessThread(xclhwemhal2::HwEmShim* inst) { inst->set_mHostMemAccessThreadStarted(true); auto mq2h_helper_ptr = std::make_unique<Q2H_helper>(inst); bool sock_ret = false; int count = 0; while(inst->get_mHostMemAccessThreadStarted() && !sock_ret && count < 71){ sock_ret = mq2h_helper_ptr->connect_sock(); count++; } int r =0; while(inst->get_mHostMemAccessThreadStarted() && r >= 0){ try { if (!inst->get_simulator_started()) return; r = mq2h_helper_ptr->poolingon_Qdma(); } catch(int e) { std::cout << " Exception during socket communitication between SIM_QDMA ---> HE_EMU driver.." << std::endl; } } } /********************************************** Q2H_helper class implementation Ends **********************************************/ } // end namespace xclhwemhal2
#include "CppUTest/TestHarness.h" #include "timelib.h" TEST_GROUP(j2000) { }; TEST(j2000, J2000Epoch) { double d = 946728000; double js = timelib_ts_to_j2000(d); DOUBLES_EQUAL(0, js, 0.0000001); } TEST(j2000, August2017) { double d = 1502755200; double js = timelib_ts_to_j2000(d); DOUBLES_EQUAL(6435.5, js, 0.0000001); } TEST_GROUP(julian_day) { }; TEST(julian_day, JulianDayEpoch) { double d = -210866760000; double js = timelib_ts_to_julianday(d); DOUBLES_EQUAL(0, js, 0.0000001); } TEST(j2000, JulianDateExampleFromWikipedia) { double d = 1357000200; double js = timelib_ts_to_julianday(d); DOUBLES_EQUAL(2456293.520833, js, 0.000001); } TEST(julian_day, August2017) { double d = 1502755200; double js = timelib_ts_to_julianday(d); DOUBLES_EQUAL(2457980.5, js, 0.0000001); }
#ifndef SPROUT_FUNCTIONAL_BIND2ND_HPP #define SPROUT_FUNCTIONAL_BIND2ND_HPP #include <sprout/config.hpp> #include <sprout/functional/base.hpp> namespace sprout { // Copyright (C) 2011 RiSK (sscrisk) // D.9.3 Class template binder2nd template<typename Fn> class binder2nd : public sprout::unary_function<typename Fn::first_argument_type, typename Fn::result_type> { protected: Fn op; typename Fn::second_argument_type value; public: SPROUT_CONSTEXPR binder2nd(Fn const& x, typename Fn::second_argument_type const& y) : op(x), value(y) {} SPROUT_CONSTEXPR typename Fn::result_type operator()(typename Fn::first_argument_type const& x) const { return op(x, value); } }; // D.9.4 bind2nd template<typename Fn, typename T> inline SPROUT_CONSTEXPR sprout::binder2nd<Fn> bind2nd(Fn const& op, T const& x) { return sprout::binder2nd<Fn>(op, typename Fn::second_argument_type(x)); } } // namespace sprout #endif // #ifndef SPROUT_FUNCTIONAL_BIND2ND_HPP
/* * This file contains code from "C++ Primer, Fifth Edition", by Stanley B. * Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: * * "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo." * * * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." * * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address: * * Pearson Education, Inc. * Rights and Permissions Department * One Lake Street * Upper Saddle River, NJ 07458 * Fax: (201) 236-3290 */ #include "debug_rep.h" #include <string> using std::string; #include <vector> using std::vector; #include <iostream> using std::cout; using std::endl; int main() { int temp[] = {1,2,3,4,5,6,7,8,9}; vector<int> v(temp, temp + sizeof(temp)/sizeof(*temp)); string s("hi"); cout << debug_rep(v) << endl; cout << debug_rep(s) << endl; cout << debug_rep("hi") << endl; cout << debug_rep(&v[0]) << endl; cout << debug_rep(&s) << endl; const string *sp = &s; cout << debug_rep(sp) << endl; char carr[] = "bye"; // calls pointer version if no overloads cout << debug_rep(carr) << endl; const char *temp2[] = {"Proust", "Shakespeare", "Barth" } ; vector<string> authors(temp2, temp2 + sizeof(temp2)/sizeof(*temp2)); cout << debug_rep(authors) << endl; vector<const char*> authors2(temp2, temp2 + sizeof(temp2)/sizeof(*temp2)); cout << debug_rep(authors2) << endl; cout << debug_rep(s) << endl; s += "more stuff"; cout << debug_rep(s) << endl; s += "\\escape\"and quotes"; cout << debug_rep(s) << endl; cout << debug_rep("hi world!") << endl; // calls debug_rep(T*) s = "hi"; const char *cp = "bye"; char arr[] = "world"; cout << debug_rep(s) << endl; // calls specialization debug_rep(const string& cout << debug_rep(cp) << endl; // calls specialization debug_rep(const char* cout << debug_rep(arr) << endl;// calls specialization debug_rep(char* cout << debug_rep(&s) << endl; // calls template debug_rep(T*) return 0; }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "fuchsia/engine/browser/frame_impl.h" #include <fuchsia/ui/gfx/cpp/fidl.h> #include <lib/fpromise/result.h> #include <lib/sys/cpp/component_context.h> #include <lib/ui/scenic/cpp/view_ref_pair.h> #include <limits> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/fuchsia/fuchsia_logging.h" #include "base/fuchsia/mem_buffer_util.h" #include "base/fuchsia/process_context.h" #include "base/json/json_writer.h" #include "base/metrics/user_metrics.h" #include "base/strings/strcat.h" #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/media_session.h" #include "content/public/browser/message_port_provider.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/permission_controller_delegate.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/renderer_preferences_util.h" #include "content/public/browser/web_contents.h" #include "fuchsia/base/message_port.h" #include "fuchsia/engine/browser/accessibility_bridge.h" #include "fuchsia/engine/browser/context_impl.h" #include "fuchsia/engine/browser/event_filter.h" #include "fuchsia/engine/browser/frame_layout_manager.h" #include "fuchsia/engine/browser/frame_window_tree_host.h" #include "fuchsia/engine/browser/media_player_impl.h" #include "fuchsia/engine/browser/navigation_policy_handler.h" #include "fuchsia/engine/browser/receiver_session_client.h" #include "fuchsia/engine/browser/url_request_rewrite_type_converters.h" #include "fuchsia/engine/browser/web_engine_devtools_controller.h" #include "fuchsia/engine/common/cast_streaming.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "net/base/net_errors.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/logging/logging_utils.h" #include "third_party/blink/public/common/messaging/web_message_port.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/mojom/loader/resource_load_info.mojom.h" #include "third_party/blink/public/mojom/navigation/was_activated_option.mojom.h" #include "ui/aura/window.h" #include "ui/compositor/compositor.h" #include "ui/gfx/switches.h" #include "ui/ozone/public/ozone_switches.h" #include "ui/wm/core/base_focus_rules.h" #include "url/gurl.h" namespace { // Simulated screen bounds to use when headless rendering is enabled. constexpr gfx::Size kHeadlessWindowSize = {1, 1}; // Simulated screen bounds to use when testing the SemanticsManager. constexpr gfx::Size kSemanticsTestingWindowSize = {720, 640}; // Name of the Inspect node that holds accessibility information. constexpr char kAccessibilityInspectNodeName[] = "accessibility"; // A special value which matches all origins when specified in an origin list. constexpr char kWildcardOrigin[] = "*"; // Used for attaching popup-related metadata to a WebContents. constexpr char kPopupCreationInfo[] = "popup-creation-info"; class PopupFrameCreationInfoUserData : public base::SupportsUserData::Data { public: fuchsia::web::PopupFrameCreationInfo info; }; class FrameFocusRules : public wm::BaseFocusRules { public: FrameFocusRules() = default; FrameFocusRules(const FrameFocusRules&) = delete; FrameFocusRules& operator=(const FrameFocusRules&) = delete; ~FrameFocusRules() override = default; // wm::BaseFocusRules implementation. bool SupportsChildActivation(const aura::Window*) const override; }; bool FrameFocusRules::SupportsChildActivation(const aura::Window*) const { // TODO(crbug.com/878439): Return a result based on window properties such as // visibility. return true; } // TODO(crbug.com/1113289): Use OnLoadScriptInjectorHost's origin matching code. bool IsUrlMatchedByOriginList(const GURL& url, const std::vector<std::string>& allowed_origins) { for (const std::string& origin : allowed_origins) { if (origin == kWildcardOrigin) return true; GURL origin_url(origin); if (!origin_url.is_valid()) { DLOG(WARNING) << "Ignored invalid origin spec when checking allowed list: " << origin; continue; } if (origin_url != url.DeprecatedGetOriginAsURL()) continue; return true; } return false; } FuchsiaLogSeverity FuchsiaWebConsoleLogLevelToFxLogSeverity( fuchsia::web::ConsoleLogLevel level) { switch (level) { case fuchsia::web::ConsoleLogLevel::DEBUG: return FUCHSIA_LOG_DEBUG; case fuchsia::web::ConsoleLogLevel::INFO: return FUCHSIA_LOG_INFO; case fuchsia::web::ConsoleLogLevel::WARN: return FUCHSIA_LOG_WARNING; case fuchsia::web::ConsoleLogLevel::ERROR: return FUCHSIA_LOG_ERROR; case fuchsia::web::ConsoleLogLevel::NONE: return FUCHSIA_LOG_NONE; default: // Cope gracefully with callers setting undefined levels. DLOG(ERROR) << "Unknown log level:" << static_cast<std::underlying_type<decltype(level)>::type>( level); return FUCHSIA_LOG_NONE; } } FuchsiaLogSeverity BlinkConsoleMessageLevelToFxLogSeverity( blink::mojom::ConsoleMessageLevel level) { switch (level) { case blink::mojom::ConsoleMessageLevel::kVerbose: return FUCHSIA_LOG_DEBUG; case blink::mojom::ConsoleMessageLevel::kInfo: return FUCHSIA_LOG_INFO; case blink::mojom::ConsoleMessageLevel::kWarning: return FUCHSIA_LOG_WARNING; case blink::mojom::ConsoleMessageLevel::kError: return FUCHSIA_LOG_ERROR; } // Cope gracefully with callers setting undefined levels. DLOG(ERROR) << "Unknown log level:" << static_cast<std::underlying_type<decltype(level)>::type>( level); return FUCHSIA_LOG_NONE; } bool IsHeadless() { return base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kHeadless); } using FrameImplMap = base::small_map<std::map<content::WebContents*, FrameImpl*>>; FrameImplMap& WebContentsToFrameImplMap() { static FrameImplMap frame_impl_map; return frame_impl_map; } content::PermissionType FidlPermissionTypeToContentPermissionType( fuchsia::web::PermissionType fidl_type) { switch (fidl_type) { case fuchsia::web::PermissionType::MICROPHONE: return content::PermissionType::AUDIO_CAPTURE; case fuchsia::web::PermissionType::CAMERA: return content::PermissionType::VIDEO_CAPTURE; case fuchsia::web::PermissionType::PROTECTED_MEDIA_IDENTIFIER: return content::PermissionType::PROTECTED_MEDIA_IDENTIFIER; case fuchsia::web::PermissionType::PERSISTENT_STORAGE: return content::PermissionType::DURABLE_STORAGE; } } // Permission request callback for FrameImpl::RequestMediaAccessPermission. void HandleMediaPermissionsRequestResult( const content::MediaStreamRequest& request, content::MediaResponseCallback callback, const std::vector<blink::mojom::PermissionStatus>& result) { blink::MediaStreamDevices devices; int result_pos = 0; if (request.audio_type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE) { if (result[result_pos] == blink::mojom::PermissionStatus::GRANTED) { devices.push_back(blink::MediaStreamDevice( request.audio_type, request.requested_audio_device_id, /*name=*/"")); } result_pos++; } if (request.video_type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE) { if (result[result_pos] == blink::mojom::PermissionStatus::GRANTED) { devices.push_back(blink::MediaStreamDevice( request.video_type, request.requested_video_device_id, /*name=*/"")); } } std::move(callback).Run( devices, devices.empty() ? blink::mojom::MediaStreamRequestResult::NO_HARDWARE : blink::mojom::MediaStreamRequestResult::OK, nullptr); } absl::optional<url::Origin> ParseAndValidateWebOrigin( const std::string& origin_str) { GURL origin_url(origin_str); if (!origin_url.username().empty() || !origin_url.password().empty() || !origin_url.query().empty() || !origin_url.ref().empty()) { return absl::nullopt; } if (!origin_url.path().empty() && origin_url.path() != "/") return absl::nullopt; auto origin = url::Origin::Create(origin_url); if (origin.opaque()) return absl::nullopt; return origin; } } // namespace FrameImpl::PendingPopup::PendingPopup( FrameImpl* frame_ptr, fidl::InterfaceHandle<fuchsia::web::Frame> handle, fuchsia::web::PopupFrameCreationInfo creation_info) : frame_ptr(std::move(frame_ptr)), handle(std::move(handle)), creation_info(std::move(creation_info)) {} FrameImpl::PendingPopup::PendingPopup(PendingPopup&& other) = default; FrameImpl::PendingPopup::~PendingPopup() = default; // static FrameImpl* FrameImpl::FromWebContents(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto& map = WebContentsToFrameImplMap(); auto it = map.find(web_contents); if (it == map.end()) return nullptr; return it->second; } // static FrameImpl* FrameImpl::FromRenderFrameHost( content::RenderFrameHost* render_frame_host) { return FromWebContents( content::WebContents::FromRenderFrameHost(render_frame_host)); } FrameImpl::FrameImpl(std::unique_ptr<content::WebContents> web_contents, ContextImpl* context, fuchsia::web::CreateFrameParams params, inspect::Node inspect_node, fidl::InterfaceRequest<fuchsia::web::Frame> frame_request) : web_contents_(std::move(web_contents)), context_(context), console_log_tag_(params.has_debug_name() ? params.debug_name() : std::string()), params_for_popups_(std::move(params)), navigation_controller_(web_contents_.get()), permission_controller_(web_contents_.get()), binding_(this, std::move(frame_request)), media_blocker_(web_contents_.get()), theme_manager_(web_contents_.get(), base::BindOnce(&FrameImpl::OnThemeManagerError, base::Unretained(this))), inspect_node_(std::move(inspect_node)), inspect_name_property_( params_for_popups_.has_debug_name() ? inspect_node_.CreateString("name", params_for_popups_.debug_name()) : inspect::StringProperty()) { DCHECK(!WebContentsToFrameImplMap()[web_contents_.get()]); WebContentsToFrameImplMap()[web_contents_.get()] = this; web_contents_->SetDelegate(this); web_contents_->SetPageBaseBackgroundColor(SK_AlphaTRANSPARENT); Observe(web_contents_.get()); url_request_rewrite_rules_manager_.AddWebContents(web_contents_.get()); binding_.set_error_handler([this](zx_status_t status) { ZX_LOG_IF(ERROR, status != ZX_ERR_PEER_CLOSED, status) << " Frame disconnected."; context_->DestroyFrame(this); }); content::UpdateFontRendererPreferencesFromSystemSettings( web_contents_->GetMutableRendererPrefs()); // TODO(http://crbug.com/1254073): Deprecate autoplay_policy in // CreateFrameParams. if (params_for_popups_.has_autoplay_policy()) { content_area_settings_.set_autoplay_policy( params_for_popups_.autoplay_policy()); } } FrameImpl::~FrameImpl() { DestroyWindowTreeHost(); context_->devtools_controller()->OnFrameDestroyed(web_contents_.get()); auto& map = WebContentsToFrameImplMap(); auto it = WebContentsToFrameImplMap().find(web_contents_.get()); DCHECK(it != map.end() && it->second == this); map.erase(it); } zx::unowned_channel FrameImpl::GetBindingChannelForTest() const { return zx::unowned_channel(binding_.channel()); } aura::Window* FrameImpl::root_window() const { return window_tree_host_->window(); } void FrameImpl::ExecuteJavaScriptInternal(std::vector<std::string> origins, fuchsia::mem::Buffer script, ExecuteJavaScriptCallback callback, bool need_result) { if (!context_->IsJavaScriptInjectionAllowed()) { callback(fpromise::error(fuchsia::web::FrameError::INTERNAL_ERROR)); return; } // Prevents script injection into the wrong document if the renderer recently // navigated to a different origin. if (!IsUrlMatchedByOriginList(web_contents_->GetLastCommittedURL(), origins)) { callback(fpromise::error(fuchsia::web::FrameError::INVALID_ORIGIN)); return; } absl::optional<std::u16string> script_utf16 = base::ReadUTF8FromVMOAsUTF16(script); if (!script_utf16) { callback(fpromise::error(fuchsia::web::FrameError::BUFFER_NOT_UTF8)); return; } content::RenderFrameHost::JavaScriptResultCallback result_callback; if (need_result) { result_callback = base::BindOnce( [](ExecuteJavaScriptCallback callback, base::Value result_value) { std::string result_json; if (!base::JSONWriter::Write(result_value, &result_json)) { callback(fpromise::error(fuchsia::web::FrameError::INTERNAL_ERROR)); return; } callback(fpromise::ok(base::MemBufferFromString( std::move(result_json), "cr-execute-js-response"))); }, std::move(callback)); } web_contents_->GetMainFrame()->ExecuteJavaScript(*script_utf16, std::move(result_callback)); if (!need_result) { // If no result is required then invoke callback() immediately. callback(fpromise::ok(fuchsia::mem::Buffer())); } } bool FrameImpl::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const std::string& frame_name, const GURL& target_url) { // Specify a generous upper bound for unacknowledged popup windows, so that we // can catch bad client behavior while not interfering with normal operation. constexpr size_t kMaxPendingWebContentsCount = 10; if (!popup_listener_) return true; if (pending_popups_.size() >= kMaxPendingWebContentsCount) { // The content is producing popups faster than the embedder can process // them. Drop the popups so as to prevent resource exhaustion. LOG(WARNING) << "Too many pending popups, ignoring request."; // Don't produce a WebContents for this popup. return true; } return false; } void FrameImpl::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { DCHECK_EQ(source, web_contents_.get()); // TODO(crbug.com/995395): Add window disposition to the FIDL interface. switch (disposition) { case WindowOpenDisposition::NEW_FOREGROUND_TAB: case WindowOpenDisposition::NEW_BACKGROUND_TAB: case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: { if (url_request_rewrite_rules_manager_.GetCachedRules()) { // There is no support for URL request rules rewriting with popups. *was_blocked = true; return; } auto* popup_creation_info = reinterpret_cast<PopupFrameCreationInfoUserData*>( new_contents->GetUserData(kPopupCreationInfo)); fuchsia::web::PopupFrameCreationInfo popup_frame_creation_info = std::move(popup_creation_info->info); popup_frame_creation_info.set_initiated_by_user(user_gesture); // The PopupFrameCreationInfo won't be needed anymore, so clear it out. new_contents->SetUserData(kPopupCreationInfo, nullptr); // ContextImpl::CreateFrameInternal() verified that |params_for_popups_| // can be cloned, so it cannot fail here. fuchsia::web::CreateFrameParams params; zx_status_t status = params_for_popups_.Clone(&params); ZX_DCHECK(status == ZX_OK, status); fidl::InterfaceHandle<fuchsia::web::Frame> frame_handle; auto* popup_frame = context_->CreateFrameForWebContents( std::move(new_contents), std::move(params), frame_handle.NewRequest()); fuchsia::web::ContentAreaSettings settings; status = content_area_settings_.Clone(&settings); ZX_DCHECK(status == ZX_OK, status); popup_frame->SetContentAreaSettings(std::move(settings)); pending_popups_.emplace_back(popup_frame, std::move(frame_handle), std::move(popup_frame_creation_info)); MaybeSendPopup(); return; } // These kinds of windows don't produce Frames. case WindowOpenDisposition::CURRENT_TAB: case WindowOpenDisposition::SINGLETON_TAB: case WindowOpenDisposition::SAVE_TO_DISK: case WindowOpenDisposition::OFF_THE_RECORD: case WindowOpenDisposition::IGNORE_ACTION: case WindowOpenDisposition::SWITCH_TO_TAB: case WindowOpenDisposition::UNKNOWN: NOTIMPLEMENTED() << "Dropped new web contents (disposition: " << static_cast<int>(disposition) << ")"; return; } } void FrameImpl::WebContentsCreated(content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const std::string& frame_name, const GURL& target_url, content::WebContents* new_contents) { auto creation_info = std::make_unique<PopupFrameCreationInfoUserData>(); creation_info->info.set_initial_url(target_url.spec()); new_contents->SetUserData(kPopupCreationInfo, std::move(creation_info)); } void FrameImpl::MaybeSendPopup() { if (!popup_listener_) return; if (popup_ack_outstanding_ || pending_popups_.empty()) return; auto popup = std::move(pending_popups_.front()); pending_popups_.pop_front(); popup_listener_->OnPopupFrameCreated(std::move(popup.handle), std::move(popup.creation_info), [this] { popup_ack_outstanding_ = false; MaybeSendPopup(); }); popup_ack_outstanding_ = true; } void FrameImpl::DestroyWindowTreeHost() { if (!window_tree_host_) return; aura::client::SetFocusClient(root_window(), nullptr); wm::SetActivationClient(root_window(), nullptr); root_window()->RemovePreTargetHandler(&event_filter_); root_window()->RemovePreTargetHandler(focus_controller_.get()); web_contents_->GetNativeView()->Hide(); window_tree_host_->Hide(); window_tree_host_->compositor()->SetVisible(false); window_tree_host_.reset(); accessibility_bridge_.reset(); // Allows posted focus events to process before the FocusController is torn // down. content::GetUIThreadTaskRunner({})->DeleteSoon(FROM_HERE, std::move(focus_controller_)); } void FrameImpl::CloseAndDestroyFrame(zx_status_t error) { DCHECK(binding_.is_bound()); binding_.Close(error); context_->DestroyFrame(this); } void FrameImpl::OnPopupListenerDisconnected(zx_status_t status) { ZX_LOG_IF(WARNING, status != ZX_ERR_PEER_CLOSED, status) << "Popup listener disconnected."; pending_popups_.clear(); } void FrameImpl::OnMediaPlayerDisconnect() { media_player_ = nullptr; } void FrameImpl::OnAccessibilityError(zx_status_t error) { // The task is posted so |accessibility_bridge_| does not tear |this| down // while events are still being processed. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&FrameImpl::CloseAndDestroyFrame, weak_factory_.GetWeakPtr(), error)); } bool FrameImpl::MaybeHandleCastStreamingMessage( std::string* origin, fuchsia::web::WebMessage* message, PostMessageCallback* callback) { if (!context_->has_cast_streaming_enabled()) { return false; } if (!IsCastStreamingAppOrigin(*origin)) { return false; } if (receiver_session_client_ || !IsValidCastStreamingMessage(*message)) { // The Cast Streaming MessagePort should only be set once and |message| // should be a valid Cast Streaming Message. (*callback)(fpromise::error(fuchsia::web::FrameError::INVALID_ORIGIN)); return true; } receiver_session_client_ = std::make_unique<ReceiverSessionClient>( std::move((*message->mutable_outgoing_transfer())[0].message_port()), IsCastStreamingVideoOnlyAppOrigin(*origin)); (*callback)(fpromise::ok()); return true; } void FrameImpl::MaybeStartCastStreaming( content::NavigationHandle* navigation_handle) { if (!context_->has_cast_streaming_enabled() || !receiver_session_client_) return; mojo::AssociatedRemote<cast_streaming::mojom::CastStreamingReceiver> cast_streaming_receiver; navigation_handle->GetRenderFrameHost() ->GetRemoteAssociatedInterfaces() ->GetInterface(&cast_streaming_receiver); receiver_session_client_->SetCastStreamingReceiver( std::move(cast_streaming_receiver)); } void FrameImpl::UpdateRenderViewZoomLevel( content::RenderViewHost* render_view_host) { float page_scale = content_area_settings_.has_page_scale() ? content_area_settings_.page_scale() : 1.0; content::HostZoomMap* host_zoom_map = content::HostZoomMap::GetForWebContents(web_contents_.get()); host_zoom_map->SetTemporaryZoomLevel( render_view_host->GetProcess()->GetID(), render_view_host->GetRoutingID(), blink::PageZoomFactorToZoomLevel(page_scale)); } void FrameImpl::ConnectToAccessibilityBridge() { fuchsia::accessibility::semantics::SemanticsManagerPtr semantics_manager; if (!semantics_manager_for_test_) { semantics_manager = base::ComponentContextForProcess() ->svc() ->Connect<fuchsia::accessibility::semantics::SemanticsManager>(); } // If the SemanticTree owned by |accessibility_bridge_| is disconnected, it // will cause |this| to be closed. accessibility_bridge_ = std::make_unique<AccessibilityBridge>( semantics_manager_for_test_ ? semantics_manager_for_test_ : semantics_manager.get(), window_tree_host_.get(), web_contents_.get(), base::BindOnce(&FrameImpl::OnAccessibilityError, base::Unretained(this)), inspect_node_.CreateChild(kAccessibilityInspectNodeName)); } void FrameImpl::CreateView(fuchsia::ui::views::ViewToken view_token) { scenic::ViewRefPair view_ref_pair = scenic::ViewRefPair::New(); CreateViewWithViewRef(std::move(view_token), std::move(view_ref_pair.control_ref), std::move(view_ref_pair.view_ref)); } void FrameImpl::CreateViewWithViewRef( fuchsia::ui::views::ViewToken view_token, fuchsia::ui::views::ViewRefControl control_ref, fuchsia::ui::views::ViewRef view_ref) { if (IsHeadless()) { LOG(WARNING) << "CreateView() called on a HEADLESS Context."; CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); return; } if (!view_token.value.is_valid()) { LOG(WARNING) << "CreateView() called with invalid view_token."; CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); return; } // If a View to this Frame is already active then disconnect it. DestroyWindowTreeHost(); scenic::ViewRefPair view_ref_pair; view_ref_pair.control_ref = std::move(control_ref); view_ref_pair.view_ref = std::move(view_ref); SetupWindowTreeHost(std::move(view_token), std::move(view_ref_pair)); ConnectToAccessibilityBridge(); } void FrameImpl::CreateView2(fuchsia::web::CreateView2Args view_args) { if (IsHeadless()) { LOG(WARNING) << "CreateView2() called on a HEADLESS Context."; CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); return; } if (!view_args.has_view_creation_token() || !view_args.view_creation_token().value.is_valid()) { LOG(WARNING) << "CreateView2() called with invalid view_creation_token."; CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); return; } // If a View to this Frame is already active then disconnect it. DestroyWindowTreeHost(); scenic::ViewRefPair view_ref_pair = scenic::ViewRefPair::New(); SetupWindowTreeHost(std::move(*view_args.mutable_view_creation_token()), std::move(view_ref_pair)); ConnectToAccessibilityBridge(); } void FrameImpl::GetMediaPlayer( fidl::InterfaceRequest<fuchsia::media::sessions2::Player> player) { media_player_ = std::make_unique<MediaPlayerImpl>( content::MediaSession::Get(web_contents_.get()), std::move(player), base::BindOnce(&FrameImpl::OnMediaPlayerDisconnect, base::Unretained(this))); } void FrameImpl::GetNavigationController( fidl::InterfaceRequest<fuchsia::web::NavigationController> controller) { navigation_controller_.AddBinding(std::move(controller)); } void FrameImpl::ExecuteJavaScript(std::vector<std::string> origins, fuchsia::mem::Buffer script, ExecuteJavaScriptCallback callback) { ExecuteJavaScriptInternal(std::move(origins), std::move(script), std::move(callback), true); } void FrameImpl::ExecuteJavaScriptNoResult( std::vector<std::string> origins, fuchsia::mem::Buffer script, ExecuteJavaScriptNoResultCallback callback) { ExecuteJavaScriptInternal( std::move(origins), std::move(script), [callback = std::move(callback)]( fuchsia::web::Frame_ExecuteJavaScript_Result result_with_value) { if (result_with_value.is_err()) { callback(fpromise::error(result_with_value.err())); } else { callback(fpromise::ok()); } }, false); } void FrameImpl::AddBeforeLoadJavaScript( uint64_t id, std::vector<std::string> origins, fuchsia::mem::Buffer script, AddBeforeLoadJavaScriptCallback callback) { constexpr char kWildcardOrigin[] = "*"; if (!context_->IsJavaScriptInjectionAllowed()) { callback(fpromise::error(fuchsia::web::FrameError::INTERNAL_ERROR)); return; } absl::optional<std::string> script_as_string = base::StringFromMemBuffer(script); if (!script_as_string) { LOG(ERROR) << "Couldn't read script from buffer."; callback(fpromise::error(fuchsia::web::FrameError::INTERNAL_ERROR)); return; } // TODO(crbug.com/1108607): Only allow wildcards to be specified standalone. if (std::any_of(origins.begin(), origins.end(), [kWildcardOrigin](base::StringPiece origin) { return origin == kWildcardOrigin; })) { script_injector_.AddScriptForAllOrigins(id, *script_as_string); } else { std::vector<url::Origin> origins_converted; for (const std::string& origin : origins) { url::Origin origin_parsed = url::Origin::Create(GURL(origin)); if (origin_parsed.opaque()) { callback(fpromise::error(fuchsia::web::FrameError::INVALID_ORIGIN)); return; } origins_converted.push_back(origin_parsed); } script_injector_.AddScript(id, origins_converted, *script_as_string); } callback(fpromise::ok()); } void FrameImpl::RemoveBeforeLoadJavaScript(uint64_t id) { script_injector_.RemoveScript(id); } void FrameImpl::PostMessage(std::string origin, fuchsia::web::WebMessage message, PostMessageCallback callback) { if (MaybeHandleCastStreamingMessage(&origin, &message, &callback)) return; fuchsia::web::Frame_PostMessage_Result result; if (origin.empty()) { callback(fpromise::error(fuchsia::web::FrameError::INVALID_ORIGIN)); return; } if (!message.has_data()) { callback(fpromise::error(fuchsia::web::FrameError::NO_DATA_IN_MESSAGE)); return; } absl::optional<std::u16string> origin_utf16; if (origin != kWildcardOrigin) origin_utf16 = base::UTF8ToUTF16(origin); absl::optional<std::u16string> data_utf16 = base::ReadUTF8FromVMOAsUTF16(message.data()); if (!data_utf16) { callback(fpromise::error(fuchsia::web::FrameError::BUFFER_NOT_UTF8)); return; } // Convert and pass along any MessagePorts contained in the message. std::vector<blink::WebMessagePort> message_ports; if (message.has_outgoing_transfer()) { for (const fuchsia::web::OutgoingTransferable& outgoing : message.outgoing_transfer()) { if (!outgoing.is_message_port()) { callback(fpromise::error(fuchsia::web::FrameError::INTERNAL_ERROR)); return; } } for (fuchsia::web::OutgoingTransferable& outgoing : *message.mutable_outgoing_transfer()) { blink::WebMessagePort blink_port = cr_fuchsia::BlinkMessagePortFromFidl( std::move(outgoing.message_port())); if (!blink_port.IsValid()) { callback(fpromise::error(fuchsia::web::FrameError::INTERNAL_ERROR)); return; } message_ports.push_back(std::move(blink_port)); } } content::MessagePortProvider::PostMessageToFrame( web_contents_->GetPrimaryPage(), std::u16string(), origin_utf16, std::move(*data_utf16), std::move(message_ports)); callback(fpromise::ok()); } void FrameImpl::SetNavigationEventListener( fidl::InterfaceHandle<fuchsia::web::NavigationEventListener> listener) { SetNavigationEventListener2(std::move(listener), {}); } void FrameImpl::SetNavigationEventListener2( fidl::InterfaceHandle<fuchsia::web::NavigationEventListener> listener, fuchsia::web::NavigationEventListenerFlags flags) { navigation_controller_.SetEventListener(std::move(listener), flags); } void FrameImpl::SetJavaScriptLogLevel(fuchsia::web::ConsoleLogLevel level) { log_level_ = FuchsiaWebConsoleLogLevelToFxLogSeverity(level); } void FrameImpl::SetConsoleLogSink(fuchsia::logger::LogSinkHandle sink) { if (sink) { console_logger_ = base::ScopedFxLogger::CreateFromLogSink( std::move(sink), {console_log_tag_}); } else { console_logger_ = {}; } } void FrameImpl::ConfigureInputTypes(fuchsia::web::InputTypes types, fuchsia::web::AllowInputState allow) { event_filter_.ConfigureInputTypes(types, allow); } void FrameImpl::SetPopupFrameCreationListener( fidl::InterfaceHandle<fuchsia::web::PopupFrameCreationListener> listener) { popup_listener_ = listener.Bind(); popup_listener_.set_error_handler( fit::bind_member(this, &FrameImpl::OnPopupListenerDisconnected)); } void FrameImpl::SetUrlRequestRewriteRules( std::vector<fuchsia::web::UrlRequestRewriteRule> rules, SetUrlRequestRewriteRulesCallback callback) { auto mojom_rules = mojo::ConvertTo<url_rewrite::mojom::UrlRequestRewriteRulesPtr>( std::move(rules)); if (url_request_rewrite_rules_manager_.OnRulesUpdated( std::move(mojom_rules))) { std::move(callback)(); } else { CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); } } void FrameImpl::EnableHeadlessRendering() { if (!IsHeadless()) { LOG(ERROR) << "EnableHeadlessRendering() on non-HEADLESS Context."; CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); return; } scenic::ViewRefPair view_ref_pair = scenic::ViewRefPair::New(); SetupWindowTreeHost(fuchsia::ui::views::ViewToken(), std::move(view_ref_pair)); gfx::Rect bounds(kHeadlessWindowSize); if (semantics_manager_for_test_) { ConnectToAccessibilityBridge(); // Set bounds for testing hit testing. bounds.set_size(kSemanticsTestingWindowSize); } window_tree_host_->SetBoundsInPixels(bounds); // FrameWindowTreeHost will Show() itself when the View is attached, but // in headless mode there is no View, so Show() it explicitly. window_tree_host_->Show(); } void FrameImpl::DisableHeadlessRendering() { if (!IsHeadless()) { LOG(ERROR) << "Attempted to disable headless rendering on non-HEADLESS Context."; CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); return; } DestroyWindowTreeHost(); } void FrameImpl::SetupWindowTreeHost(fuchsia::ui::views::ViewToken view_token, scenic::ViewRefPair view_ref_pair) { DCHECK(!window_tree_host_); window_tree_host_ = std::make_unique<FrameWindowTreeHost>( std::move(view_token), std::move(view_ref_pair), web_contents_.get()); InitWindowTreeHost(); } void FrameImpl::SetupWindowTreeHost( fuchsia::ui::views::ViewCreationToken view_creation_token, scenic::ViewRefPair view_ref_pair) { DCHECK(!window_tree_host_); window_tree_host_ = std::make_unique<FrameWindowTreeHost>( std::move(view_creation_token), std::move(view_ref_pair), web_contents_.get()); InitWindowTreeHost(); } void FrameImpl::InitWindowTreeHost() { DCHECK(window_tree_host_); window_tree_host_->InitHost(); root_window()->AddPreTargetHandler(&event_filter_); // Add hooks which automatically set the focus state when input events are // received. focus_controller_ = std::make_unique<wm::FocusController>(new FrameFocusRules); root_window()->AddPreTargetHandler(focus_controller_.get()); aura::client::SetFocusClient(root_window(), focus_controller_.get()); wm::SetActivationClient(root_window(), focus_controller_.get()); layout_manager_ = new FrameLayoutManager; root_window()->SetLayoutManager(layout_manager_); // Transfers ownership. if (!render_size_override_.IsEmpty()) layout_manager_->ForceContentDimensions(render_size_override_); root_window()->AddChild(web_contents_->GetNativeView()); web_contents_->GetNativeView()->Show(); // FrameWindowTreeHost will Show() itself when the View is actually attached // to the view-tree to be displayed. See https://crbug.com/1109270 } void FrameImpl::SetMediaSessionId(uint64_t session_id) { media_session_id_ = session_id; } void FrameImpl::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { base::RecordComputedAction("MediaPlay"); } void FrameImpl::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, WebContentsObserver::MediaStoppedReason reason) { base::RecordComputedAction("MediaPause"); } void FrameImpl::GetPrivateMemorySize(GetPrivateMemorySizeCallback callback) { if (!web_contents_->GetMainFrame()->GetProcess()->IsReady()) { // Renderer process is not yet started. callback(0); return; } zx_info_task_stats_t task_stats; zx_status_t status = zx_object_get_info( web_contents_->GetMainFrame()->GetProcess()->GetProcess().Handle(), ZX_INFO_TASK_STATS, &task_stats, sizeof(task_stats), nullptr, nullptr); if (status != ZX_OK) { // Fail gracefully by returning zero. ZX_LOG(WARNING, status) << "zx_object_get_info(ZX_INFO_TASK_STATS)"; callback(0); return; } callback(task_stats.mem_private_bytes); } void FrameImpl::SetNavigationPolicyProvider( fuchsia::web::NavigationPolicyProviderParams params, fidl::InterfaceHandle<fuchsia::web::NavigationPolicyProvider> provider) { navigation_policy_handler_ = std::make_unique<NavigationPolicyHandler>( std::move(params), std::move(provider)); } void FrameImpl::OnThemeManagerError() { // TODO(crbug.com/1148454): Destroy the frame once a fake Display service is // implemented. // this->CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); } void FrameImpl::SetPreferredTheme(fuchsia::settings::ThemeType theme) { fuchsia::web::ContentAreaSettings settings; settings.set_theme(theme); SetContentAreaSettings(std::move(settings)); } void FrameImpl::SetPageScale(float scale) { fuchsia::web::ContentAreaSettings settings; settings.set_page_scale(scale); SetContentAreaSettings(std::move(settings)); } void FrameImpl::SetContentAreaSettings( fuchsia::web::ContentAreaSettings settings) { if (settings.has_hide_scrollbars()) content_area_settings_.set_hide_scrollbars(settings.hide_scrollbars()); if (settings.has_autoplay_policy()) content_area_settings_.set_autoplay_policy(settings.autoplay_policy()); if (settings.has_theme()) { content_area_settings_.set_theme(settings.theme()); theme_manager_.SetTheme(settings.theme()); } if (settings.has_page_scale()) { if (settings.page_scale() <= 0.0) { LOG(ERROR) << "SetPageScale() called with nonpositive scale."; CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); return; } if (!(content_area_settings_.has_page_scale() && (settings.page_scale() == content_area_settings_.page_scale()))) { content_area_settings_.set_page_scale(settings.page_scale()); UpdateRenderViewZoomLevel(web_contents_->GetRenderViewHost()); } } web_contents_->OnWebPreferencesChanged(); } void FrameImpl::ResetContentAreaSettings() { content_area_settings_ = fuchsia::web::ContentAreaSettings(); web_contents_->OnWebPreferencesChanged(); UpdateRenderViewZoomLevel(web_contents_->GetRenderViewHost()); } void FrameImpl::OverrideWebPreferences( blink::web_pref::WebPreferences* web_prefs) { if (content_area_settings_.has_hide_scrollbars()) { web_prefs->hide_scrollbars = content_area_settings_.hide_scrollbars(); } else { // Verify that hide_scrollbars defaults to false, per FIDL API. DCHECK(!web_prefs->hide_scrollbars); } if (content_area_settings_.has_autoplay_policy()) { switch (content_area_settings_.autoplay_policy()) { case fuchsia::web::AutoplayPolicy::ALLOW: web_prefs->autoplay_policy = blink::mojom::AutoplayPolicy::kNoUserGestureRequired; break; case fuchsia::web::AutoplayPolicy::REQUIRE_USER_ACTIVATION: web_prefs->autoplay_policy = blink::mojom::AutoplayPolicy::kDocumentUserActivationRequired; break; } } else { // REQUIRE_USER_ACTIVATION is the default per the FIDL API. web_prefs->autoplay_policy = blink::mojom::AutoplayPolicy::kDocumentUserActivationRequired; } theme_manager_.ApplyThemeToWebPreferences(web_prefs); } void FrameImpl::ForceContentDimensions( std::unique_ptr<fuchsia::ui::gfx::vec2> web_dips) { if (!web_dips) { render_size_override_ = {}; if (layout_manager_) layout_manager_->ForceContentDimensions({}); return; } gfx::Size web_dips_converted(web_dips->x, web_dips->y); if (web_dips_converted.IsEmpty()) { LOG(ERROR) << "Rejecting zero-area size for ForceContentDimensions()."; CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); return; } render_size_override_ = web_dips_converted; if (layout_manager_) layout_manager_->ForceContentDimensions(web_dips_converted); } void FrameImpl::SetPermissionState( fuchsia::web::PermissionDescriptor fidl_permission, std::string web_origin_string, fuchsia::web::PermissionState fidl_state) { if (!fidl_permission.has_type()) { LOG(ERROR) << "PermissionDescriptor.type is not specified in " "SetPermissionState()."; CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); return; } content::PermissionType type = FidlPermissionTypeToContentPermissionType(fidl_permission.type()); blink::mojom::PermissionStatus state = (fidl_state == fuchsia::web::PermissionState::GRANTED) ? blink::mojom::PermissionStatus::GRANTED : blink::mojom::PermissionStatus::DENIED; // TODO(crbug.com/1136994): Remove this once the PermissionManager API is // available. if (web_origin_string == "*" && type == content::PermissionType::PROTECTED_MEDIA_IDENTIFIER) { permission_controller_.SetDefaultPermissionState(type, state); return; } // Handle per-origin permissions specifications. auto web_origin = ParseAndValidateWebOrigin(web_origin_string); if (!web_origin) { LOG(ERROR) << "SetPermissionState() called with invalid web_origin: " << web_origin_string; CloseAndDestroyFrame(ZX_ERR_INVALID_ARGS); return; } permission_controller_.SetPermissionState(type, web_origin.value(), state); } void FrameImpl::CloseContents(content::WebContents* source) { DCHECK_EQ(source, web_contents_.get()); CloseAndDestroyFrame(ZX_OK); } void FrameImpl::SetBlockMediaLoading(bool blocked) { media_blocker_.BlockMediaLoading(blocked); } bool FrameImpl::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel log_level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { FuchsiaLogSeverity severity = BlinkConsoleMessageLevelToFxLogSeverity(log_level); if (severity < log_level_) { // Prevent the default logging mechanism from logging the message. return true; } if (!console_logger_.is_valid()) { // Log via the process' LogSink service if none was set on the Frame. // Connect on-demand, so that embedders need not provide a LogSink in the // CreateContextParams services, unless they actually enable logging. console_logger_ = base::ScopedFxLogger::CreateFromLogSink( base::ComponentContextForProcess() ->svc() ->Connect<fuchsia::logger::LogSink>(), {console_log_tag_}); if (!console_logger_.is_valid()) return false; } std::string source_id_utf8 = base::UTF16ToUTF8(source_id); std::string message_utf8 = base::UTF16ToUTF8(message); console_logger_.LogMessage(source_id_utf8, line_no, message_utf8, severity); return true; } void FrameImpl::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { DCHECK_EQ(web_contents_.get(), web_contents); std::vector<content::PermissionType> permissions; if (request.audio_type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE) { permissions.push_back(content::PermissionType::AUDIO_CAPTURE); } else if (request.audio_type != blink::mojom::MediaStreamType::NO_SERVICE) { std::move(callback).Run( blink::MediaStreamDevices(), blink::mojom::MediaStreamRequestResult::NOT_SUPPORTED, nullptr); return; } if (request.video_type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE) { permissions.push_back(content::PermissionType::VIDEO_CAPTURE); } else if (request.video_type != blink::mojom::MediaStreamType::NO_SERVICE) { std::move(callback).Run( blink::MediaStreamDevices(), blink::mojom::MediaStreamRequestResult::NOT_SUPPORTED, nullptr); return; } auto* render_frame_host = content::RenderFrameHost::FromID( request.render_process_id, request.render_frame_id); if (!render_frame_host) { std::move(callback).Run( blink::MediaStreamDevices(), blink::mojom::MediaStreamRequestResult::INVALID_STATE, nullptr); return; } auto* permission_controller = web_contents_->GetBrowserContext()->GetPermissionControllerDelegate(); permission_controller->RequestPermissions( permissions, render_frame_host, request.security_origin, request.user_gesture, base::BindOnce(&HandleMediaPermissionsRequestResult, request, std::move(callback))); } bool FrameImpl::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { content::PermissionType permission; switch (type) { case blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE: permission = content::PermissionType::AUDIO_CAPTURE; break; case blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE: permission = content::PermissionType::VIDEO_CAPTURE; break; default: NOTREACHED(); return false; } auto* permission_controller = web_contents_->GetBrowserContext()->GetPermissionControllerDelegate(); return permission_controller->GetPermissionStatusForFrame( permission, render_frame_host, security_origin) == blink::mojom::PermissionStatus::GRANTED; } bool FrameImpl::CanOverscrollContent() { // Don't process "overscroll" events (e.g. pull-to-refresh, swipe back, // swipe forward). // TODO(crbug/1177399): Add overscroll toggle to Frame API. return false; } void FrameImpl::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // TODO(https://crbug.com/1218946): With MPArch there may be multiple main // frames. This caller was converted automatically to the primary main frame // to preserve its semantics. Follow up to confirm correctness. if (!navigation_handle->IsInPrimaryMainFrame() || navigation_handle->IsSameDocument() || navigation_handle->IsErrorPage()) { return; } script_injector_.InjectScriptsForURL(navigation_handle->GetURL(), navigation_handle->GetRenderFrameHost()); MaybeStartCastStreaming(navigation_handle); } void FrameImpl::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { context_->devtools_controller()->OnFrameLoaded(web_contents_.get()); } void FrameImpl::RenderFrameCreated(content::RenderFrameHost* frame_host) { // The top-level frame is given a transparent background color. // GetView() is guaranteed to be non-null until |frame_host| teardown. if (!frame_host->GetParentOrOuterDocument()) { frame_host->GetView()->SetBackgroundColor(SK_AlphaTRANSPARENT); } } void FrameImpl::RenderViewHostChanged(content::RenderViewHost* old_host, content::RenderViewHost* new_host) { // UpdateRenderViewZoomLevel() sets temporary zoom level for the current // RenderView. It needs to be called again whenever main RenderView is // changed. UpdateRenderViewZoomLevel(new_host); } void FrameImpl::DidFirstVisuallyNonEmptyPaint() { base::RecordComputedAction("AppFirstPaint"); } void FrameImpl::ResourceLoadComplete( content::RenderFrameHost* render_frame_host, const content::GlobalRequestID& request_id, const blink::mojom::ResourceLoadInfo& resource_load_info) { int net_error = resource_load_info.net_error; if (net_error != net::OK) { base::RecordComputedAction( base::StringPrintf("WebEngine.ResourceRequestError:%d", net_error)); } } // TODO(crbug.com/1136681#c6): Move below GetBindingChannelForTest when fixed. void FrameImpl::EnableExplicitSitesFilter(std::string error_page) { explicit_sites_filter_error_page_ = std::move(error_page); }
class Solution { public: vector<string> letterCasePermutation(string S) { vector<string> res; backtracking(S,0,res); return res; } private: void backtracking(string& S,int idx, vector<string>& res){ res.push_back(S); for(int i=idx;i<S.size();i++){ if(isdigit(S[i])) continue; int d = isupper(S[i])?32:-32; S[i] += d; backtracking(S,i+1,res); S[i] -= d; } } };
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/test/image_decoder_test.h" #include <stddef.h> #include <memory> #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/md5.h" #include "base/path_service.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "third_party/WebKit/public/platform/WebData.h" #include "third_party/WebKit/public/platform/WebImage.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/WebKit/public/web/WebImageDecoder.h" // Uncomment this to recalculate the MD5 sums; see header comments. // #define CALCULATE_MD5_SUMS namespace { const int kFirstFrameIndex = 0; // Determine if we should test with file specified by |path| based // on |file_selection| and the |threshold| for the file size. bool ShouldSkipFile(const base::FilePath& path, ImageDecoderTestFileSelection file_selection, const int64_t threshold) { if (file_selection == TEST_ALL) return false; int64_t image_size = 0; base::GetFileSize(path, &image_size); return (file_selection == TEST_SMALLER) == (image_size > threshold); } } // namespace void ReadFileToVector(const base::FilePath& path, std::vector<char>* contents) { std::string raw_image_data; base::ReadFileToString(path, &raw_image_data); contents->resize(raw_image_data.size()); memcpy(&contents->front(), raw_image_data.data(), raw_image_data.size()); } base::FilePath GetMD5SumPath(const base::FilePath& path) { static const base::FilePath::StringType kDecodedDataExtension( FILE_PATH_LITERAL(".md5sum")); return base::FilePath(path.value() + kDecodedDataExtension); } #if defined(CALCULATE_MD5_SUMS) void SaveMD5Sum(const base::FilePath& path, const blink::WebImage& web_image) { // Calculate MD5 sum. base::MD5Digest digest; base::MD5Sum(web_image.getSkBitmap().getPixels(), web_image.getSkBitmap().width() * web_image.getSkBitmap().height() * sizeof(uint32_t), &digest); // Write sum to disk. int bytes_written = base::WriteFile( path, reinterpret_cast<const char*>(&digest), sizeof digest); ASSERT_EQ(sizeof digest, bytes_written); } #endif #if !defined(CALCULATE_MD5_SUMS) void VerifyImage(const blink::WebImageDecoder& decoder, const base::FilePath& path, const base::FilePath& md5_sum_path, size_t frame_index) { // Make sure decoding can complete successfully. EXPECT_TRUE(decoder.IsSizeAvailable()) << path.value(); EXPECT_GE(decoder.FrameCount(), frame_index) << path.value(); EXPECT_TRUE(decoder.IsFrameCompleteAtIndex(frame_index)) << path.value(); EXPECT_FALSE(decoder.IsFailed()); // Calculate MD5 sum. base::MD5Digest actual_digest; blink::WebImage web_image = decoder.GetFrameAtIndex(frame_index); base::MD5Sum(web_image.GetSkBitmap().getPixels(), web_image.GetSkBitmap().width() * web_image.GetSkBitmap().height() * sizeof(uint32_t), &actual_digest); // Read the MD5 sum off disk. std::string file_bytes; base::ReadFileToString(md5_sum_path, &file_bytes); base::MD5Digest expected_digest; ASSERT_EQ(sizeof expected_digest, file_bytes.size()) << path.value(); memcpy(&expected_digest, file_bytes.data(), sizeof expected_digest); // Verify that the sums are the same. EXPECT_EQ(0, memcmp(&expected_digest, &actual_digest, sizeof actual_digest)) << path.value(); } #endif void ImageDecoderTest::SetUp() { base::FilePath data_dir; ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &data_dir)); data_dir_ = data_dir.AppendASCII("webkit").AppendASCII("data").AppendASCII( format_ + "_decoder"); if (!base::PathExists(data_dir_)) { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); VLOG(0) << test_info->name() << " not running because test data wasn't found."; data_dir_.clear(); return; } } std::vector<base::FilePath> ImageDecoderTest::GetImageFiles() const { std::string pattern = "*." + format_; base::FileEnumerator enumerator(data_dir_, false, base::FileEnumerator::FILES); std::vector<base::FilePath> image_files; for (base::FilePath next_file_name = enumerator.Next(); !next_file_name.empty(); next_file_name = enumerator.Next()) { base::FilePath base_name = next_file_name.BaseName(); #if defined(OS_WIN) std::string base_name_ascii = base::UTF16ToASCII(base_name.value()); #else std::string base_name_ascii = base_name.value(); #endif if (base::MatchPattern(base_name_ascii, pattern)) image_files.push_back(next_file_name); } return image_files; } bool ImageDecoderTest::ShouldImageFail(const base::FilePath& path) const { const base::FilePath::StringType kBadSuffix(FILE_PATH_LITERAL(".bad.")); return (path.value().length() > (kBadSuffix.length() + format_.length()) && !path.value().compare(path.value().length() - format_.length() - kBadSuffix.length(), kBadSuffix.length(), kBadSuffix)); } void ImageDecoderTest::TestDecoding( ImageDecoderTestFileSelection file_selection, const int64_t threshold) { if (data_dir_.empty()) return; const std::vector<base::FilePath> image_files(GetImageFiles()); for (std::vector<base::FilePath>::const_iterator i = image_files.begin(); i != image_files.end(); ++i) { if (!ShouldSkipFile(*i, file_selection, threshold)) TestWebKitImageDecoder(*i, GetMD5SumPath(*i), kFirstFrameIndex); } } void ImageDecoderTest::TestWebKitImageDecoder( const base::FilePath& image_path, const base::FilePath& md5_sum_path, int desired_frame_index) const { #if defined(CALCULATE_MD5_SUMS) // If we're just calculating the MD5 sums, skip failing images quickly. if (ShouldImageFail(image_path)) return; #endif std::vector<char> image_contents; ReadFileToVector(image_path, &image_contents); EXPECT_TRUE(image_contents.size()); std::unique_ptr<blink::WebImageDecoder> decoder(CreateWebKitImageDecoder()); EXPECT_FALSE(decoder->IsFailed()); #if !defined(CALCULATE_MD5_SUMS) // Test chunking file into half. const int partial_size = image_contents.size()/2; blink::WebData partial_data( reinterpret_cast<const char*>(&(image_contents.at(0))), partial_size); // Make Sure the image decoder doesn't fail when we ask for the frame // buffer for this partial image. // NOTE: We can't check that frame 0 is non-NULL, because if this is an // ICO and we haven't yet supplied enough data to read the directory, // there is no framecount and thus no first frame. decoder->SetData(const_cast<blink::WebData&>(partial_data), false); EXPECT_FALSE(decoder->IsFailed()) << image_path.value(); #endif // Make sure passing the complete image results in successful decoding. blink::WebData data(reinterpret_cast<const char*>(&(image_contents.at(0))), image_contents.size()); decoder->SetData(const_cast<blink::WebData&>(data), true); if (ShouldImageFail(image_path)) { EXPECT_FALSE(decoder->IsFrameCompleteAtIndex(kFirstFrameIndex)); EXPECT_TRUE(decoder->IsFailed()); } else { EXPECT_FALSE(decoder->IsFailed()) << image_path.value(); #if defined(CALCULATE_MD5_SUMS) SaveMD5Sum(md5_sum_path, decoder->getFrameAtIndex(desired_frame_index)); #else VerifyImage(*decoder, image_path, md5_sum_path, desired_frame_index); #endif } }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2019 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #include "index/comparer.hpp" #include "index/norm.hpp" #include "iql/query_builder.hpp" #include "utils/index_utils.hpp" #include "tests_shared.hpp" #include "index_tests.hpp" namespace { class sorted_europarl_doc_template : public tests::europarl_doc_template { public: explicit sorted_europarl_doc_template( std::string field, std::vector<irs::type_info::type_id> field_features) : field_{std::move(field)}, field_features_{std::move(field_features)} { } virtual void init() override { indexed.push_back( std::make_shared<tests::string_field>( "title", irs::IndexFeatures::ALL, field_features_)); indexed.push_back( std::make_shared<text_ref_field>( "title_anl", false, field_features_)); indexed.push_back( std::make_shared<text_ref_field>( "title_anl_pay", true, field_features_)); indexed.push_back( std::make_shared<text_ref_field>( "body_anl", false, field_features_)); indexed.push_back( std::make_shared<text_ref_field>( "body_anl_pay", true, field_features_)); { insert(std::make_shared<tests::long_field>()); auto& field = static_cast<tests::long_field&>(indexed.back()); field.name("date"); } insert(std::make_shared<tests::string_field>( "datestr", irs::IndexFeatures::ALL, field_features_)); insert(std::make_shared<tests::string_field>( "body", irs::IndexFeatures::ALL, field_features_)); { insert(std::make_shared<tests::int_field>()); auto& field = static_cast<tests::int_field&>(indexed.back()); field.name("id"); } insert(std::make_shared<tests::string_field>( "idstr", irs::IndexFeatures::ALL, field_features_)); auto fields = indexed.find(field_); if (!fields.empty()) { sorted = fields[0]; } } private: std::string field_; // sorting field std::vector<irs::type_info::type_id> field_features_; }; // sorted_europal_doc_template struct string_comparer : irs::comparer { virtual bool less(const irs::bytes_ref& lhs, const irs::bytes_ref& rhs) const { if (lhs.empty() && rhs.empty()) { return false; } else if (rhs.empty()) { return true; } else if (lhs.empty()) { return false; } const auto lhs_value = irs::to_string<irs::bytes_ref>(lhs.c_str()); const auto rhs_value = irs::to_string<irs::bytes_ref>(rhs.c_str()); return lhs_value > rhs_value; } }; struct long_comparer : irs::comparer { virtual bool less(const irs::bytes_ref& lhs, const irs::bytes_ref& rhs) const { if (lhs.null() && rhs.null()) { return false; } else if (rhs.null()) { return false; } else if (lhs.null()) { return true; } auto* plhs = lhs.c_str(); auto* prhs = rhs.c_str(); return irs::zig_zag_decode64(irs::vread<uint64_t>(plhs)) < irs::zig_zag_decode64(irs::vread<uint64_t>(prhs)); } }; struct custom_feature { struct header { explicit header(irs::range<const irs::bytes_ref> headers) noexcept { for (const auto header : headers) { update(header); } } void write(irs::bstring& out) const { EXPECT_TRUE(out.empty()); out.resize(sizeof(size_t)); auto* p = out.data(); irs::write<size_t>(p, count); } void update(irs::bytes_ref in) { EXPECT_EQ(sizeof(count), in.size()); auto* p = in.c_str(); count += irs::read<decltype(count)>(p); } size_t count{0}; }; struct writer : irs::feature_writer { explicit writer(irs::range<const irs::bytes_ref> headers) noexcept : hdr{{}} { if (!headers.empty()) { init_header.emplace(headers); } } virtual void write( const irs::field_stats& stats, irs::doc_id_t doc, // cppcheck-suppress constParameter irs::columnstore_writer::values_writer_f& writer) final { ++hdr.count; // We intentionally call `writer(doc)` multiple // times to check concatenation logic. writer(doc).write_int(stats.len); writer(doc).write_int(stats.max_term_freq); writer(doc).write_int(stats.num_overlap); writer(doc).write_int(stats.num_unique); } virtual void write( data_output& out, irs::bytes_ref payload) { if (!payload.empty()) { ++hdr.count; out.write_bytes(payload.c_str(), payload.size()); } } virtual void finish(irs::bstring& out) final { if (init_header.has_value()) { // <= due to removals EXPECT_LE(hdr.count, init_header.value().count); } hdr.write(out); } header hdr; std::optional<header> init_header; std::optional<size_t> expected_count; }; static irs::feature_writer::ptr make_writer( irs::range<const irs::bytes_ref> payload) { return irs::memory::make_managed<writer>(payload); } }; REGISTER_ATTRIBUTE(custom_feature); class sorted_index_test_case : public tests::index_test_base { protected: bool supports_pluggable_features() const noexcept { // old formats don't support pluggable features constexpr irs::string_ref kOldFormats[] { "1_0", "1_1", "1_2", "1_3", "1_3simd" }; return std::end(kOldFormats) == std::find(std::begin(kOldFormats), std::end(kOldFormats), codec()->type().name()); } irs::feature_info_provider_t features() { return [this](irs::type_info::type_id id) { if (id == irs::type<irs::Norm>::id()) { return std::make_pair( irs::column_info{irs::type<irs::compression::lz4>::get(), {}, false}, &irs::Norm::MakeWriter); } if (supports_pluggable_features()) { if (irs::type<irs::Norm2>::id() == id) { return std::make_pair( irs::column_info{irs::type<irs::compression::none>::get(), {}, false}, &irs::Norm2::MakeWriter); } else if (irs::type<custom_feature>::id() == id) { return std::make_pair( irs::column_info{irs::type<irs::compression::none>::get(), {}, false}, &custom_feature::make_writer); } } return std::make_pair( irs::column_info{irs::type<irs::compression::none>::get(), {}, false}, irs::feature_writer_factory_t{}); }; } std::vector<irs::type_info::type_id> field_features() { return supports_pluggable_features() ? std::vector<irs::type_info::type_id>{ irs::type<irs::Norm>::id(), irs::type<irs::Norm2>::id(), irs::type<custom_feature>::id() } : std::vector<irs::type_info::type_id>{ irs::type<irs::Norm>::id() }; } void assert_index(size_t skip = 0, irs::automaton_table_matcher* matcher = nullptr) const { index_test_base::assert_index(irs::IndexFeatures::NONE, skip, matcher); index_test_base::assert_index( irs::IndexFeatures::NONE | irs::IndexFeatures::FREQ, skip, matcher); index_test_base::assert_index( irs::IndexFeatures::NONE | irs::IndexFeatures::FREQ | irs::IndexFeatures::POS, skip, matcher); index_test_base::assert_index( irs::IndexFeatures::NONE | irs::IndexFeatures::FREQ | irs::IndexFeatures::POS | irs::IndexFeatures::OFFS, skip, matcher); index_test_base::assert_index( irs::IndexFeatures::NONE | irs::IndexFeatures::FREQ | irs::IndexFeatures::POS | irs::IndexFeatures::PAY, skip, matcher); index_test_base::assert_index( irs::IndexFeatures::NONE | irs::IndexFeatures::FREQ | irs::IndexFeatures::POS | irs::IndexFeatures::OFFS | irs::IndexFeatures::PAY, skip, matcher); index_test_base::assert_columnstore(); } void check_feature_header(const irs::sub_reader& segment, const irs::field_meta& field, irs::type_info::type_id type, irs::bytes_ref header) { ASSERT_TRUE(supports_pluggable_features()); auto feature = field.features.find(type); ASSERT_NE(feature, field.features.end()); ASSERT_TRUE(irs::field_limits::valid(feature->second)); auto* column = segment.column(feature->second); ASSERT_NE(nullptr, column); ASSERT_FALSE(column->payload().null()); ASSERT_EQ(header, column->payload()); } void check_empty_feature(const irs::sub_reader& segment, const irs::field_meta& field, irs::type_info::type_id type) { ASSERT_TRUE(supports_pluggable_features()); auto feature = field.features.find(type); ASSERT_NE(feature, field.features.end()); ASSERT_FALSE(irs::field_limits::valid(feature->second)); auto* column = segment.column(feature->second); ASSERT_EQ(nullptr, column); } void check_features(const irs::sub_reader& segment, irs::string_ref field_name, size_t count, bool after_consolidation) { auto* field_reader = segment.field(field_name); ASSERT_NE(nullptr, field_reader); auto& field = field_reader->meta(); ASSERT_EQ(3, field.features.size()); // irs::norm, nothing is written since all values are equal to 1 check_empty_feature(segment, field, irs::type<irs::Norm>::id()); // custom_feature { irs::byte_type buf[sizeof(count)]; auto* p = buf; irs::write<size_t>(p, count); check_feature_header(segment, field, irs::type<custom_feature>::id(), { buf, sizeof buf }); } // irs::Norm2 { irs::Norm2Header hdr{after_consolidation ? irs::Norm2Encoding::Byte : irs::Norm2Encoding::Int}; hdr.Reset(1); irs::bstring buf; irs::Norm2Header::Write(hdr, buf); check_feature_header(segment, field, irs::type<irs::Norm2>::id(), buf); } } }; TEST_P(sorted_index_test_case, simple_sequential) { constexpr irs::string_ref sorted_column = "name"; // Build index tests::json_doc_generator gen( resource("simple_sequential.json"), [&sorted_column, this](tests::document& doc, const std::string& name, const tests::json_doc_generator::json_value& data) { if (data.is_string()) { auto field = std::make_shared<tests::string_field>( name, data.str, irs::IndexFeatures::ALL, field_features()); doc.insert(field); if (name == sorted_column) { doc.sorted = field; } } else if (data.is_number()) { auto field = std::make_shared<tests::long_field>(); field->name(name); field->value(data.ui); doc.insert(field); } }); string_comparer less; irs::index_writer::init_options opts; opts.comparator = &less; opts.features = features(); add_segment(gen, irs::OM_CREATE, opts); // add segment // Check index assert_index(); // Check columns { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(1, reader.size()); auto& segment = reader[0]; ASSERT_EQ(segment.docs_count(), segment.live_docs_count()); ASSERT_NE(nullptr, segment.sort()); // check sorted column { std::vector<irs::bstring> column_payload; gen.reset(); while (auto* doc = gen.next()) { auto* field = doc->stored.get(sorted_column); ASSERT_NE(nullptr, field); column_payload.emplace_back(); irs::bytes_output out(column_payload.back()); field->write(out); } ASSERT_EQ(column_payload.size(), segment.docs_count()); std::sort( column_payload.begin(), column_payload.end(), [&less](const irs::bstring& lhs, const irs::bstring& rhs) { return less(lhs, rhs); }); auto& sorted_column = *segment.sort(); ASSERT_EQ(segment.docs_count(), sorted_column.size()); auto sorted_column_it = sorted_column.iterator(false); ASSERT_NE(nullptr, sorted_column_it); auto* payload = irs::get<irs::payload>(*sorted_column_it); ASSERT_TRUE(payload); auto expected_doc = irs::doc_limits::min(); for (auto& expected_payload : column_payload) { ASSERT_TRUE(sorted_column_it->next()); ASSERT_EQ(expected_doc, sorted_column_it->value()); ASSERT_EQ(expected_payload, payload->value); ++expected_doc; } ASSERT_FALSE(sorted_column_it->next()); } // Check regular columns constexpr irs::string_ref column_names[] { "seq", "value", "duplicated", "prefix" }; for (auto& column_name : column_names) { struct doc { irs::doc_id_t id{ irs::doc_limits::eof() }; irs::bstring order; irs::bstring value; }; std::vector<doc> column_docs; column_docs.reserve(segment.docs_count()); gen.reset(); irs::doc_id_t id{ irs::doc_limits::min() }; while (auto* doc = gen.next()) { auto* sorted = doc->stored.get(sorted_column); ASSERT_NE(nullptr, sorted); column_docs.emplace_back(); auto* column = doc->stored.get(column_name); auto& value = column_docs.back(); irs::bytes_output order_out(value.order); sorted->write(order_out); if (column) { value.id = id++; irs::bytes_output value_out(value.value); column->write(value_out); } } std::sort( column_docs.begin(), column_docs.end(), [&less](const doc& lhs, const doc& rhs) { return less(lhs.order, rhs.order); }); auto* column_meta = segment.column(column_name); ASSERT_NE(nullptr, column_meta); auto* column = segment.column(column_meta->id()); ASSERT_NE(nullptr, column); ASSERT_EQ(id-1, column->size()); auto column_it = column->iterator(false); ASSERT_NE(nullptr, column_it); auto* payload = irs::get<irs::payload>(*column_it); ASSERT_TRUE(payload); irs::doc_id_t doc = 0; for (auto& expected_value: column_docs) { ++doc; if (irs::doc_limits::eof(expected_value.id)) { // skip empty values continue; } ASSERT_TRUE(column_it->next()); ASSERT_EQ(doc, column_it->value()); EXPECT_EQ(expected_value.value, payload->value); } ASSERT_FALSE(column_it->next()); } // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", 32, false); check_features(segment, "same", 32, false); check_features(segment, "duplicated", 13, false); check_features(segment, "prefix", 10, false); } } } TEST_P(sorted_index_test_case, simple_sequential_consolidate) { constexpr irs::string_ref sorted_column = "name"; // Build index tests::json_doc_generator gen( resource("simple_sequential.json"), [&sorted_column, this](tests::document& doc, const std::string& name, const tests::json_doc_generator::json_value& data) { if (data.is_string()) { auto field = std::make_shared<tests::string_field>( name, data.str, irs::IndexFeatures::ALL, field_features()); doc.insert(field); if (name == sorted_column) { doc.sorted = field; } } else if (data.is_number()) { auto field = std::make_shared<tests::long_field>(); field->name(name); field->value(data.i64); doc.insert(field); } }); constexpr std::pair<size_t, size_t> segment_offsets[] { { 0, 15 }, { 15, 17 } }; string_comparer less; irs::index_writer::init_options opts; opts.comparator = &less; opts.features = features(); auto writer = open_writer(irs::OM_CREATE, opts); ASSERT_NE(nullptr, writer); ASSERT_EQ(&less, writer->comparator()); // Add segment 0 { auto& offset = segment_offsets[0]; tests::limiting_doc_generator segment_gen(gen, offset.first, offset.second); add_segment(*writer, segment_gen); } // Add segment 1 add_segment(*writer, gen); // Check index assert_index(); // Check columns { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(2, reader.size()); // Check segments size_t i = 0; for (auto& segment : *reader) { auto& offset = segment_offsets[i++]; tests::limiting_doc_generator segment_gen(gen, offset.first, offset.second); ASSERT_EQ(offset.second, segment.docs_count()); ASSERT_EQ(segment.docs_count(), segment.live_docs_count()); ASSERT_NE(nullptr, segment.sort()); // Check sorted column { segment_gen.reset(); std::vector<irs::bstring> column_payload; while (auto* doc = segment_gen.next()) { auto* field = doc->stored.get(sorted_column); ASSERT_NE(nullptr, field); column_payload.emplace_back(); irs::bytes_output out(column_payload.back()); field->write(out); } ASSERT_EQ(column_payload.size(), segment.docs_count()); std::sort( column_payload.begin(), column_payload.end(), [&less](const irs::bstring& lhs, const irs::bstring& rhs) { return less(lhs, rhs); }); auto& sorted_column = *segment.sort(); ASSERT_EQ(segment.docs_count(), sorted_column.size()); ASSERT_TRUE(sorted_column.name().null()); ASSERT_TRUE(sorted_column.payload().empty()); auto sorted_column_it = sorted_column.iterator(false); ASSERT_NE(nullptr, sorted_column_it); auto* payload = irs::get<irs::payload>(*sorted_column_it); ASSERT_TRUE(payload); auto expected_doc = irs::doc_limits::min(); for (auto& expected_payload : column_payload) { ASSERT_TRUE(sorted_column_it->next()); ASSERT_EQ(expected_doc, sorted_column_it->value()); ASSERT_EQ(expected_payload, payload->value); ++expected_doc; } ASSERT_FALSE(sorted_column_it->next()); } // Check stored columns constexpr irs::string_ref column_names[] { "seq", "value", "duplicated", "prefix" }; for (auto& column_name : column_names) { struct doc { irs::doc_id_t id{ irs::doc_limits::eof() }; irs::bstring order; irs::bstring value; }; std::vector<doc> column_docs; column_docs.reserve(segment.docs_count()); segment_gen.reset(); irs::doc_id_t id{ irs::doc_limits::min() }; while (auto* doc = segment_gen.next()) { auto* sorted = doc->stored.get(sorted_column); ASSERT_NE(nullptr, sorted); column_docs.emplace_back(); auto* column = doc->stored.get(column_name); auto& value = column_docs.back(); irs::bytes_output order_out(value.order); sorted->write(order_out); if (column) { value.id = id++; irs::bytes_output value_out(value.value); column->write(value_out); } } std::sort( column_docs.begin(), column_docs.end(), [&less](const doc& lhs, const doc& rhs) { return less(lhs.order, rhs.order); }); auto* column_meta = segment.column(column_name); ASSERT_NE(nullptr, column_meta); auto* column = segment.column(column_meta->id()); ASSERT_NE(nullptr, column); ASSERT_EQ(column_meta, column); ASSERT_TRUE(column->payload().empty()); ASSERT_EQ(id-1, column->size()); auto column_it = column->iterator(false); ASSERT_NE(nullptr, column_it); auto* payload = irs::get<irs::payload>(*column_it); ASSERT_TRUE(payload); irs::doc_id_t doc = 0; for (auto& expected_value: column_docs) { ++doc; if (irs::doc_limits::eof(expected_value.id)) { // skip empty values continue; } ASSERT_TRUE(column_it->next()); ASSERT_EQ(doc, column_it->value()); EXPECT_EQ(expected_value.value, payload->value); } ASSERT_FALSE(column_it->next()); } // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", offset.second, false); check_features(segment, "same", offset.second, false); { constexpr irs::string_ref kColumnName = "duplicated"; auto* column = segment.column(kColumnName); ASSERT_NE(nullptr, column); check_features(segment, kColumnName, column->size(), false); } { constexpr irs::string_ref kColumnName = "prefix"; auto* column = segment.column(kColumnName); ASSERT_NE(nullptr, column); check_features(segment, kColumnName, column->size(), false); } } } } // Consolidate segments { irs::index_utils::consolidate_count consolidate_all; ASSERT_TRUE(writer->consolidate(irs::index_utils::consolidation_policy(consolidate_all))); writer->commit(); // simulate consolidation index().clear(); index().emplace_back(writer->feature_info()); auto& segment = index().back(); gen.reset(); while (auto* doc = gen.next()) { segment.insert(*doc); } for (auto& column : segment.columns()) { column.rewrite(); } ASSERT_NE(nullptr, writer->comparator()); segment.sort(*writer->comparator()); } assert_index(); // Check columns in consolidated segment { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(1, reader.size()); auto& segment = reader[0]; ASSERT_EQ(segment_offsets[0].second + segment_offsets[1].second, segment.docs_count()); ASSERT_EQ(segment.docs_count(), segment.live_docs_count()); ASSERT_NE(nullptr, segment.sort()); // Check sorted column { gen.reset(); std::vector<irs::bstring> column_payload; while (auto* doc = gen.next()) { auto* field = doc->stored.get(sorted_column); ASSERT_NE(nullptr, field); column_payload.emplace_back(); irs::bytes_output out(column_payload.back()); field->write(out); } ASSERT_EQ(column_payload.size(), segment.docs_count()); std::sort( column_payload.begin(), column_payload.end(), [&less](const irs::bstring& lhs, const irs::bstring& rhs) { return less(lhs, rhs); }); auto& sorted_column = *segment.sort(); ASSERT_EQ(segment.docs_count(), sorted_column.size()); ASSERT_TRUE(sorted_column.payload().empty()); ASSERT_TRUE(sorted_column.name().null()); auto sorted_column_it = sorted_column.iterator(false); ASSERT_NE(nullptr, sorted_column_it); auto* payload = irs::get<irs::payload>(*sorted_column_it); ASSERT_TRUE(payload); auto expected_doc = irs::doc_limits::min(); for (auto& expected_payload : column_payload) { ASSERT_TRUE(sorted_column_it->next()); ASSERT_EQ(expected_doc, sorted_column_it->value()); ASSERT_EQ(expected_payload, payload->value); ++expected_doc; } ASSERT_FALSE(sorted_column_it->next()); } // Check stored columns constexpr irs::string_ref column_names[] { "seq", "value", "duplicated", "prefix" }; for (auto& column_name : column_names) { struct doc { irs::doc_id_t id{ irs::doc_limits::eof() }; irs::bstring order; irs::bstring value; }; std::vector<doc> column_docs; column_docs.reserve(segment.docs_count()); gen.reset(); irs::doc_id_t id{ irs::doc_limits::min() }; while (auto* doc = gen.next()) { auto* sorted = doc->stored.get(sorted_column); ASSERT_NE(nullptr, sorted); column_docs.emplace_back(); auto* column = doc->stored.get(column_name); auto& value = column_docs.back(); irs::bytes_output order_out(value.order); sorted->write(order_out); if (column) { value.id = id++; irs::bytes_output value_out(value.value); column->write(value_out); } } std::sort( column_docs.begin(), column_docs.end(), [&less](const doc& lhs, const doc& rhs) { return less(lhs.order, rhs.order); }); auto* column_meta = segment.column(column_name); ASSERT_NE(nullptr, column_meta); auto* column = segment.column(column_meta->id()); ASSERT_NE(nullptr, column); ASSERT_EQ(column_meta, column); ASSERT_TRUE(column->payload().empty()); ASSERT_EQ(id-1, column->size()); auto column_it = column->iterator(false); ASSERT_NE(nullptr, column_it); auto* payload = irs::get<irs::payload>(*column_it); ASSERT_TRUE(payload); irs::doc_id_t doc = 0; for (auto& expected_value: column_docs) { ++doc; if (irs::doc_limits::eof(expected_value.id)) { // skip empty values continue; } ASSERT_TRUE(column_it->next()); ASSERT_EQ(doc, column_it->value()); EXPECT_EQ(expected_value.value, payload->value); } ASSERT_FALSE(column_it->next()); } // Check pluggable features in consolidated segment if (supports_pluggable_features()) { check_features(segment, "name", 32, true); check_features(segment, "same", 32, true); check_features(segment, "duplicated", 13, true); check_features(segment, "prefix", 10, true); } } } TEST_P(sorted_index_test_case, simple_sequential_already_sorted) { constexpr irs::string_ref sorted_column = "seq"; // Build index tests::json_doc_generator gen( resource("simple_sequential.json"), [&sorted_column, this](tests::document& doc, const std::string& name, const tests::json_doc_generator::json_value& data) { if (data.is_string()) { auto field = std::make_shared<tests::string_field>( name, data.str, irs::IndexFeatures::ALL, field_features()); doc.insert(field); } else if (data.is_number()) { auto field = std::make_shared<tests::long_field>(); field->name(name); field->value(data.i64); doc.insert(field); if (name == sorted_column) { doc.sorted = field; } } }); long_comparer less; irs::index_writer::init_options opts; opts.comparator = &less; opts.features = features(); add_segment(gen, irs::OM_CREATE, opts); // add segment assert_index(); // Check columns { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(1, reader.size()); auto& segment = reader[0]; ASSERT_EQ(segment.docs_count(), segment.live_docs_count()); ASSERT_NE(nullptr, segment.sort()); // Check sorted column { std::vector<irs::bstring> column_payload; gen.reset(); while (auto* doc = gen.next()) { auto* field = doc->stored.get(sorted_column); ASSERT_NE(nullptr, field); column_payload.emplace_back(); irs::bytes_output out(column_payload.back()); field->write(out); } ASSERT_EQ(column_payload.size(), segment.docs_count()); std::sort( column_payload.begin(), column_payload.end(), [&less](const irs::bstring& lhs, const irs::bstring& rhs) { return less(lhs, rhs); }); auto& sorted_column = *segment.sort(); ASSERT_EQ(segment.docs_count(), sorted_column.size()); ASSERT_TRUE(sorted_column.name().null()); ASSERT_TRUE(sorted_column.payload().empty()); auto sorted_column_it = sorted_column.iterator(false); ASSERT_NE(nullptr, sorted_column_it); auto* payload = irs::get<irs::payload>(*sorted_column_it); ASSERT_TRUE(payload); auto expected_doc = irs::doc_limits::min(); for (auto& expected_payload : column_payload) { ASSERT_TRUE(sorted_column_it->next()); ASSERT_EQ(expected_doc, sorted_column_it->value()); ASSERT_EQ(expected_payload, payload->value); ++expected_doc; } ASSERT_FALSE(sorted_column_it->next()); } // Check stored columns constexpr irs::string_ref column_names[] { "name", "value", "duplicated", "prefix" }; for (auto& column_name : column_names) { struct doc { irs::doc_id_t id{ irs::doc_limits::eof() }; irs::bstring order; irs::bstring value; }; std::vector<doc> column_docs; column_docs.reserve(segment.docs_count()); gen.reset(); irs::doc_id_t id{ irs::doc_limits::min() }; while (auto* doc = gen.next()) { auto* sorted = doc->stored.get(sorted_column); ASSERT_NE(nullptr, sorted); column_docs.emplace_back(); auto* column = doc->stored.get(column_name); auto& value = column_docs.back(); irs::bytes_output order_out(value.order); sorted->write(order_out); if (column) { value.id = id++; irs::bytes_output value_out(value.value); column->write(value_out); } } std::sort( column_docs.begin(), column_docs.end(), [&less](const doc& lhs, const doc& rhs) { return less(lhs.order, rhs.order); }); auto* column_meta = segment.column(column_name); ASSERT_NE(nullptr, column_meta); auto* column = segment.column(column_meta->id()); ASSERT_NE(nullptr, column); ASSERT_EQ(column_meta, column); ASSERT_EQ(0, column->payload().size()); ASSERT_EQ(id-1, column->size()); auto column_it = column->iterator(false); ASSERT_NE(nullptr, column_it); auto* payload = irs::get<irs::payload>(*column_it); ASSERT_TRUE(payload); irs::doc_id_t doc = 0; for (auto& expected_value: column_docs) { ++doc; if (irs::doc_limits::eof(expected_value.id)) { // skip empty values continue; } ASSERT_TRUE(column_it->next()); ASSERT_EQ(doc, column_it->value()); EXPECT_EQ(expected_value.value, payload->value); } ASSERT_FALSE(column_it->next()); } // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", 32, false); check_features(segment, "same", 32, false); check_features(segment, "duplicated", 13, false); check_features(segment, "prefix", 10, false); } } } TEST_P(sorted_index_test_case, europarl) { sorted_europarl_doc_template doc("date", field_features()); tests::delim_doc_generator gen(resource("europarl.subset.txt"), doc); long_comparer less; irs::index_writer::init_options opts; opts.comparator = &less; opts.features = features(); add_segment(gen, irs::OM_CREATE, opts); assert_index(); } TEST_P(sorted_index_test_case, multi_valued_sorting_field) { struct { bool write(irs::data_output& out) { out.write_bytes(reinterpret_cast<const irs::byte_type*>(value.c_str()), value.size()); return true; } irs::string_ref value; } field; tests::string_ref_field same("same"); same.value("A"); // Open writer string_comparer less; irs::index_writer::init_options opts; opts.comparator = &less; opts.features = features(); auto writer = open_writer(irs::OM_CREATE, opts); ASSERT_NE(nullptr, writer); ASSERT_EQ(&less, writer->comparator()); // Write documents { auto docs = writer->documents(); { auto doc = docs.insert(); // Compound sorted field field.value = "A"; doc.insert<irs::Action::STORE_SORTED>(field); field.value = "B"; doc.insert<irs::Action::STORE_SORTED>(field); // Indexed field doc.insert<irs::Action::INDEX>(same); } { auto doc = docs.insert(); // Compound sorted field field.value = "C"; doc.insert<irs::Action::STORE_SORTED>(field); field.value = "D"; doc.insert<irs::Action::STORE_SORTED>(field); // Indexed field doc.insert<irs::Action::INDEX>(same); } } writer->commit(); // Read documents { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(1, reader.size()); // Check segment 0 { auto& segment = reader[0]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_TRUE(column->payload().empty()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = termItr->postings(irs::IndexFeatures::NONE); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("CD", irs::ref_cast<char>(actual_value->value)); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("AB", irs::ref_cast<char>(actual_value->value)); ASSERT_FALSE(docsItr->next()); } } } TEST_P(sorted_index_test_case, check_document_order_after_consolidation_dense) { tests::json_doc_generator gen( resource("simple_sequential.json"), [this](tests::document& doc, const std::string& name, const tests::json_doc_generator::json_value& data) { if (data.is_string()) { auto field = std::make_shared<tests::string_field>( name, data.str, irs::IndexFeatures::ALL, field_features()); doc.insert(field); if (name == "name") { doc.sorted = field; } } }); auto* doc0 = gen.next(); // name == 'A' auto* doc1 = gen.next(); // name == 'B' auto* doc2 = gen.next(); // name == 'C' auto* doc3 = gen.next(); // name == 'D' string_comparer less; // open writer irs::index_writer::init_options opts; opts.comparator = &less; opts.features = features(); auto writer = open_writer(irs::OM_CREATE, opts); ASSERT_NE(nullptr, writer); ASSERT_EQ(&less, writer->comparator()); // Segment 0 ASSERT_TRUE(insert(*writer, doc0->indexed.begin(), doc0->indexed.end(), doc0->stored.begin(), doc0->stored.end(), doc0->sorted)); ASSERT_TRUE(insert(*writer, doc2->indexed.begin(), doc2->indexed.end(), doc2->stored.begin(), doc2->stored.end(), doc2->sorted)); writer->commit(); // Segment 1 ASSERT_TRUE(insert(*writer, doc1->indexed.begin(), doc1->indexed.end(), doc1->stored.begin(), doc1->stored.end(), doc1->sorted)); ASSERT_TRUE(insert(*writer, doc3->indexed.begin(), doc3->indexed.end(), doc3->stored.begin(), doc3->stored.end(), doc3->sorted)); writer->commit(); // Read documents { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(2, reader.size()); // Check segment 0 { auto& segment = reader[0]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_TRUE(column->payload().empty()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = termItr->postings(irs::IndexFeatures::NONE); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("C", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("A", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_FALSE(docsItr->next()); // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", 2, false); check_features(segment, "same", 2, false); check_features(segment, "duplicated", 2, false); check_features(segment, "prefix", 1, false); } } // Check segment 1 { auto& segment = reader[1]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = termItr->postings(irs::IndexFeatures::NONE); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("D", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("B", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_FALSE(docsItr->next()); // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", 2, false); check_features(segment, "same", 2, false); check_features(segment, "duplicated", 1, false); check_features(segment, "prefix", 1, false); } } } // Consolidate segments { irs::index_utils::consolidate_count consolidate_all; ASSERT_TRUE(writer->consolidate(irs::index_utils::consolidation_policy(consolidate_all))); writer->commit(); } // Check consolidated segment { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(1, reader.size()); ASSERT_EQ(reader->live_docs_count(), reader->docs_count()); { auto& segment = reader[0]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_TRUE(column->payload().empty()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = termItr->postings(irs::IndexFeatures::NONE); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("D", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("C", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("B", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("A", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_FALSE(docsItr->next()); // Check pluggable features in consolidated segment if (supports_pluggable_features()) { check_features(segment, "name", 4, true); check_features(segment, "same", 4, true); check_features(segment, "duplicated", 3, true); check_features(segment, "prefix", 2, true); } } } // Create expected index auto& expected_index = index(); expected_index.emplace_back(writer->feature_info()); expected_index.back().insert( doc0->indexed.begin(), doc0->indexed.end(), doc0->stored.begin(), doc0->stored.end(), doc0->sorted.get()); expected_index.back().insert( doc2->indexed.begin(), doc2->indexed.end(), doc2->stored.begin(), doc2->stored.end(), doc2->sorted.get()); expected_index.back().insert( doc1->indexed.begin(), doc1->indexed.end(), doc1->stored.begin(), doc1->stored.end(), doc1->sorted.get()); expected_index.back().insert( doc3->indexed.begin(), doc3->indexed.end(), doc3->stored.begin(), doc3->stored.end(), doc3->sorted.get()); expected_index.back().sort(*writer->comparator()); for (auto& column : expected_index.back().columns()) { column.rewrite(); } assert_index(); } TEST_P(sorted_index_test_case, check_document_order_after_consolidation_dense_with_removals) { tests::json_doc_generator gen( resource("simple_sequential.json"), [this](tests::document& doc, const std::string& name, const tests::json_doc_generator::json_value& data) { if (data.is_string()) { auto field = std::make_shared<tests::string_field>( name, data.str, irs::IndexFeatures::ALL, field_features()); doc.insert(field); if (name == "name") { doc.sorted = field; } } }); auto* doc0 = gen.next(); // name == 'A' auto* doc1 = gen.next(); // name == 'B' auto* doc2 = gen.next(); // name == 'C' auto* doc3 = gen.next(); // name == 'D' tests::string_field empty_field{"", irs::IndexFeatures::NONE}; ASSERT_FALSE(empty_field.value().null()); ASSERT_TRUE(empty_field.value().empty()); string_comparer less; // open writer irs::index_writer::init_options opts; opts.comparator = &less; opts.features = features(); auto writer = open_writer(irs::OM_CREATE, opts); ASSERT_NE(nullptr, writer); ASSERT_EQ(&less, writer->comparator()); // segment 0 ASSERT_TRUE(insert(*writer, doc0->indexed.begin(), doc0->indexed.end(), doc0->stored.begin(), doc0->stored.end(), doc0->sorted)); ASSERT_TRUE(insert(*writer, doc2->indexed.begin(), doc2->indexed.end(), doc2->stored.begin(), doc2->stored.end(), doc2->sorted)); writer->commit(); // segment 1 ASSERT_TRUE(insert(*writer, doc1->indexed.begin(), doc1->indexed.end(), doc1->stored.begin(), doc1->stored.end(), doc1->sorted)); ASSERT_TRUE(insert(*writer, doc3->indexed.begin(), doc3->indexed.end(), doc3->stored.begin(), doc3->stored.end(), doc3->sorted)); writer->commit(); // Read documents { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(2, reader.size()); // Check segment 0 { auto& segment = reader[0]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_TRUE(column->payload().empty()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = termItr->postings(irs::IndexFeatures::NONE); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("C", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("A", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_FALSE(docsItr->next()); // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", 2, false); check_features(segment, "same", 2, false); check_features(segment, "duplicated", 2, false); check_features(segment, "prefix", 1, false); } } // Check segment 1 { auto& segment = reader[1]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_EQ(0, column->payload().size()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = termItr->postings(irs::IndexFeatures::NONE); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("D", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("B", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_FALSE(docsItr->next()); // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", 2, false); check_features(segment, "same", 2, false); check_features(segment, "duplicated", 1, false); check_features(segment, "prefix", 1, false); } } } // Remove document { auto query_doc1 = irs::iql::query_builder().build("name==C", "C"); writer->documents().remove(*query_doc1.filter); writer->commit(); } // Read documents { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(2, reader.size()); // Check segment 0 { auto& segment = reader[0]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_EQ(0, column->payload().size()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = segment.mask(termItr->postings(irs::IndexFeatures::NONE)); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("A", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_FALSE(docsItr->next()); // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", 2, false); check_features(segment, "same", 2, false); check_features(segment, "duplicated", 2, false); check_features(segment, "prefix", 1, false); } } // Check segment 1 { auto& segment = reader[1]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_EQ(0, column->payload().size()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = segment.mask(termItr->postings(irs::IndexFeatures::NONE)); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("D", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("B", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_FALSE(docsItr->next()); // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", 2, false); check_features(segment, "same", 2, false); check_features(segment, "duplicated", 1, false); check_features(segment, "prefix", 1, false); } } } // Consolidate segments { irs::index_utils::consolidate_count consolidate_all; ASSERT_TRUE(writer->consolidate(irs::index_utils::consolidation_policy(consolidate_all))); writer->commit(); } // Check consolidated segment { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(1, reader.size()); ASSERT_EQ(reader->live_docs_count(), reader->docs_count()); // Check segment 0 { auto& segment = reader[0]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_EQ(0, column->payload().size()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = termItr->postings(irs::IndexFeatures::NONE); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("D", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("B", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("A", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_FALSE(docsItr->next()); // Check pluggable features in consolidated segment if (supports_pluggable_features()) { check_features(segment, "name", 3, true); check_features(segment, "same", 3, true); check_features(segment, "duplicated", 2, true); check_features(segment, "prefix", 2, true); } } } // Create expected index auto& expected_index = index(); expected_index.emplace_back(writer->feature_info()); expected_index.back().insert( doc0->indexed.begin(), doc0->indexed.end(), doc0->stored.begin(), doc0->stored.end(), doc0->sorted.get()); expected_index.back().insert( doc1->indexed.begin(), doc1->indexed.end(), doc1->stored.begin(), doc1->stored.end(), doc1->sorted.get()); expected_index.back().insert( doc3->indexed.begin(), doc3->indexed.end(), doc3->stored.begin(), doc3->stored.end(), doc3->sorted.get()); for (auto& column : expected_index.back().columns()) { column.rewrite(); } expected_index.back().sort(*writer->comparator()); assert_index(); } TEST_P(sorted_index_test_case, check_document_order_after_consolidation_sparse) { tests::json_doc_generator gen( resource("simple_sequential.json"), [this] (tests::document& doc, const std::string& name, const tests::json_doc_generator::json_value& data) { if (data.is_string()) { auto field = std::make_shared<tests::string_field>( name, data.str, irs::IndexFeatures::ALL, field_features()); doc.insert(field); if (name == "name") { doc.sorted = field; } } }); auto* doc0 = gen.next(); // name == 'A' auto* doc1 = gen.next(); // name == 'B' auto* doc2 = gen.next(); // name == 'C' auto* doc3 = gen.next(); // name == 'D' string_comparer less; irs::index_writer::init_options opts; opts.comparator = &less; opts.features = features(); auto writer = open_writer(irs::OM_CREATE, opts); ASSERT_NE(nullptr, writer); ASSERT_NE(nullptr, writer->comparator()); // Create segment 0 ASSERT_TRUE(insert(*writer, doc2->indexed.begin(), doc2->indexed.end(), doc2->stored.begin(), doc2->stored.end())); ASSERT_TRUE(insert(*writer, doc0->indexed.begin(), doc0->indexed.end(), doc0->stored.begin(), doc0->stored.end(), doc0->sorted)); writer->commit(); // Create segment 1 ASSERT_TRUE(insert(*writer, doc1->indexed.begin(), doc1->indexed.end(), doc1->stored.begin(), doc1->stored.end(), doc1->sorted)); ASSERT_TRUE(insert(*writer, doc3->indexed.begin(), doc3->indexed.end(), doc3->stored.begin(), doc3->stored.end())); writer->commit(); // Read documents { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(2, reader.size()); // Check segment 0 { auto& segment = reader[0]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_EQ(0, column->payload().size()); ASSERT_EQ(2, column->size()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = termItr->postings(irs::IndexFeatures::NONE); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("A", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_TRUE(actual_value->value.empty()); ASSERT_FALSE(docsItr->next()); // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", 2, false); check_features(segment, "same", 2, false); check_features(segment, "duplicated", 2, false); check_features(segment, "prefix", 1, false); } } // Check segment 1 { auto& segment = reader[1]; const auto* column = segment.sort(); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_EQ(0, column->payload().size()); ASSERT_EQ(2, column->size()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = termItr->postings(irs::IndexFeatures::NONE); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("B", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_TRUE(actual_value->value.empty()); ASSERT_FALSE(docsItr->next()); // Check pluggable features if (supports_pluggable_features()) { check_features(segment, "name", 2, false); check_features(segment, "same", 2, false); check_features(segment, "duplicated", 1, false); check_features(segment, "prefix", 1, false); } } } // Consolidate segments { irs::index_utils::consolidate_count consolidate_all; ASSERT_TRUE(writer->consolidate(irs::index_utils::consolidation_policy(consolidate_all))); writer->commit(); } // Check consolidated segment { auto reader = irs::directory_reader::open(dir(), codec()); ASSERT_TRUE(reader); ASSERT_EQ(1, reader.size()); ASSERT_EQ(reader->live_docs_count(), reader->docs_count()); // Check segment 0 { auto& segment = reader[0]; const auto* column = segment.sort(); ASSERT_EQ(4, column->size()); ASSERT_NE(nullptr, column); ASSERT_TRUE(column->name().null()); ASSERT_EQ(0, column->payload().size()); auto values = column->iterator(false); ASSERT_NE(nullptr, values); auto* actual_value = irs::get<irs::payload>(*values); ASSERT_NE(nullptr, actual_value); auto terms = segment.field("same"); ASSERT_NE(nullptr, terms); auto termItr = terms->iterator(irs::SeekMode::NORMAL); ASSERT_TRUE(termItr->next()); auto docsItr = termItr->postings(irs::IndexFeatures::NONE); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("B", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_EQ("A", irs::to_string<irs::string_ref>(actual_value->value.c_str())); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_TRUE(actual_value->value.empty()); ASSERT_TRUE(docsItr->next()); ASSERT_EQ(docsItr->value(), values->seek(docsItr->value())); ASSERT_TRUE(actual_value->value.empty()); ASSERT_FALSE(docsItr->next()); // Check pluggable features in consolidated segment if (supports_pluggable_features()) { check_features(segment, "name", 4, true); check_features(segment, "same", 4, true); check_features(segment, "duplicated", 3, true); check_features(segment, "prefix", 2, true); } } } // FIXME(gnusi) // We can't use assert_index() to check the // whole index because sort is not stable // // struct empty_field : tests::ifield { // irs::string_ref name() const override { // EXPECT_FALSE(true); // throw irs::not_impl_error{}; // } // // irs::token_stream& get_tokens() const override { // EXPECT_FALSE(true); // throw irs::not_impl_error{}; // } // // irs::features_t features() const override { // EXPECT_FALSE(true); // throw irs::not_impl_error{}; // } // // // irs::IndexFeatures index_features() const override { // EXPECT_FALSE(true); // throw irs::not_impl_error{}; // } // // bool write(irs::data_output&) const override { // return true; // } // // mutable irs::null_token_stream stream_; // } empty; // // // Create expected index // auto& expected_index = index(); // expected_index.emplace_back(writer->feature_info()); // expected_index.back().insert( // doc2->indexed.begin(), doc2->indexed.end(), // doc2->stored.begin(), doc2->stored.end(), // &empty); // expected_index.back().insert( // doc0->indexed.begin(), doc0->indexed.end(), // doc0->stored.begin(), doc0->stored.end(), // doc0->sorted.get()); // expected_index.back().insert( // doc1->indexed.begin(), doc1->indexed.end(), // doc1->stored.begin(), doc1->stored.end(), // doc1->sorted.get()); // expected_index.back().insert( // doc3->indexed.begin(), doc3->indexed.end(), // doc3->stored.begin(), doc3->stored.end(), // &empty); // for (auto& column : expected_index.back().columns()) { // column.rewrite(); // } // expected_index.back().sort(*writer->comparator()); // // assert_index(); } // Separate definition as MSVC parser fails to do conditional defines in macro expansion #ifdef IRESEARCH_SSE2 const auto kSortedIndexTestCaseValues = ::testing::Values( tests::format_info{"1_1", "1_0"}, tests::format_info{"1_2", "1_0"}, tests::format_info{"1_3", "1_0"}, tests::format_info{"1_4", "1_0"}, tests::format_info{"1_3simd", "1_0"}, tests::format_info{"1_4simd", "1_0"}); #else const auto kSortedIndexTestCaseValues = ::testing::Values( tests::format_info{"1_1", "1_0"}, tests::format_info{"1_2", "1_0"}, tests::format_info{"1_3", "1_0"}, tests::format_info{"1_4", "1_0"}); #endif INSTANTIATE_TEST_SUITE_P( sorted_index_test, sorted_index_test_case, ::testing::Combine( ::testing::Values( &tests::directory<&tests::memory_directory>, &tests::directory<&tests::fs_directory>, &tests::directory<&tests::mmap_directory>), kSortedIndexTestCaseValues), sorted_index_test_case::to_string); }
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: russ@q12.org Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * 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 files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ #include "config.h" #include "ball.h" #include "joint_internal.h" //**************************************************************************** // ball and socket dxJointBall::dxJointBall( dxWorld *w ) : dxJoint( w ) { dSetZero( anchor1, 4 ); dSetZero( anchor2, 4 ); // These are now set in dxJoint constructor // erp = world->global_erp; // cfm = world->global_cfm; } void dxJointBall::getSureMaxInfo( SureMaxInfo* info ) { info->max_m = 3; } void dxJointBall::getInfo1( dxJoint::Info1 *info ) { info->m = 3; info->nub = 3; } void dxJointBall::getInfo2( dxJoint::Info2 *info ) { // If joint values of erp and cfm are negative, then ignore them. // info->erp, info->cfm already have the global values from quickstep if (this->erp >= 0) info->erp = this->erp; if (this->cfm >= 0) { info->cfm[0] = cfm; info->cfm[1] = cfm; info->cfm[2] = cfm; } setBall( this, info, anchor1, anchor2 ); } void dJointSetBallAnchor( dJointID j, dReal x, dReal y, dReal z ) { dxJointBall* joint = ( dxJointBall* )j; dUASSERT( joint, "bad joint argument" ); checktype( joint, Ball ); setAnchors( joint, x, y, z, joint->anchor1, joint->anchor2 ); } void dJointSetBallAnchor2( dJointID j, dReal x, dReal y, dReal z ) { dxJointBall* joint = ( dxJointBall* )j; dUASSERT( joint, "bad joint argument" ); checktype( joint, Ball ); joint->anchor2[0] = x; joint->anchor2[1] = y; joint->anchor2[2] = z; joint->anchor2[3] = 0; } void dJointGetBallAnchor( dJointID j, dVector3 result ) { dxJointBall* joint = ( dxJointBall* )j; dUASSERT( joint, "bad joint argument" ); dUASSERT( result, "bad result argument" ); checktype( joint, Ball ); if ( joint->flags & dJOINT_REVERSE ) getAnchor2( joint, result, joint->anchor2 ); else getAnchor( joint, result, joint->anchor1 ); } void dJointGetBallAnchor2( dJointID j, dVector3 result ) { dxJointBall* joint = ( dxJointBall* )j; dUASSERT( joint, "bad joint argument" ); dUASSERT( result, "bad result argument" ); checktype( joint, Ball ); if ( joint->flags & dJOINT_REVERSE ) getAnchor( joint, result, joint->anchor1 ); else getAnchor2( joint, result, joint->anchor2 ); } void dxJointBall::set( int num, dReal value ) { switch (num) { case dParamCFM: cfm = value; break; case dParamERP: erp = value; break; default: break; } } dReal dxJointBall::get( int num ) { switch ( num ) { case dParamCFM: return cfm; case dParamERP: return erp; default: return 0; } } void dJointSetBallParam( dJointID j, int parameter, dReal value ) { dxJointBall* joint = ( dxJointBall* )j; dUASSERT( joint, "bad joint argument" ); checktype( joint, Ball ); joint->set( parameter, value ); } dReal dJointGetBallParam( dJointID j, int parameter ) { dxJointBall* joint = ( dxJointBall* )j; dUASSERT( joint, "bad joint argument" ); checktype( joint, Ball ); return joint->get( parameter ); } dJointType dxJointBall::type() const { return dJointTypeBall; } size_t dxJointBall::size() const { return sizeof( *this ); } void dxJointBall::setRelativeValues() { dVector3 anchor; dJointGetBallAnchor(this, anchor); setAnchors( this, anchor[0], anchor[1], anchor[2], anchor1, anchor2 ); }
/* ========================================================================= Copyright (c) 2010-2012, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. Portions of this software are copyright by UChicago Argonne, LLC. ----------------- ViennaCL - The Vienna Computing Library ----------------- Project Head: Karl Rupp rupp@iue.tuwien.ac.at (A list of authors and contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ============================================================================= */ #ifndef VIENNACL_WITH_OPENCL #define VIENNACL_WITH_OPENCL #endif #include "viennacl/scalar.hpp" #include "viennacl/vector.hpp" #include "viennacl/compressed_matrix.hpp" #include "viennacl/linalg/prod.hpp" #include <iostream> #include <vector> #include <stdlib.h> #include "benchmark-utils.hpp" template <typename ScalarType, typename VectorType, typename MatrixType> class test_data; #include "common.hpp" #ifdef ENABLE_VIENNAPROFILER #include "common_vprof.hpp" #endif template <typename TestData> void matrix_vec_mul(TestData & data) { data.v2 = viennacl::linalg::prod(data.mat, data.v1); } /* * Auto-Tuning for dense matrix kernels */ #define BENCHMARK_MATRIX_SIZE 32768 //a helper container that holds the objects used during benchmarking template <typename ScalarType, typename VectorType, typename MatrixType> class test_data { public: typedef typename VectorType::value_type::value_type value_type; test_data(ScalarType & s1_, VectorType & v1_, VectorType & v2_, MatrixType & mat_) : s1(s1_), v1(v1_), v2(v2_), mat(mat_) {} ScalarType & s1; VectorType & v1; VectorType & v2; MatrixType & mat; }; ////////////////////// some functions that aid testing to follow ///////////////////////////////// template<typename ScalarType> int run_matrix_benchmark(test_config & config, viennacl::io::parameter_database& paras) { typedef viennacl::scalar<ScalarType> VCLScalar; typedef viennacl::vector<ScalarType> VCLVector; typedef viennacl::compressed_matrix<ScalarType> VCLMatrix; //////////////////////////////////////////////////////////////////// //set up a little bit of data to play with: //ScalarType std_result = 0; ScalarType std_factor1 = static_cast<ScalarType>(3.1415); ScalarType std_factor2 = static_cast<ScalarType>(42.0); viennacl::scalar<ScalarType> vcl_factor1(std_factor1); viennacl::scalar<ScalarType> vcl_factor2(std_factor2); std::vector<ScalarType> std_vec1(BENCHMARK_MATRIX_SIZE); //used to set all values to zero std::vector< std::map< unsigned int, ScalarType> > stl_mat(BENCHMARK_MATRIX_SIZE); //store identity matrix here VCLVector vcl_vec1(BENCHMARK_MATRIX_SIZE); VCLVector vcl_vec2(BENCHMARK_MATRIX_SIZE); VCLMatrix vcl_mat(BENCHMARK_MATRIX_SIZE, BENCHMARK_MATRIX_SIZE); for (int i=0; i<BENCHMARK_MATRIX_SIZE; ++i) { if (i > 10) { stl_mat[i][i - 10] = 1.0; stl_mat[i][i - 7] = 1.0; stl_mat[i][i - 4] = 1.0; stl_mat[i][i - 2] = 1.0; } stl_mat[i][i] = 1.0; if (i + 10 < BENCHMARK_MATRIX_SIZE) { stl_mat[i][i + 5] = 1.0; stl_mat[i][i + 7] = 1.0; stl_mat[i][i + 9] = 1.0; stl_mat[i][i + 10] = 1.0; } } viennacl::copy(std_vec1, vcl_vec1); //initialize vectors with all zeros (no need to worry about overflows then) viennacl::copy(std_vec1, vcl_vec2); //initialize vectors with all zeros (no need to worry about overflows then) viennacl::copy(stl_mat, vcl_mat); typedef test_data<VCLScalar, VCLVector, VCLMatrix> TestDataType; test_data<VCLScalar, VCLVector, VCLMatrix> data(vcl_factor1, vcl_vec1, vcl_vec2, vcl_mat); ////////////////////////////////////////////////////////// ///////////// Start parameter recording ///////////////// ////////////////////////////////////////////////////////// typedef std::map< double, std::pair<unsigned int, unsigned int> > TimingType; std::map< std::string, TimingType > all_timings; //other kernels: std::cout << "------- Related to other operations ----------" << std::endl; config.kernel_name("vec_mul"); optimize_full(paras, all_timings[config.kernel_name()], matrix_vec_mul<TestDataType>, config, data); return 0; } int main() { std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << " Device Info" << std::endl; std::cout << "----------------------------------------------" << std::endl; viennacl::ocl::device dev = viennacl::ocl::current_device(); std::cout << dev.info() << std::endl; // ----------------------------------------- viennacl::io::parameter_database paras; // ----------------------------------------- std::string devname = dev.name(); std::string driver = dev.driver_version(); cl_uint compunits = dev.max_compute_units(); size_t wgsize = dev.max_workgroup_size(); // ----------------------------------------- paras.add_device(); paras.add_data_node(viennacl::io::tag::name, devname); paras.add_data_node(viennacl::io::tag::driver, driver); paras.add_data_node(viennacl::io::tag::compun, compunits); paras.add_data_node(viennacl::io::tag::workgrp, wgsize); // ----------------------------------------- //set up test config: test_config conf; conf.max_local_size(dev.max_work_group_size()); // GPU specific test setup: if (dev.type() == CL_DEVICE_TYPE_GPU) { unsigned int units = 1; while (2 * units < dev.compute_units()) units *= 2; conf.min_work_groups(units); conf.max_work_groups(512); //reasonable upper limit on current GPUs conf.min_local_size(16); //less than 16 threads per work group is unlikely to have any impact //conf.min_local_size(dev.max_work_group_size()); //testing only } else if (dev.type() == CL_DEVICE_TYPE_CPU)// CPU specific test setup { conf.min_work_groups(1); conf.max_work_groups(2*dev.compute_units()); //reasonable upper limit on current CPUs - more experience needed here! conf.min_local_size(1); } else { std::cerr << "Unknown device type (neither CPU nor GPU)! Aborting..." << std::endl; exit(0); } std::cout << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << "## Benchmark :: Matrix" << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << std::endl; std::cout << " -------------------------------" << std::endl; std::cout << " # benchmarking single-precision" << std::endl; std::cout << " -------------------------------" << std::endl; // ----------------------------------------- paras.add_test(); paras.add_data_node(viennacl::io::tag::name, viennacl::io::val::compmat); paras.add_data_node(viennacl::io::tag::numeric, viennacl::io::val::fl); paras.add_data_node(viennacl::io::tag::alignment, "1"); // ----------------------------------------- //set up test config: conf.program_name(viennacl::linalg::kernels::compressed_matrix<float, 1>::program_name()); run_matrix_benchmark<float>(conf, paras); if( viennacl::ocl::current_device().double_support() ) { std::cout << std::endl; std::cout << " -------------------------------" << std::endl; std::cout << " # benchmarking double-precision" << std::endl; std::cout << " -------------------------------" << std::endl; // ----------------------------------------- paras.add_test(); paras.add_data_node(viennacl::io::tag::name, viennacl::io::val::compmat); paras.add_data_node(viennacl::io::tag::numeric, viennacl::io::val::dbl); paras.add_data_node(viennacl::io::tag::alignment, "1"); conf.program_name(viennacl::linalg::kernels::compressed_matrix<double, 1>::program_name()); // ----------------------------------------- run_matrix_benchmark<double>(conf, paras); } // ----------------------------------------- //paras.dump(); // dump to terminal paras.dump("sparse_parameters.xml"); // dump to outputfile //std::ofstream stream; paras.dump(stream); // dump to stream // ----------------------------------------- std::cout << std::endl; std::cout << "/////////////////////////////////////////////////////////////////////////////////" << std::endl; std::cout << "// Parameter evaluation for viennacl::compressed_matrix finished successfully! //" << std::endl; std::cout << "/////////////////////////////////////////////////////////////////////////////////" << std::endl; return 0; }
/*************************************************************************/ /* scene_tree_dock.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "scene_tree_dock.h" #include "core/io/resource_saver.h" #include "core/os/keyboard.h" #include "core/project_settings.h" #include "editor/editor_node.h" #include "editor/editor_settings.h" #include "editor/multi_node_edit.h" #include "editor/plugins/animation_player_editor_plugin.h" #include "editor/plugins/canvas_item_editor_plugin.h" #include "editor/plugins/script_editor_plugin.h" #include "editor/plugins/spatial_editor_plugin.h" #include "editor/script_editor_debugger.h" #include "scene/main/viewport.h" #include "scene/resources/packed_scene.h" void SceneTreeDock::_nodes_drag_begin() { if (restore_script_editor_on_drag) { EditorNode::get_singleton()->set_visible_editor(EditorNode::EDITOR_SCRIPT); restore_script_editor_on_drag = false; } } void SceneTreeDock::_input(Ref<InputEvent> p_event) { Ref<InputEventMouseButton> mb = p_event; if (mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == BUTTON_LEFT) { restore_script_editor_on_drag = false; //lost chance } } void SceneTreeDock::_unhandled_key_input(Ref<InputEvent> p_event) { if (get_viewport()->get_modal_stack_top()) return; //ignore because of modal window if (get_focus_owner() && get_focus_owner()->is_text_field()) return; if (!p_event->is_pressed() || p_event->is_echo()) return; if (ED_IS_SHORTCUT("scene_tree/batch_rename", p_event)) { _tool_selected(TOOL_BATCH_RENAME); } else if (ED_IS_SHORTCUT("scene_tree/rename", p_event)) { _tool_selected(TOOL_RENAME); } else if (ED_IS_SHORTCUT("scene_tree/add_child_node", p_event)) { _tool_selected(TOOL_NEW); } else if (ED_IS_SHORTCUT("scene_tree/instance_scene", p_event)) { _tool_selected(TOOL_INSTANCE); } else if (ED_IS_SHORTCUT("scene_tree/change_node_type", p_event)) { _tool_selected(TOOL_REPLACE); } else if (ED_IS_SHORTCUT("scene_tree/duplicate", p_event)) { _tool_selected(TOOL_DUPLICATE); } else if (ED_IS_SHORTCUT("scene_tree/attach_script", p_event)) { _tool_selected(TOOL_ATTACH_SCRIPT); } else if (ED_IS_SHORTCUT("scene_tree/clear_script", p_event)) { _tool_selected(TOOL_CLEAR_SCRIPT); } else if (ED_IS_SHORTCUT("scene_tree/move_up", p_event)) { _tool_selected(TOOL_MOVE_UP); } else if (ED_IS_SHORTCUT("scene_tree/move_down", p_event)) { _tool_selected(TOOL_MOVE_DOWN); } else if (ED_IS_SHORTCUT("scene_tree/reparent", p_event)) { _tool_selected(TOOL_REPARENT); } else if (ED_IS_SHORTCUT("scene_tree/merge_from_scene", p_event)) { _tool_selected(TOOL_MERGE_FROM_SCENE); } else if (ED_IS_SHORTCUT("scene_tree/save_branch_as_scene", p_event)) { _tool_selected(TOOL_NEW_SCENE_FROM); } else if (ED_IS_SHORTCUT("scene_tree/delete_no_confirm", p_event)) { _tool_selected(TOOL_ERASE, true); } else if (ED_IS_SHORTCUT("scene_tree/copy_node_path", p_event)) { _tool_selected(TOOL_COPY_NODE_PATH); } else if (ED_IS_SHORTCUT("scene_tree/delete", p_event)) { _tool_selected(TOOL_ERASE); } } void SceneTreeDock::instance(const String &p_file) { Node *parent = scene_tree->get_selected(); if (!parent) { parent = edited_scene; }; if (!edited_scene) { current_option = -1; accept->set_text(TTR("No parent to instance a child at.")); accept->popup_centered_minsize(); return; }; ERR_FAIL_COND(!parent); Vector<String> scenes; scenes.push_back(p_file); _perform_instance_scenes(scenes, parent, -1); } void SceneTreeDock::instance_scenes(const Vector<String> &p_files, Node *p_parent) { Node *parent = p_parent; if (!parent) { parent = scene_tree->get_selected(); } if (!parent || !edited_scene) { accept->set_text(TTR("No parent to instance the scenes at.")); accept->popup_centered_minsize(); return; }; _perform_instance_scenes(p_files, parent, -1); } void SceneTreeDock::_perform_instance_scenes(const Vector<String> &p_files, Node *parent, int p_pos) { ERR_FAIL_COND(!parent); Vector<Node *> instances; bool error = false; for (int i = 0; i < p_files.size(); i++) { Ref<PackedScene> sdata = ResourceLoader::load(p_files[i]); if (!sdata.is_valid()) { current_option = -1; accept->set_text(vformat(TTR("Error loading scene from %s"), p_files[i])); accept->popup_centered_minsize(); error = true; break; } Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE); if (!instanced_scene) { current_option = -1; accept->set_text(vformat(TTR("Error instancing scene from %s"), p_files[i])); accept->popup_centered_minsize(); error = true; break; } if (edited_scene->get_filename() != "") { if (_cyclical_dependency_exists(edited_scene->get_filename(), instanced_scene)) { accept->set_text(vformat(TTR("Cannot instance the scene '%s' because the current scene exists within one of its nodes."), p_files[i])); accept->popup_centered_minsize(); error = true; break; } } instanced_scene->set_filename(ProjectSettings::get_singleton()->localize_path(p_files[i])); instances.push_back(instanced_scene); } if (error) { for (int i = 0; i < instances.size(); i++) { memdelete(instances[i]); } return; } editor_data->get_undo_redo().create_action(TTR("Instance Scene(s)")); for (int i = 0; i < instances.size(); i++) { Node *instanced_scene = instances[i]; editor_data->get_undo_redo().add_do_method(parent, "add_child", instanced_scene); if (p_pos >= 0) { editor_data->get_undo_redo().add_do_method(parent, "move_child", instanced_scene, p_pos + i); } editor_data->get_undo_redo().add_do_method(instanced_scene, "set_owner", edited_scene); editor_data->get_undo_redo().add_do_method(editor_selection, "clear"); editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", instanced_scene); editor_data->get_undo_redo().add_do_reference(instanced_scene); editor_data->get_undo_redo().add_undo_method(parent, "remove_child", instanced_scene); String new_name = parent->validate_child_name(instanced_scene); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_instance_node", edited_scene->get_path_to(parent), p_files[i], new_name); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)).plus_file(new_name))); } editor_data->get_undo_redo().commit_action(); } void SceneTreeDock::_replace_with_branch_scene(const String &p_file, Node *base) { Ref<PackedScene> sdata = ResourceLoader::load(p_file); if (!sdata.is_valid()) { accept->set_text(vformat(TTR("Error loading scene from %s"), p_file)); accept->popup_centered_minsize(); return; } Node *instanced_scene = sdata->instance(PackedScene::GEN_EDIT_STATE_INSTANCE); if (!instanced_scene) { accept->set_text(vformat(TTR("Error instancing scene from %s"), p_file)); accept->popup_centered_minsize(); return; } Node *parent = base->get_parent(); int pos = base->get_index(); parent->remove_child(base); parent->add_child(instanced_scene); parent->move_child(instanced_scene, pos); instanced_scene->set_owner(edited_scene); editor_selection->clear(); editor_selection->add_node(instanced_scene); scene_tree->set_selected(instanced_scene); // Delete the node as late as possible because before another one is selected // an editor plugin could be referencing it to do something with it before // switching to another (or to none); and since some steps of changing the // editor state are deferred, the safest thing is to do this is as the last // step of this function and also by enqueing instead of memdelete()-ing it here base->queue_delete(); } bool SceneTreeDock::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) { int childCount = p_desired_node->get_child_count(); if (p_desired_node->get_filename() == p_target_scene_path) { return true; } for (int i = 0; i < childCount; i++) { Node *child = p_desired_node->get_child(i); if (_cyclical_dependency_exists(p_target_scene_path, child)) { return true; } } return false; } void SceneTreeDock::_tool_selected(int p_tool, bool p_confirm_override) { current_option = p_tool; switch (p_tool) { case TOOL_BATCH_RENAME: { Tree *tree = scene_tree->get_scene_tree(); if (tree->is_anything_selected()) { rename_dialog->popup_centered(); } } break; case TOOL_RENAME: { Tree *tree = scene_tree->get_scene_tree(); if (tree->is_anything_selected()) { tree->grab_focus(); tree->edit_selected(); } } break; case TOOL_NEW: { String preferred = ""; Node *current_edited_scene_root = EditorNode::get_singleton()->get_edited_scene(); if (current_edited_scene_root) { if (ClassDB::is_parent_class(current_edited_scene_root->get_class_name(), "Node2D")) preferred = "Node2D"; else if (ClassDB::is_parent_class(current_edited_scene_root->get_class_name(), "Spatial")) preferred = "Spatial"; } create_dialog->set_preferred_search_result_type(preferred); create_dialog->popup_create(true); } break; case TOOL_INSTANCE: { Node *scene = edited_scene; if (!scene) { EditorNode::get_singleton()->new_inherited_scene(); break; } file->set_mode(EditorFileDialog::MODE_OPEN_FILE); List<String> extensions; ResourceLoader::get_recognized_extensions_for_type("PackedScene", &extensions); file->clear_filters(); for (int i = 0; i < extensions.size(); i++) { file->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); } file->popup_centered_ratio(); } break; case TOOL_REPLACE: { create_dialog->popup_create(false, true); } break; case TOOL_ATTACH_SCRIPT: { Node *selected = scene_tree->get_selected(); if (!selected) break; Ref<Script> existing = selected->get_script(); String path = selected->get_filename(); if (path == "") { String root_path = editor_data->get_edited_scene_root()->get_filename(); if (root_path == "") { path = String("res://").plus_file(selected->get_name()); } else { path = root_path.get_base_dir().plus_file(selected->get_name()); } } String inherits = selected->get_class(); if (existing.is_valid()) { for (int i = 0; i < ScriptServer::get_language_count(); i++) { ScriptLanguage *l = ScriptServer::get_language(i); if (l->get_type() == existing->get_class()) { String name = l->get_global_class_name(existing->get_path()); if (ScriptServer::is_global_class(name)) { if (EDITOR_GET("interface/editors/derive_script_globals_by_name").operator bool()) { inherits = editor->get_editor_data().script_class_get_base(name); } else if (l->can_inherit_from_file()) { inherits = "\"" + existing->get_path() + "\""; } } else { inherits = "\"" + existing->get_path() + "\""; } } } } script_create_dialog->config(inherits, path); script_create_dialog->popup_centered(); } break; case TOOL_CLEAR_SCRIPT: { List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.empty()) return; editor_data->get_undo_redo().create_action(TTR("Clear Script")); editor_data->get_undo_redo().add_do_method(editor, "push_item", (Script *)NULL); for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Ref<Script> existing = E->get()->get_script(); if (existing.is_valid()) { const RefPtr empty; editor_data->get_undo_redo().add_do_method(E->get(), "set_script", empty); editor_data->get_undo_redo().add_undo_method(E->get(), "set_script", existing); } } editor_data->get_undo_redo().add_do_method(this, "_update_script_button"); editor_data->get_undo_redo().add_undo_method(this, "_update_script_button"); editor_data->get_undo_redo().commit_action(); } break; case TOOL_MOVE_UP: case TOOL_MOVE_DOWN: { if (!scene_tree->get_selected()) break; if (scene_tree->get_selected() == edited_scene) { current_option = -1; accept->set_text(TTR("This operation can't be done on the tree root.")); accept->popup_centered_minsize(); break; } if (!_validate_no_foreign()) break; bool MOVING_DOWN = (p_tool == TOOL_MOVE_DOWN); bool MOVING_UP = !MOVING_DOWN; Node *common_parent = scene_tree->get_selected()->get_parent(); List<Node *> selection = editor_selection->get_selected_node_list(); selection.sort_custom<Node::Comparator>(); // sort by index if (MOVING_DOWN) selection.invert(); int lowest_id = common_parent->get_child_count() - 1; int highest_id = 0; for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { int index = E->get()->get_index(); if (index > highest_id) highest_id = index; if (index < lowest_id) lowest_id = index; if (E->get()->get_parent() != common_parent) common_parent = NULL; } if (!common_parent || (MOVING_DOWN && highest_id >= common_parent->get_child_count() - MOVING_DOWN) || (MOVING_UP && lowest_id == 0)) break; // one or more nodes can not be moved if (selection.size() == 1) editor_data->get_undo_redo().create_action(TTR("Move Node In Parent")); if (selection.size() > 1) editor_data->get_undo_redo().create_action(TTR("Move Nodes In Parent")); for (int i = 0; i < selection.size(); i++) { Node *top_node = selection[i]; Node *bottom_node = selection[selection.size() - 1 - i]; ERR_FAIL_COND(!top_node->get_parent()); ERR_FAIL_COND(!bottom_node->get_parent()); int bottom_node_pos = bottom_node->get_index(); int top_node_pos_next = top_node->get_index() + (MOVING_DOWN ? 1 : -1); editor_data->get_undo_redo().add_do_method(top_node->get_parent(), "move_child", top_node, top_node_pos_next); editor_data->get_undo_redo().add_undo_method(bottom_node->get_parent(), "move_child", bottom_node, bottom_node_pos); } editor_data->get_undo_redo().commit_action(); } break; case TOOL_DUPLICATE: { if (!edited_scene) break; if (editor_selection->is_selected(edited_scene)) { current_option = -1; accept->set_text(TTR("This operation can't be done on the tree root.")); accept->popup_centered_minsize(); break; } if (!_validate_no_foreign()) break; List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() == 0) break; editor_data->get_undo_redo().create_action(TTR("Duplicate Node(s)")); editor_data->get_undo_redo().add_do_method(editor_selection, "clear"); Node *dupsingle = NULL; for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Node *node = E->get(); Node *parent = node->get_parent(); List<Node *> owned; node->get_owned_by(node->get_owner(), &owned); Map<const Node *, Node *> duplimap; Node *dup = node->duplicate_from_editor(duplimap); ERR_CONTINUE(!dup); if (selection.size() == 1) dupsingle = dup; dup->set_name(parent->validate_child_name(dup)); editor_data->get_undo_redo().add_do_method(parent, "add_child_below_node", node, dup); for (List<Node *>::Element *F = owned.front(); F; F = F->next()) { if (!duplimap.has(F->get())) { continue; } Node *d = duplimap[F->get()]; editor_data->get_undo_redo().add_do_method(d, "set_owner", node->get_owner()); } editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", dup); editor_data->get_undo_redo().add_undo_method(parent, "remove_child", dup); editor_data->get_undo_redo().add_do_reference(dup); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_duplicate_node", edited_scene->get_path_to(node), dup->get_name()); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)).plus_file(dup->get_name()))); } editor_data->get_undo_redo().commit_action(); if (dupsingle) editor->push_item(dupsingle); } break; case TOOL_REPARENT: { if (!scene_tree->get_selected()) break; if (editor_selection->is_selected(edited_scene)) { current_option = -1; accept->set_text(TTR("This operation can't be done on the tree root.")); accept->popup_centered_minsize(); break; } if (!_validate_no_foreign()) break; List<Node *> nodes = editor_selection->get_selected_node_list(); Set<Node *> nodeset; for (List<Node *>::Element *E = nodes.front(); E; E = E->next()) { nodeset.insert(E->get()); } reparent_dialog->popup_centered_ratio(); reparent_dialog->set_current(nodeset); } break; case TOOL_MAKE_ROOT: { List<Node *> nodes = editor_selection->get_selected_node_list(); ERR_FAIL_COND(nodes.size() != 1); Node *node = nodes.front()->get(); Node *root = get_tree()->get_edited_scene_root(); if (node == root) return; editor_data->get_undo_redo().create_action("Make node as Root"); _node_replace_owner(root, node, node, MODE_DO); editor_data->get_undo_redo().add_do_method(node->get_parent(), "remove_child", node); editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", node); editor_data->get_undo_redo().add_do_method(node, "set_filename", root->get_filename()); editor_data->get_undo_redo().add_undo_method(node, "set_filename", String()); editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", root); editor_data->get_undo_redo().add_undo_method(node->get_parent(), "add_child", node); _node_replace_owner(root, node, root, MODE_UNDO); editor_data->get_undo_redo().add_do_method(scene_tree, "update_tree"); editor_data->get_undo_redo().add_undo_method(scene_tree, "update_tree"); editor_data->get_undo_redo().add_undo_reference(root); editor_data->get_undo_redo().commit_action(); } break; case TOOL_MULTI_EDIT: { Node *root = EditorNode::get_singleton()->get_edited_scene(); if (!root) break; Ref<MultiNodeEdit> mne = memnew(MultiNodeEdit); for (const Map<Node *, Object *>::Element *E = EditorNode::get_singleton()->get_editor_selection()->get_selection().front(); E; E = E->next()) { mne->add_node(root->get_path_to(E->key())); } EditorNode::get_singleton()->push_item(mne.ptr()); } break; case TOOL_ERASE: { List<Node *> remove_list = editor_selection->get_selected_node_list(); if (remove_list.empty()) return; if (!_validate_no_foreign()) break; if (p_confirm_override) { _delete_confirm(); } else { delete_dialog->set_text(TTR("Delete Node(s)?")); delete_dialog->popup_centered_minsize(); } } break; case TOOL_MERGE_FROM_SCENE: { EditorNode::get_singleton()->merge_from_scene(); } break; case TOOL_NEW_SCENE_FROM: { Node *scene = editor_data->get_edited_scene_root(); if (!scene) { accept->set_text(TTR("This operation can't be done without a scene.")); accept->popup_centered_minsize(); break; } List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() != 1) { accept->set_text(TTR("This operation requires a single selected node.")); accept->popup_centered_minsize(); break; } Node *tocopy = selection.front()->get(); if (tocopy == scene) { accept->set_text(TTR("Can not perform with the root node.")); accept->popup_centered_minsize(); break; } if (tocopy != editor_data->get_edited_scene_root() && tocopy->get_filename() != "") { accept->set_text(TTR("This operation can't be done on instanced scenes.")); accept->popup_centered_minsize(); break; } new_scene_from_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); List<String> extensions; Ref<PackedScene> sd = memnew(PackedScene); ResourceSaver::get_recognized_extensions(sd, &extensions); new_scene_from_dialog->clear_filters(); for (int i = 0; i < extensions.size(); i++) { new_scene_from_dialog->add_filter("*." + extensions[i] + " ; " + extensions[i].to_upper()); } String existing; if (extensions.size()) { String root_name(tocopy->get_name()); existing = root_name + "." + extensions.front()->get().to_lower(); } new_scene_from_dialog->set_current_path(existing); new_scene_from_dialog->popup_centered_ratio(); new_scene_from_dialog->set_title(TTR("Save New Scene As...")); } break; case TOOL_COPY_NODE_PATH: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { Node *root = EditorNode::get_singleton()->get_edited_scene(); NodePath path = root->get_path().rel_path_to(node->get_path()); OS::get_singleton()->set_clipboard(path); } } } break; case TOOL_SCENE_EDITABLE_CHILDREN: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { bool editable = EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(node); int editable_item_idx = menu->get_item_idx_from_text(TTR("Editable Children")); int placeholder_item_idx = menu->get_item_idx_from_text(TTR("Load As Placeholder")); editable = !editable; EditorNode::get_singleton()->get_edited_scene()->set_editable_instance(node, editable); menu->set_item_checked(editable_item_idx, editable); if (editable) { node->set_scene_instance_load_placeholder(false); menu->set_item_checked(placeholder_item_idx, false); } SpatialEditor::get_singleton()->update_all_gizmos(node); scene_tree->update_tree(); } } } break; case TOOL_SCENE_USE_PLACEHOLDER: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { bool placeholder = node->get_scene_instance_load_placeholder(); placeholder = !placeholder; int editable_item_idx = menu->get_item_idx_from_text(TTR("Editable Children")); int placeholder_item_idx = menu->get_item_idx_from_text(TTR("Load As Placeholder")); if (placeholder) EditorNode::get_singleton()->get_edited_scene()->set_editable_instance(node, false); node->set_scene_instance_load_placeholder(placeholder); menu->set_item_checked(editable_item_idx, false); menu->set_item_checked(placeholder_item_idx, placeholder); scene_tree->update_tree(); } } } break; case TOOL_SCENE_MAKE_LOCAL: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { Node *root = EditorNode::get_singleton()->get_edited_scene(); UndoRedo *undo_redo = &editor_data->get_undo_redo(); if (!root) break; ERR_FAIL_COND(node->get_filename() == String()); undo_redo->create_action(TTR("Make Local")); undo_redo->add_do_method(node, "set_filename", ""); undo_redo->add_undo_method(node, "set_filename", node->get_filename()); _node_replace_owner(node, node, root); undo_redo->add_do_method(scene_tree, "update_tree"); undo_redo->add_undo_method(scene_tree, "update_tree"); undo_redo->commit_action(); } } } break; case TOOL_SCENE_OPEN: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { scene_tree->emit_signal("open", node->get_filename()); } } } break; case TOOL_SCENE_CLEAR_INHERITANCE: { clear_inherit_confirm->popup_centered_minsize(); } break; case TOOL_SCENE_CLEAR_INHERITANCE_CONFIRM: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { node->set_scene_inherited_state(Ref<SceneState>()); scene_tree->update_tree(); EditorNode::get_singleton()->get_inspector()->update_tree(); } } } break; case TOOL_SCENE_OPEN_INHERITED: { List<Node *> selection = editor_selection->get_selected_node_list(); List<Node *>::Element *e = selection.front(); if (e) { Node *node = e->get(); if (node) { if (node && node->get_scene_inherited_state().is_valid()) { scene_tree->emit_signal("open", node->get_scene_inherited_state()->get_path()); } } } } break; case TOOL_CREATE_2D_SCENE: case TOOL_CREATE_3D_SCENE: case TOOL_CREATE_USER_INTERFACE: case TOOL_CREATE_FAVORITE: { Node *new_node; if (TOOL_CREATE_FAVORITE == p_tool) { String name = selected_favorite_root.get_slicec(' ', 0); if (ScriptServer::is_global_class(name)) { new_node = Object::cast_to<Node>(ClassDB::instance(ScriptServer::get_global_class_base(name))); Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(name), "Script"); if (new_node && script.is_valid()) { new_node->set_script(script.get_ref_ptr()); new_node->set_name(name); } } else { new_node = Object::cast_to<Node>(ClassDB::instance(selected_favorite_root)); } if (!new_node) { ERR_EXPLAIN("Creating root from favorite '" + selected_favorite_root + "' failed. Creating 'Node' instead."); new_node = memnew(Node); } } else { switch (p_tool) { case TOOL_CREATE_2D_SCENE: new_node = memnew(Node2D); break; case TOOL_CREATE_3D_SCENE: new_node = memnew(Spatial); break; case TOOL_CREATE_USER_INTERFACE: { Control *node = memnew(Control); node->set_anchors_and_margins_preset(PRESET_WIDE); //more useful for resizable UIs. new_node = node; } break; } } editor_data->get_undo_redo().create_action("New Scene Root"); editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", new_node); editor_data->get_undo_redo().add_do_method(scene_tree, "update_tree"); editor_data->get_undo_redo().add_do_reference(new_node); editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", (Object *)NULL); editor_data->get_undo_redo().commit_action(); editor->edit_node(new_node); } break; default: { if (p_tool >= EDIT_SUBRESOURCE_BASE) { int idx = p_tool - EDIT_SUBRESOURCE_BASE; ERR_FAIL_INDEX(idx, subresources.size()); Object *obj = ObjectDB::get_instance(subresources[idx]); ERR_FAIL_COND(!obj); editor->push_item(obj); } } } } void SceneTreeDock::_notification(int p_what) { switch (p_what) { case NOTIFICATION_READY: { if (!first_enter) break; first_enter = false; CanvasItemEditorPlugin *canvas_item_plugin = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor("2D")); if (canvas_item_plugin) { canvas_item_plugin->get_canvas_item_editor()->connect("item_lock_status_changed", scene_tree, "_update_tree"); canvas_item_plugin->get_canvas_item_editor()->connect("item_group_status_changed", scene_tree, "_update_tree"); scene_tree->connect("node_changed", canvas_item_plugin->get_canvas_item_editor()->get_viewport_control(), "update"); } SpatialEditorPlugin *spatial_editor_plugin = Object::cast_to<SpatialEditorPlugin>(editor_data->get_editor("3D")); spatial_editor_plugin->get_spatial_editor()->connect("item_lock_status_changed", scene_tree, "_update_tree"); button_add->set_icon(get_icon("Add", "EditorIcons")); button_instance->set_icon(get_icon("Instance", "EditorIcons")); button_create_script->set_icon(get_icon("ScriptCreate", "EditorIcons")); button_clear_script->set_icon(get_icon("ScriptRemove", "EditorIcons")); filter->set_right_icon(get_icon("Search", "EditorIcons")); filter->set_clear_button_enabled(true); EditorNode::get_singleton()->get_editor_selection()->connect("selection_changed", this, "_selection_changed"); // create_root_dialog HBoxContainer *top_row = memnew(HBoxContainer); top_row->set_name("NodeShortcutsTopRow"); top_row->set_h_size_flags(SIZE_EXPAND_FILL); top_row->add_child(memnew(Label(TTR("Create Root Node:")))); top_row->add_spacer(); ToolButton *node_shortcuts_toggle = memnew(ToolButton); node_shortcuts_toggle->set_name("NodeShortcutsToggle"); node_shortcuts_toggle->set_icon(get_icon("Favorites", "EditorIcons")); node_shortcuts_toggle->set_toggle_mode(true); node_shortcuts_toggle->set_pressed(EDITOR_GET("_use_favorites_root_selection")); node_shortcuts_toggle->set_anchors_and_margins_preset(Control::PRESET_CENTER_RIGHT); node_shortcuts_toggle->connect("pressed", this, "_update_create_root_dialog"); top_row->add_child(node_shortcuts_toggle); create_root_dialog->add_child(top_row); VBoxContainer *node_shortcuts = memnew(VBoxContainer); node_shortcuts->set_name("NodeShortcuts"); VBoxContainer *beginner_node_shortcuts = memnew(VBoxContainer); beginner_node_shortcuts->set_name("BeginnerNodeShortcuts"); node_shortcuts->add_child(beginner_node_shortcuts); Button *button_2d = memnew(Button); beginner_node_shortcuts->add_child(button_2d); button_2d->set_text(TTR("2D Scene")); button_2d->set_icon(get_icon("Node2D", "EditorIcons")); button_2d->connect("pressed", this, "_tool_selected", make_binds(TOOL_CREATE_2D_SCENE, false)); Button *button_3d = memnew(Button); beginner_node_shortcuts->add_child(button_3d); button_3d->set_text(TTR("3D Scene")); button_3d->set_icon(get_icon("Spatial", "EditorIcons")); button_3d->connect("pressed", this, "_tool_selected", make_binds(TOOL_CREATE_3D_SCENE, false)); Button *button_ui = memnew(Button); beginner_node_shortcuts->add_child(button_ui); button_ui->set_text(TTR("User Interface")); button_ui->set_icon(get_icon("Control", "EditorIcons")); button_ui->connect("pressed", this, "_tool_selected", make_binds(TOOL_CREATE_USER_INTERFACE, false)); VBoxContainer *favorite_node_shortcuts = memnew(VBoxContainer); favorite_node_shortcuts->set_name("FavoriteNodeShortcuts"); node_shortcuts->add_child(favorite_node_shortcuts); Button *button_custom = memnew(Button); node_shortcuts->add_child(button_custom); button_custom->set_text(TTR("Custom Node")); button_custom->set_icon(get_icon("Add", "EditorIcons")); button_custom->connect("pressed", this, "_tool_selected", make_binds(TOOL_NEW, false)); node_shortcuts->add_spacer(); create_root_dialog->add_child(node_shortcuts); _update_create_root_dialog(); } break; case NOTIFICATION_ENTER_TREE: { clear_inherit_confirm->connect("confirmed", this, "_tool_selected", varray(TOOL_SCENE_CLEAR_INHERITANCE_CONFIRM)); } break; case NOTIFICATION_EXIT_TREE: { clear_inherit_confirm->disconnect("confirmed", this, "_tool_selected"); } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { button_add->set_icon(get_icon("Add", "EditorIcons")); button_instance->set_icon(get_icon("Instance", "EditorIcons")); button_create_script->set_icon(get_icon("ScriptCreate", "EditorIcons")); button_clear_script->set_icon(get_icon("ScriptRemove", "EditorIcons")); filter->set_right_icon(get_icon("Search", "EditorIcons")); filter->set_clear_button_enabled(true); } break; case NOTIFICATION_PROCESS: { bool show_create_root = bool(EDITOR_GET("interface/editors/show_scene_tree_root_selection")) && get_tree()->get_edited_scene_root() == NULL; if (show_create_root != create_root_dialog->is_visible_in_tree()) { if (show_create_root) { create_root_dialog->show(); scene_tree->hide(); } else { create_root_dialog->hide(); scene_tree->show(); } } } break; } } void SceneTreeDock::_node_replace_owner(Node *p_base, Node *p_node, Node *p_root, ReplaceOwnerMode p_mode) { if (p_base != p_node) { if (p_node->get_owner() == p_base) { UndoRedo *undo_redo = &editor_data->get_undo_redo(); switch (p_mode) { case MODE_BIDI: { undo_redo->add_do_method(p_node, "set_owner", p_root); undo_redo->add_undo_method(p_node, "set_owner", p_base); } break; case MODE_DO: { undo_redo->add_do_method(p_node, "set_owner", p_root); } break; case MODE_UNDO: { undo_redo->add_undo_method(p_node, "set_owner", p_root); } break; } } } for (int i = 0; i < p_node->get_child_count(); i++) { _node_replace_owner(p_base, p_node->get_child(i), p_root, p_mode); } } void SceneTreeDock::_load_request(const String &p_path) { editor->open_request(p_path); } void SceneTreeDock::_script_open_request(const Ref<Script> &p_script) { editor->edit_resource(p_script); } void SceneTreeDock::_node_selected() { Node *node = scene_tree->get_selected(); if (!node) { editor->push_item(NULL); return; } if (ScriptEditor::get_singleton()->is_visible_in_tree()) { restore_script_editor_on_drag = true; } editor->push_item(node); } void SceneTreeDock::_node_renamed() { _node_selected(); } void SceneTreeDock::_set_owners(Node *p_owner, const Array &p_nodes) { for (int i = 0; i < p_nodes.size(); i++) { Node *n = Object::cast_to<Node>(p_nodes[i]); if (!n) continue; n->set_owner(p_owner); } } void SceneTreeDock::_fill_path_renames(Vector<StringName> base_path, Vector<StringName> new_base_path, Node *p_node, List<Pair<NodePath, NodePath> > *p_renames) { base_path.push_back(p_node->get_name()); if (new_base_path.size()) new_base_path.push_back(p_node->get_name()); NodePath from(base_path, true); NodePath to; if (new_base_path.size()) to = NodePath(new_base_path, true); Pair<NodePath, NodePath> npp; npp.first = from; npp.second = to; p_renames->push_back(npp); for (int i = 0; i < p_node->get_child_count(); i++) { _fill_path_renames(base_path, new_base_path, p_node->get_child(i), p_renames); } } void SceneTreeDock::fill_path_renames(Node *p_node, Node *p_new_parent, List<Pair<NodePath, NodePath> > *p_renames) { if (!bool(EDITOR_DEF("editors/animation/autorename_animation_tracks", true))) return; Vector<StringName> base_path; Node *n = p_node->get_parent(); while (n) { base_path.push_back(n->get_name()); n = n->get_parent(); } base_path.invert(); Vector<StringName> new_base_path; if (p_new_parent) { n = p_new_parent; while (n) { new_base_path.push_back(n->get_name()); n = n->get_parent(); } new_base_path.invert(); } _fill_path_renames(base_path, new_base_path, p_node, p_renames); } void SceneTreeDock::perform_node_renames(Node *p_base, List<Pair<NodePath, NodePath> > *p_renames, Map<Ref<Animation>, Set<int> > *r_rem_anims) { Map<Ref<Animation>, Set<int> > rem_anims; if (!r_rem_anims) r_rem_anims = &rem_anims; if (!p_base) { p_base = edited_scene; } if (!p_base) return; // Renaming node paths used in script instances if (p_base->get_script_instance()) { ScriptInstance *si = p_base->get_script_instance(); if (si) { List<PropertyInfo> properties; si->get_property_list(&properties); for (List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { String propertyname = E->get().name; Variant p = p_base->get(propertyname); if (p.get_type() == Variant::NODE_PATH) { // Goes through all paths to check if its matching for (List<Pair<NodePath, NodePath> >::Element *E = p_renames->front(); E; E = E->next()) { NodePath root_path = p_base->get_path(); NodePath rel_path_old = root_path.rel_path_to(E->get().first); NodePath rel_path_new = E->get().second; // if not empty, get new relative path if (E->get().second != NodePath()) { rel_path_new = root_path.rel_path_to(E->get().second); } // if old path detected, then it needs to be replaced with the new one if (p == rel_path_old) { editor_data->get_undo_redo().add_do_property(p_base, propertyname, rel_path_new); editor_data->get_undo_redo().add_undo_property(p_base, propertyname, rel_path_old); p_base->set(propertyname, rel_path_new); break; } } } } } } bool autorename_animation_tracks = bool(EDITOR_DEF("editors/animation/autorename_animation_tracks", true)); if (autorename_animation_tracks && Object::cast_to<AnimationPlayer>(p_base)) { AnimationPlayer *ap = Object::cast_to<AnimationPlayer>(p_base); List<StringName> anims; ap->get_animation_list(&anims); Node *root = ap->get_node(ap->get_root()); if (root) { NodePath root_path = root->get_path(); NodePath new_root_path = root_path; for (List<Pair<NodePath, NodePath> >::Element *E = p_renames->front(); E; E = E->next()) { if (E->get().first == root_path) { new_root_path = E->get().second; break; } } if (new_root_path != NodePath()) { //will not be erased for (List<StringName>::Element *E = anims.front(); E; E = E->next()) { Ref<Animation> anim = ap->get_animation(E->get()); if (!r_rem_anims->has(anim)) { r_rem_anims->insert(anim, Set<int>()); Set<int> &ran = r_rem_anims->find(anim)->get(); for (int i = 0; i < anim->get_track_count(); i++) ran.insert(i); } Set<int> &ran = r_rem_anims->find(anim)->get(); if (anim.is_null()) continue; for (int i = 0; i < anim->get_track_count(); i++) { NodePath track_np = anim->track_get_path(i); Node *n = root->get_node(track_np); if (!n) { continue; } NodePath old_np = n->get_path(); if (!ran.has(i)) continue; //channel was removed for (List<Pair<NodePath, NodePath> >::Element *E = p_renames->front(); E; E = E->next()) { if (E->get().first == old_np) { if (E->get().second == NodePath()) { //will be erased int idx = 0; Set<int>::Element *EI = ran.front(); ERR_FAIL_COND(!EI); //bug while (EI->get() != i) { idx++; EI = EI->next(); ERR_FAIL_COND(!EI); //another bug } editor_data->get_undo_redo().add_do_method(anim.ptr(), "remove_track", idx); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "add_track", anim->track_get_type(i), idx); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_path", idx, track_np); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_interpolation_type", idx, anim->track_get_interpolation_type(i)); for (int j = 0; j < anim->track_get_key_count(i); j++) { editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_insert_key", idx, anim->track_get_key_time(i, j), anim->track_get_key_value(i, j), anim->track_get_key_transition(i, j)); } ran.erase(i); //byebye channel } else { //will be renamed NodePath rel_path = new_root_path.rel_path_to(E->get().second); NodePath new_path = NodePath(rel_path.get_names(), track_np.get_subnames(), false); if (new_path == track_np) continue; //bleh editor_data->get_undo_redo().add_do_method(anim.ptr(), "track_set_path", i, new_path); editor_data->get_undo_redo().add_undo_method(anim.ptr(), "track_set_path", i, track_np); } } } } } } } } for (int i = 0; i < p_base->get_child_count(); i++) perform_node_renames(p_base->get_child(i), p_renames, r_rem_anims); } void SceneTreeDock::_node_prerenamed(Node *p_node, const String &p_new_name) { List<Pair<NodePath, NodePath> > path_renames; Vector<StringName> base_path; Node *n = p_node->get_parent(); while (n) { base_path.push_back(n->get_name()); n = n->get_parent(); } base_path.invert(); Vector<StringName> new_base_path = base_path; base_path.push_back(p_node->get_name()); new_base_path.push_back(p_new_name); Pair<NodePath, NodePath> npp; npp.first = NodePath(base_path, true); npp.second = NodePath(new_base_path, true); path_renames.push_back(npp); for (int i = 0; i < p_node->get_child_count(); i++) _fill_path_renames(base_path, new_base_path, p_node->get_child(i), &path_renames); perform_node_renames(NULL, &path_renames); } bool SceneTreeDock::_validate_no_foreign() { List<Node *> selection = editor_selection->get_selected_node_list(); for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { if (E->get() != edited_scene && E->get()->get_owner() != edited_scene) { accept->set_text(TTR("Can't operate on nodes from a foreign scene!")); accept->popup_centered_minsize(); return false; } if (edited_scene->get_scene_inherited_state().is_valid() && edited_scene->get_scene_inherited_state()->find_node_by_path(edited_scene->get_path_to(E->get())) >= 0) { accept->set_text(TTR("Can't operate on nodes the current scene inherits from!")); accept->popup_centered_minsize(); return false; } } return true; } void SceneTreeDock::_node_reparent(NodePath p_path, bool p_keep_global_xform) { Node *new_parent = scene_root->get_node(p_path); ERR_FAIL_COND(!new_parent); List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.empty()) return; //nothing to reparent Vector<Node *> nodes; for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { nodes.push_back(E->get()); } _do_reparent(new_parent, -1, nodes, p_keep_global_xform); } void SceneTreeDock::_do_reparent(Node *p_new_parent, int p_position_in_parent, Vector<Node *> p_nodes, bool p_keep_global_xform) { Node *new_parent = p_new_parent; ERR_FAIL_COND(!new_parent); Node *validate = new_parent; while (validate) { if (p_nodes.find(validate) != -1) { ERR_EXPLAIN("Selection changed at some point.. can't reparent"); ERR_FAIL(); return; } validate = validate->get_parent(); } //ok all valid if (p_nodes.size() == 0) return; //nothing to reparent //sort by tree order, so re-adding is easy p_nodes.sort_custom<Node::Comparator>(); editor_data->get_undo_redo().create_action(TTR("Reparent Node")); List<Pair<NodePath, NodePath> > path_renames; Vector<StringName> former_names; int inc = 0; for (int ni = 0; ni < p_nodes.size(); ni++) { //no undo for now, sorry Node *node = p_nodes[ni]; fill_path_renames(node, new_parent, &path_renames); former_names.push_back(node->get_name()); List<Node *> owned; node->get_owned_by(node->get_owner(), &owned); Array owners; for (List<Node *>::Element *E = owned.front(); E; E = E->next()) { owners.push_back(E->get()); } if (new_parent == node->get_parent() && node->get_index() < p_position_in_parent + ni) { //if child will generate a gap when moved, adjust inc--; } editor_data->get_undo_redo().add_do_method(node->get_parent(), "remove_child", node); editor_data->get_undo_redo().add_do_method(new_parent, "add_child", node); if (p_position_in_parent >= 0) editor_data->get_undo_redo().add_do_method(new_parent, "move_child", node, p_position_in_parent + inc); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); String old_name = former_names[ni]; String new_name = new_parent->validate_child_name(node); // name was modified, fix the path renames if (old_name.casecmp_to(new_name) != 0) { // Fix the to name to have the new name NodePath old_new_name = path_renames[ni].second; NodePath new_path; Vector<StringName> unfixed_new_names = old_new_name.get_names(); Vector<StringName> fixed_new_names; // Get last name and replace with fixed new name for (int a = 0; a < (unfixed_new_names.size() - 1); a++) { fixed_new_names.push_back(unfixed_new_names[a]); } fixed_new_names.push_back(new_name); NodePath fixed_node_path = NodePath(fixed_new_names, true); path_renames[ni].second = fixed_node_path; } editor_data->get_undo_redo().add_do_method(sed, "live_debug_reparent_node", edited_scene->get_path_to(node), edited_scene->get_path_to(new_parent), new_name, p_position_in_parent + inc); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_reparent_node", NodePath(String(edited_scene->get_path_to(new_parent)).plus_file(new_name)), edited_scene->get_path_to(node->get_parent()), node->get_name(), node->get_index()); if (p_keep_global_xform) { if (Object::cast_to<Node2D>(node)) editor_data->get_undo_redo().add_do_method(node, "set_global_transform", Object::cast_to<Node2D>(node)->get_global_transform()); if (Object::cast_to<Spatial>(node)) editor_data->get_undo_redo().add_do_method(node, "set_global_transform", Object::cast_to<Spatial>(node)->get_global_transform()); if (Object::cast_to<Control>(node)) editor_data->get_undo_redo().add_do_method(node, "set_global_position", Object::cast_to<Control>(node)->get_global_position()); } editor_data->get_undo_redo().add_do_method(this, "_set_owners", edited_scene, owners); if (AnimationPlayerEditor::singleton->get_track_editor()->get_root() == node) editor_data->get_undo_redo().add_do_method(AnimationPlayerEditor::singleton->get_track_editor(), "set_root", node); editor_data->get_undo_redo().add_undo_method(new_parent, "remove_child", node); editor_data->get_undo_redo().add_undo_method(node, "set_name", former_names[ni]); inc++; } //add and move in a second step.. (so old order is preserved) for (int ni = 0; ni < p_nodes.size(); ni++) { Node *node = p_nodes[ni]; List<Node *> owned; node->get_owned_by(node->get_owner(), &owned); Array owners; for (List<Node *>::Element *E = owned.front(); E; E = E->next()) { owners.push_back(E->get()); } int child_pos = node->get_position_in_parent(); editor_data->get_undo_redo().add_undo_method(node->get_parent(), "add_child", node); editor_data->get_undo_redo().add_undo_method(node->get_parent(), "move_child", node, child_pos); editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners); if (AnimationPlayerEditor::singleton->get_track_editor()->get_root() == node) editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_track_editor(), "set_root", node); if (p_keep_global_xform) { if (Object::cast_to<Node2D>(node)) editor_data->get_undo_redo().add_undo_method(node, "set_transform", Object::cast_to<Node2D>(node)->get_transform()); if (Object::cast_to<Spatial>(node)) editor_data->get_undo_redo().add_undo_method(node, "set_transform", Object::cast_to<Spatial>(node)->get_transform()); if (Object::cast_to<Control>(node)) editor_data->get_undo_redo().add_undo_method(node, "set_position", Object::cast_to<Control>(node)->get_position()); } } perform_node_renames(NULL, &path_renames); editor_data->get_undo_redo().commit_action(); } void SceneTreeDock::_script_created(Ref<Script> p_script) { List<Node *> selected = editor_selection->get_selected_node_list(); if (selected.empty()) return; editor_data->get_undo_redo().create_action(TTR("Attach Script")); for (List<Node *>::Element *E = selected.front(); E; E = E->next()) { Ref<Script> existing = E->get()->get_script(); editor_data->get_undo_redo().add_do_method(E->get(), "set_script", p_script.get_ref_ptr()); editor_data->get_undo_redo().add_undo_method(E->get(), "set_script", existing); } editor_data->get_undo_redo().commit_action(); editor->push_item(p_script.operator->()); } void SceneTreeDock::_delete_confirm() { List<Node *> remove_list = editor_selection->get_selected_node_list(); if (remove_list.empty()) return; editor->get_editor_plugins_over()->make_visible(false); editor_data->get_undo_redo().create_action(TTR("Remove Node(s)")); bool entire_scene = false; for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) { if (E->get() == edited_scene) { entire_scene = true; } } if (entire_scene) { editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", (Object *)NULL); editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", edited_scene); editor_data->get_undo_redo().add_undo_method(edited_scene, "set_owner", edited_scene->get_owner()); editor_data->get_undo_redo().add_undo_method(scene_tree, "update_tree"); editor_data->get_undo_redo().add_undo_reference(edited_scene); } else { remove_list.sort_custom<Node::Comparator>(); //sort nodes to keep positions List<Pair<NodePath, NodePath> > path_renames; //delete from animation for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) { Node *n = E->get(); if (!n->is_inside_tree() || !n->get_parent()) continue; fill_path_renames(n, NULL, &path_renames); } perform_node_renames(NULL, &path_renames); //delete for read for (List<Node *>::Element *E = remove_list.front(); E; E = E->next()) { Node *n = E->get(); if (!n->is_inside_tree() || !n->get_parent()) continue; List<Node *> owned; n->get_owned_by(n->get_owner(), &owned); Array owners; for (List<Node *>::Element *E = owned.front(); E; E = E->next()) { owners.push_back(E->get()); } editor_data->get_undo_redo().add_do_method(n->get_parent(), "remove_child", n); editor_data->get_undo_redo().add_undo_method(n->get_parent(), "add_child", n); editor_data->get_undo_redo().add_undo_method(n->get_parent(), "move_child", n, n->get_index()); if (AnimationPlayerEditor::singleton->get_track_editor()->get_root() == n) editor_data->get_undo_redo().add_undo_method(AnimationPlayerEditor::singleton->get_track_editor(), "set_root", n); editor_data->get_undo_redo().add_undo_method(this, "_set_owners", edited_scene, owners); editor_data->get_undo_redo().add_undo_reference(n); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_remove_and_keep_node", edited_scene->get_path_to(n), n->get_instance_id()); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_restore_node", n->get_instance_id(), edited_scene->get_path_to(n->get_parent()), n->get_index()); } } editor_data->get_undo_redo().commit_action(); // hack, force 2d editor viewport to refresh after deletion if (CanvasItemEditor *editor = CanvasItemEditor::get_singleton()) editor->get_viewport_control()->update(); editor->push_item(NULL); // Fixes the EditorHistory from still offering deleted notes EditorHistory *editor_history = EditorNode::get_singleton()->get_editor_history(); editor_history->cleanup_history(); EditorNode::get_singleton()->call("_prepare_history"); } void SceneTreeDock::_update_script_button() { if (EditorNode::get_singleton()->get_editor_selection()->get_selection().size() == 1) { button_create_script->show(); } else { button_create_script->hide(); } } void SceneTreeDock::_selection_changed() { int selection_size = EditorNode::get_singleton()->get_editor_selection()->get_selection().size(); if (selection_size > 1) { //automatically turn on multi-edit _tool_selected(TOOL_MULTI_EDIT); } _update_script_button(); } void SceneTreeDock::_create() { if (current_option == TOOL_NEW) { Node *parent = NULL; if (edited_scene) { // If root exists in edited scene parent = scene_tree->get_selected(); if (!parent) parent = edited_scene; } else { // If no root exist in edited scene parent = scene_root; ERR_FAIL_COND(!parent); } Object *c = create_dialog->instance_selected(); ERR_FAIL_COND(!c); Node *child = Object::cast_to<Node>(c); ERR_FAIL_COND(!child); editor_data->get_undo_redo().create_action(TTR("Create Node")); if (edited_scene) { editor_data->get_undo_redo().add_do_method(parent, "add_child", child); editor_data->get_undo_redo().add_do_method(child, "set_owner", edited_scene); editor_data->get_undo_redo().add_do_method(editor_selection, "clear"); editor_data->get_undo_redo().add_do_method(editor_selection, "add_node", child); editor_data->get_undo_redo().add_do_reference(child); editor_data->get_undo_redo().add_undo_method(parent, "remove_child", child); String new_name = parent->validate_child_name(child); ScriptEditorDebugger *sed = ScriptEditor::get_singleton()->get_debugger(); editor_data->get_undo_redo().add_do_method(sed, "live_debug_create_node", edited_scene->get_path_to(parent), child->get_class(), new_name); editor_data->get_undo_redo().add_undo_method(sed, "live_debug_remove_node", NodePath(String(edited_scene->get_path_to(parent)).plus_file(new_name))); } else { editor_data->get_undo_redo().add_do_method(editor, "set_edited_scene", child); editor_data->get_undo_redo().add_do_method(scene_tree, "update_tree"); editor_data->get_undo_redo().add_do_reference(child); editor_data->get_undo_redo().add_undo_method(editor, "set_edited_scene", (Object *)NULL); } editor_data->get_undo_redo().commit_action(); editor->push_item(c); editor_selection->clear(); editor_selection->add_node(child); if (Object::cast_to<Control>(c)) { //make editor more comfortable, so some controls don't appear super shrunk Control *ct = Object::cast_to<Control>(c); Size2 ms = ct->get_minimum_size(); if (ms.width < 4) ms.width = 40; if (ms.height < 4) ms.height = 40; ct->set_size(ms); } } else if (current_option == TOOL_REPLACE) { List<Node *> selection = editor_selection->get_selected_node_list(); ERR_FAIL_COND(selection.size() <= 0); for (List<Node *>::Element *E = selection.front(); E; E = E->next()) { Node *n = E->get(); ERR_FAIL_COND(!n); Object *c = create_dialog->instance_selected(); ERR_FAIL_COND(!c); Node *newnode = Object::cast_to<Node>(c); ERR_FAIL_COND(!newnode); replace_node(n, newnode); } } } void SceneTreeDock::replace_node(Node *p_node, Node *p_by_node) { Node *n = p_node; Node *newnode = p_by_node; Node *default_oldnode = Object::cast_to<Node>(ClassDB::instance(n->get_class())); List<PropertyInfo> pinfo; n->get_property_list(&pinfo); for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) continue; if (E->get().name == "__meta__") continue; if (default_oldnode->get(E->get().name) != n->get(E->get().name)) { newnode->set(E->get().name, n->get(E->get().name)); } } memdelete(default_oldnode); editor->push_item(NULL); //reconnect signals List<MethodInfo> sl; n->get_signal_list(&sl); for (List<MethodInfo>::Element *E = sl.front(); E; E = E->next()) { List<Object::Connection> cl; n->get_signal_connection_list(E->get().name, &cl); for (List<Object::Connection>::Element *F = cl.front(); F; F = F->next()) { Object::Connection &c = F->get(); if (!(c.flags & Object::CONNECT_PERSIST)) continue; newnode->connect(c.signal, c.target, c.method, varray(), Object::CONNECT_PERSIST); } } String newname = n->get_name(); List<Node *> to_erase; for (int i = 0; i < n->get_child_count(); i++) { if (n->get_child(i)->get_owner() == NULL && n->is_owned_by_parent()) { to_erase.push_back(n->get_child(i)); } } n->replace_by(newnode, true); if (n == edited_scene) { edited_scene = newnode; editor->set_edited_scene(newnode); newnode->set_editable_instances(n->get_editable_instances()); } //small hack to make collisionshapes and other kind of nodes to work for (int i = 0; i < newnode->get_child_count(); i++) { Node *c = newnode->get_child(i); c->call("set_transform", c->call("get_transform")); } editor_data->get_undo_redo().clear_history(); newnode->set_name(newname); editor->push_item(newnode); memdelete(n); while (to_erase.front()) { memdelete(to_erase.front()->get()); to_erase.pop_front(); } } void SceneTreeDock::set_edited_scene(Node *p_scene) { edited_scene = p_scene; } void SceneTreeDock::set_selected(Node *p_node, bool p_emit_selected) { scene_tree->set_selected(p_node, p_emit_selected); } void SceneTreeDock::import_subscene() { import_subscene_dialog->popup_centered_ratio(); } void SceneTreeDock::_import_subscene() { Node *parent = scene_tree->get_selected(); if (!parent) { parent = editor_data->get_edited_scene_root(); ERR_FAIL_COND(!parent); } import_subscene_dialog->move(parent, edited_scene); editor_data->get_undo_redo().clear_history(); //no undo for now.. } void SceneTreeDock::_new_scene_from(String p_file) { List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() != 1) { accept->set_text(TTR("This operation requires a single selected node.")); accept->popup_centered_minsize(); return; } if (EditorNode::get_singleton()->is_scene_open(p_file)) { accept->set_text(TTR("Can't overwrite scene that is still open!")); accept->popup_centered_minsize(); return; } Node *base = selection.front()->get(); Map<Node *, Node *> reown; reown[editor_data->get_edited_scene_root()] = base; Node *copy = base->duplicate_and_reown(reown); if (copy) { Ref<PackedScene> sdata = memnew(PackedScene); Error err = sdata->pack(copy); memdelete(copy); if (err != OK) { accept->set_text(TTR("Couldn't save new scene. Likely dependencies (instances) couldn't be satisfied.")); accept->popup_centered_minsize(); return; } int flg = 0; if (EditorSettings::get_singleton()->get("filesystem/on_save/compress_binary_resources")) flg |= ResourceSaver::FLAG_COMPRESS; err = ResourceSaver::save(p_file, sdata, flg); if (err != OK) { accept->set_text(TTR("Error saving scene.")); accept->popup_centered_minsize(); return; } _replace_with_branch_scene(p_file, base); } else { accept->set_text(TTR("Error duplicating scene to save it.")); accept->popup_centered_minsize(); return; } } static bool _is_node_visible(Node *p_node) { if (!p_node->get_owner()) return false; if (p_node->get_owner() != EditorNode::get_singleton()->get_edited_scene() && !EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(p_node->get_owner())) return false; return true; } static bool _has_visible_children(Node *p_node) { bool collapsed = p_node->is_displayed_folded(); if (collapsed) return false; for (int i = 0; i < p_node->get_child_count(); i++) { Node *child = p_node->get_child(i); if (!_is_node_visible(child)) continue; return true; } return false; } static Node *_find_last_visible(Node *p_node) { Node *last = NULL; bool collapsed = p_node->is_displayed_folded(); if (!collapsed) { for (int i = 0; i < p_node->get_child_count(); i++) { if (_is_node_visible(p_node->get_child(i))) { last = p_node->get_child(i); } } } if (last) { Node *lastc = _find_last_visible(last); if (lastc) last = lastc; } else { last = p_node; } return last; } void SceneTreeDock::_normalize_drop(Node *&to_node, int &to_pos, int p_type) { to_pos = -1; if (p_type == -1) { //drop at above selected node if (to_node == EditorNode::get_singleton()->get_edited_scene()) { to_node = NULL; ERR_EXPLAIN("Cannot perform drop above the root node!"); ERR_FAIL(); } to_pos = to_node->get_index(); to_node = to_node->get_parent(); } else if (p_type == 1) { //drop at below selected node if (to_node == EditorNode::get_singleton()->get_edited_scene()) { //if at lower sibling of root node to_pos = 0; //just insert at beginning of root node return; } Node *lower_sibling = NULL; if (_has_visible_children(to_node)) { to_pos = 0; } else { for (int i = to_node->get_index() + 1; i < to_node->get_parent()->get_child_count(); i++) { Node *c = to_node->get_parent()->get_child(i); if (_is_node_visible(c)) { lower_sibling = c; break; } } if (lower_sibling) { to_pos = lower_sibling->get_index(); } to_node = to_node->get_parent(); } } } void SceneTreeDock::_files_dropped(Vector<String> p_files, NodePath p_to, int p_type) { Node *node = get_node(p_to); ERR_FAIL_COND(!node); int to_pos = -1; _normalize_drop(node, to_pos, p_type); _perform_instance_scenes(p_files, node, to_pos); } void SceneTreeDock::_script_dropped(String p_file, NodePath p_to) { Ref<Script> scr = ResourceLoader::load(p_file); ERR_FAIL_COND(!scr.is_valid()); Node *n = get_node(p_to); if (n) { editor_data->get_undo_redo().create_action(TTR("Attach Script")); editor_data->get_undo_redo().add_do_method(n, "set_script", scr); editor_data->get_undo_redo().add_undo_method(n, "set_script", n->get_script()); editor_data->get_undo_redo().add_do_method(this, "_update_script_button"); editor_data->get_undo_redo().add_undo_method(this, "_update_script_button"); editor_data->get_undo_redo().commit_action(); } } void SceneTreeDock::_nodes_dragged(Array p_nodes, NodePath p_to, int p_type) { Vector<Node *> nodes; Node *to_node; for (int i = 0; i < p_nodes.size(); i++) { Node *n = get_node((p_nodes[i])); if (n) { nodes.push_back(n); } } if (nodes.size() == 0) return; to_node = get_node(p_to); if (!to_node) return; int to_pos = -1; _normalize_drop(to_node, to_pos, p_type); _do_reparent(to_node, to_pos, nodes, true); } void SceneTreeDock::_add_children_to_popup(Object *p_obj, int p_depth) { if (p_depth > 8) return; List<PropertyInfo> pinfo; p_obj->get_property_list(&pinfo); for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_EDITOR)) continue; if (E->get().hint != PROPERTY_HINT_RESOURCE_TYPE) continue; Variant value = p_obj->get(E->get().name); if (value.get_type() != Variant::OBJECT) continue; Object *obj = value; if (!obj) continue; Ref<Texture> icon = EditorNode::get_singleton()->get_object_icon(obj); if (menu->get_item_count() == 0) { menu->add_submenu_item(TTR("Sub-Resources"), "Sub-Resources"); } int index = menu_subresources->get_item_count(); menu_subresources->add_icon_item(icon, E->get().name.capitalize(), EDIT_SUBRESOURCE_BASE + subresources.size()); menu_subresources->set_item_h_offset(index, p_depth * 10 * EDSCALE); subresources.push_back(obj->get_instance_id()); _add_children_to_popup(obj, p_depth + 1); } } void SceneTreeDock::_tree_rmb(const Vector2 &p_menu_pos) { if (!EditorNode::get_singleton()->get_edited_scene()) { menu->clear(); menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW); menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE); menu->set_size(Size2(1, 1)); menu->set_position(p_menu_pos); menu->popup(); return; } List<Node *> selection = editor_selection->get_selected_node_list(); if (selection.size() == 0) return; menu->clear(); if (selection.size() == 1) { Node *selected = selection[0]; subresources.clear(); menu_subresources->clear(); menu_subresources->set_size(Size2(1, 1)); _add_children_to_popup(selection.front()->get(), 0); if (menu->get_item_count() > 0) menu->add_separator(); menu->add_icon_shortcut(get_icon("Add", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/add_child_node"), TOOL_NEW); menu->add_icon_shortcut(get_icon("Instance", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/instance_scene"), TOOL_INSTANCE); menu->add_separator(); menu->add_icon_shortcut(get_icon("ScriptCreate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/attach_script"), TOOL_ATTACH_SCRIPT); Ref<Script> existing = selected->get_script(); if (existing.is_valid()) { menu->add_icon_shortcut(get_icon("ScriptRemove", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/clear_script"), TOOL_CLEAR_SCRIPT); } menu->add_separator(); menu->add_icon_shortcut(get_icon("Rename", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/rename"), TOOL_RENAME); } menu->add_icon_shortcut(get_icon("Reload", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/change_node_type"), TOOL_REPLACE); if (scene_tree->get_selected() != edited_scene) { menu->add_separator(); menu->add_icon_shortcut(get_icon("MoveUp", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_up"), TOOL_MOVE_UP); menu->add_icon_shortcut(get_icon("MoveDown", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/move_down"), TOOL_MOVE_DOWN); menu->add_icon_shortcut(get_icon("Duplicate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/duplicate"), TOOL_DUPLICATE); menu->add_icon_shortcut(get_icon("Reparent", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/reparent"), TOOL_REPARENT); } if (selection.size() == 1) { menu->add_icon_shortcut(get_icon("NewRoot", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/make_root"), TOOL_MAKE_ROOT); menu->add_separator(); menu->add_icon_shortcut(get_icon("Blend", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/merge_from_scene"), TOOL_MERGE_FROM_SCENE); menu->add_icon_shortcut(get_icon("CreateNewSceneFrom", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/save_branch_as_scene"), TOOL_NEW_SCENE_FROM); menu->add_separator(); menu->add_icon_shortcut(get_icon("CopyNodePath", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/copy_node_path"), TOOL_COPY_NODE_PATH); bool is_external = (selection[0]->get_filename() != ""); if (is_external) { bool is_inherited = selection[0]->get_scene_inherited_state() != NULL; bool is_top_level = selection[0]->get_owner() == NULL; if (is_inherited && is_top_level) { menu->add_separator(); menu->add_item(TTR("Clear Inheritance"), TOOL_SCENE_CLEAR_INHERITANCE); menu->add_icon_item(get_icon("Load", "EditorIcons"), TTR("Open in Editor"), TOOL_SCENE_OPEN_INHERITED); } else if (!is_top_level) { menu->add_separator(); bool editable = EditorNode::get_singleton()->get_edited_scene()->is_editable_instance(selection[0]); bool placeholder = selection[0]->get_scene_instance_load_placeholder(); menu->add_check_item(TTR("Editable Children"), TOOL_SCENE_EDITABLE_CHILDREN); menu->add_check_item(TTR("Load As Placeholder"), TOOL_SCENE_USE_PLACEHOLDER); menu->add_item(TTR("Make Local"), TOOL_SCENE_MAKE_LOCAL); menu->add_icon_item(get_icon("Load", "EditorIcons"), TTR("Open in Editor"), TOOL_SCENE_OPEN); menu->set_item_checked(menu->get_item_idx_from_text(TTR("Editable Children")), editable); menu->set_item_checked(menu->get_item_idx_from_text(TTR("Load As Placeholder")), placeholder); } } } else { menu->add_separator(); menu->add_icon_shortcut(get_icon("ScriptCreate", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/attach_script"), TOOL_ATTACH_SCRIPT); menu->add_icon_shortcut(get_icon("ScriptRemove", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/clear_script"), TOOL_CLEAR_SCRIPT); } if (selection.size() > 1) { //this is not a commonly used action, it makes no sense for it to be where it was nor always present. menu->add_separator(); menu->add_icon_shortcut(get_icon("Rename", "EditorIcons"), ED_GET_SHORTCUT("scene_tree/batch_rename"), TOOL_BATCH_RENAME); } menu->add_separator(); menu->add_icon_shortcut(get_icon("Remove", "EditorIcons"), ED_SHORTCUT("scene_tree/delete", TTR("Delete Node(s)"), KEY_DELETE), TOOL_ERASE); menu->set_size(Size2(1, 1)); menu->set_position(p_menu_pos); menu->popup(); } void SceneTreeDock::_filter_changed(const String &p_filter) { scene_tree->set_filter(p_filter); } String SceneTreeDock::get_filter() { return filter->get_text(); } void SceneTreeDock::set_filter(const String &p_filter) { filter->set_text(p_filter); scene_tree->set_filter(p_filter); } void SceneTreeDock::_focus_node() { Node *node = scene_tree->get_selected(); ERR_FAIL_COND(!node); if (node->is_class("CanvasItem")) { CanvasItemEditorPlugin *editor = Object::cast_to<CanvasItemEditorPlugin>(editor_data->get_editor("2D")); editor->get_canvas_item_editor()->focus_selection(); } else { SpatialEditorPlugin *editor = Object::cast_to<SpatialEditorPlugin>(editor_data->get_editor("3D")); editor->get_spatial_editor()->get_editor_viewport(0)->focus_selection(); } } void SceneTreeDock::open_script_dialog(Node *p_for_node) { scene_tree->set_selected(p_for_node, false); _tool_selected(TOOL_ATTACH_SCRIPT); } void SceneTreeDock::add_remote_tree_editor(Control *p_remote) { ERR_FAIL_COND(remote_tree != NULL); add_child(p_remote); remote_tree = p_remote; remote_tree->hide(); } void SceneTreeDock::show_remote_tree() { _remote_tree_selected(); } void SceneTreeDock::hide_remote_tree() { _local_tree_selected(); } void SceneTreeDock::show_tab_buttons() { button_hb->show(); } void SceneTreeDock::hide_tab_buttons() { button_hb->hide(); } void SceneTreeDock::_remote_tree_selected() { scene_tree->hide(); if (remote_tree) remote_tree->show(); edit_remote->set_pressed(true); edit_local->set_pressed(false); emit_signal("remote_tree_selected"); } void SceneTreeDock::_local_tree_selected() { scene_tree->show(); if (remote_tree) remote_tree->hide(); edit_remote->set_pressed(false); edit_local->set_pressed(true); } void SceneTreeDock::_update_create_root_dialog() { BaseButton *toggle = Object::cast_to<BaseButton>(create_root_dialog->get_node(String("NodeShortcutsTopRow/NodeShortcutsToggle"))); Node *node_shortcuts = create_root_dialog->get_node(String("NodeShortcuts")); if (!toggle || !node_shortcuts) return; Control *beginner_nodes = Object::cast_to<Control>(node_shortcuts->get_node(String("BeginnerNodeShortcuts"))); Control *favorite_nodes = Object::cast_to<Control>(node_shortcuts->get_node(String("FavoriteNodeShortcuts"))); if (!beginner_nodes || !favorite_nodes) return; EditorSettings::get_singleton()->set_setting("_use_favorites_root_selection", toggle->is_pressed()); EditorSettings::get_singleton()->save(); if (toggle->is_pressed()) { for (int i = 0; i < favorite_nodes->get_child_count(); i++) { favorite_nodes->get_child(i)->queue_delete(); } FileAccess *f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_dir().plus_file("favorites.Node"), FileAccess::READ); if (f) { while (!f->eof_reached()) { String l = f->get_line().strip_edges(); if (l != String()) { Button *button = memnew(Button); favorite_nodes->add_child(button); button->set_text(TTR(l)); String name = l.get_slicec(' ', 0); if (ScriptServer::is_global_class(name)) name = ScriptServer::get_global_class_base(name); button->set_icon(EditorNode::get_singleton()->get_class_icon(name)); button->connect("pressed", this, "_favorite_root_selected", make_binds(l)); } } memdelete(f); } if (!favorite_nodes->is_visible_in_tree()) { favorite_nodes->show(); beginner_nodes->hide(); } } else { if (!beginner_nodes->is_visible_in_tree()) { beginner_nodes->show(); favorite_nodes->hide(); } } } void SceneTreeDock::_favorite_root_selected(const String &p_class) { selected_favorite_root = p_class; _tool_selected(TOOL_CREATE_FAVORITE, false); } void SceneTreeDock::_bind_methods() { ClassDB::bind_method(D_METHOD("_tool_selected"), &SceneTreeDock::_tool_selected, DEFVAL(false)); ClassDB::bind_method(D_METHOD("_create"), &SceneTreeDock::_create); ClassDB::bind_method(D_METHOD("_node_reparent"), &SceneTreeDock::_node_reparent); ClassDB::bind_method(D_METHOD("_set_owners"), &SceneTreeDock::_set_owners); ClassDB::bind_method(D_METHOD("_node_selected"), &SceneTreeDock::_node_selected); ClassDB::bind_method(D_METHOD("_node_renamed"), &SceneTreeDock::_node_renamed); ClassDB::bind_method(D_METHOD("_script_created"), &SceneTreeDock::_script_created); ClassDB::bind_method(D_METHOD("_load_request"), &SceneTreeDock::_load_request); ClassDB::bind_method(D_METHOD("_script_open_request"), &SceneTreeDock::_script_open_request); ClassDB::bind_method(D_METHOD("_unhandled_key_input"), &SceneTreeDock::_unhandled_key_input); ClassDB::bind_method(D_METHOD("_input"), &SceneTreeDock::_input); ClassDB::bind_method(D_METHOD("_nodes_drag_begin"), &SceneTreeDock::_nodes_drag_begin); ClassDB::bind_method(D_METHOD("_delete_confirm"), &SceneTreeDock::_delete_confirm); ClassDB::bind_method(D_METHOD("_node_prerenamed"), &SceneTreeDock::_node_prerenamed); ClassDB::bind_method(D_METHOD("_import_subscene"), &SceneTreeDock::_import_subscene); ClassDB::bind_method(D_METHOD("_selection_changed"), &SceneTreeDock::_selection_changed); ClassDB::bind_method(D_METHOD("_new_scene_from"), &SceneTreeDock::_new_scene_from); ClassDB::bind_method(D_METHOD("_nodes_dragged"), &SceneTreeDock::_nodes_dragged); ClassDB::bind_method(D_METHOD("_files_dropped"), &SceneTreeDock::_files_dropped); ClassDB::bind_method(D_METHOD("_script_dropped"), &SceneTreeDock::_script_dropped); ClassDB::bind_method(D_METHOD("_tree_rmb"), &SceneTreeDock::_tree_rmb); ClassDB::bind_method(D_METHOD("_filter_changed"), &SceneTreeDock::_filter_changed); ClassDB::bind_method(D_METHOD("_focus_node"), &SceneTreeDock::_focus_node); ClassDB::bind_method(D_METHOD("_remote_tree_selected"), &SceneTreeDock::_remote_tree_selected); ClassDB::bind_method(D_METHOD("_local_tree_selected"), &SceneTreeDock::_local_tree_selected); ClassDB::bind_method(D_METHOD("_update_script_button"), &SceneTreeDock::_update_script_button); ClassDB::bind_method(D_METHOD("_favorite_root_selected"), &SceneTreeDock::_favorite_root_selected); ClassDB::bind_method(D_METHOD("_update_create_root_dialog"), &SceneTreeDock::_update_create_root_dialog); ClassDB::bind_method(D_METHOD("instance"), &SceneTreeDock::instance); ADD_SIGNAL(MethodInfo("remote_tree_selected")); } SceneTreeDock::SceneTreeDock(EditorNode *p_editor, Node *p_scene_root, EditorSelection *p_editor_selection, EditorData &p_editor_data) { set_name("Scene"); editor = p_editor; edited_scene = NULL; editor_data = &p_editor_data; editor_selection = p_editor_selection; scene_root = p_scene_root; VBoxContainer *vbc = this; HBoxContainer *filter_hbc = memnew(HBoxContainer); filter_hbc->add_constant_override("separate", 0); ToolButton *tb; ED_SHORTCUT("scene_tree/rename", TTR("Rename")); ED_SHORTCUT("scene_tree/batch_rename", TTR("Batch Rename"), KEY_MASK_CMD | KEY_F2); ED_SHORTCUT("scene_tree/add_child_node", TTR("Add Child Node"), KEY_MASK_CMD | KEY_A); ED_SHORTCUT("scene_tree/instance_scene", TTR("Instance Child Scene")); ED_SHORTCUT("scene_tree/change_node_type", TTR("Change Type")); ED_SHORTCUT("scene_tree/attach_script", TTR("Attach Script")); ED_SHORTCUT("scene_tree/clear_script", TTR("Clear Script")); ED_SHORTCUT("scene_tree/move_up", TTR("Move Up"), KEY_MASK_CMD | KEY_UP); ED_SHORTCUT("scene_tree/move_down", TTR("Move Down"), KEY_MASK_CMD | KEY_DOWN); ED_SHORTCUT("scene_tree/duplicate", TTR("Duplicate"), KEY_MASK_CMD | KEY_D); ED_SHORTCUT("scene_tree/reparent", TTR("Reparent")); ED_SHORTCUT("scene_tree/make_root", TTR("Make Scene Root")); ED_SHORTCUT("scene_tree/merge_from_scene", TTR("Merge From Scene")); ED_SHORTCUT("scene_tree/save_branch_as_scene", TTR("Save Branch as Scene")); ED_SHORTCUT("scene_tree/copy_node_path", TTR("Copy Node Path"), KEY_MASK_CMD | KEY_C); ED_SHORTCUT("scene_tree/delete_no_confirm", TTR("Delete (No Confirm)"), KEY_MASK_SHIFT | KEY_DELETE); ED_SHORTCUT("scene_tree/delete", TTR("Delete"), KEY_DELETE); tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_NEW, false)); tb->set_tooltip(TTR("Add/Create a New Node")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/add_child_node")); filter_hbc->add_child(tb); button_add = tb; tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_INSTANCE, false)); tb->set_tooltip(TTR("Instance a scene file as a Node. Creates an inherited scene if no root node exists.")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/instance_scene")); filter_hbc->add_child(tb); button_instance = tb; vbc->add_child(filter_hbc); filter = memnew(LineEdit); filter->set_h_size_flags(SIZE_EXPAND_FILL); filter->set_placeholder(TTR("Filter nodes")); filter_hbc->add_child(filter); filter->connect("text_changed", this, "_filter_changed"); tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_ATTACH_SCRIPT, false)); tb->set_tooltip(TTR("Attach a new or existing script for the selected node.")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/attach_script")); filter_hbc->add_child(tb); tb->hide(); button_create_script = tb; tb = memnew(ToolButton); tb->connect("pressed", this, "_tool_selected", make_binds(TOOL_CLEAR_SCRIPT, false)); tb->set_tooltip(TTR("Clear a script for the selected node.")); tb->set_shortcut(ED_GET_SHORTCUT("scene_tree/clear_script")); filter_hbc->add_child(tb); button_clear_script = tb; tb->hide(); button_hb = memnew(HBoxContainer); vbc->add_child(button_hb); edit_remote = memnew(ToolButton); button_hb->add_child(edit_remote); edit_remote->set_h_size_flags(SIZE_EXPAND_FILL); edit_remote->set_text(TTR("Remote")); edit_remote->set_toggle_mode(true); edit_remote->connect("pressed", this, "_remote_tree_selected"); edit_local = memnew(ToolButton); button_hb->add_child(edit_local); edit_local->set_h_size_flags(SIZE_EXPAND_FILL); edit_local->set_text(TTR("Local")); edit_local->set_toggle_mode(true); edit_local->connect("pressed", this, "_local_tree_selected"); remote_tree = NULL; button_hb->hide(); create_root_dialog = memnew(VBoxContainer); vbc->add_child(create_root_dialog); create_root_dialog->hide(); scene_tree = memnew(SceneTreeEditor(false, true, true)); vbc->add_child(scene_tree); scene_tree->set_v_size_flags(SIZE_EXPAND | SIZE_FILL); scene_tree->connect("rmb_pressed", this, "_tree_rmb"); scene_tree->connect("node_selected", this, "_node_selected", varray(), CONNECT_DEFERRED); scene_tree->connect("node_renamed", this, "_node_renamed", varray(), CONNECT_DEFERRED); scene_tree->connect("node_prerename", this, "_node_prerenamed"); scene_tree->connect("open", this, "_load_request"); scene_tree->connect("open_script", this, "_script_open_request"); scene_tree->connect("nodes_rearranged", this, "_nodes_dragged"); scene_tree->connect("files_dropped", this, "_files_dropped"); scene_tree->connect("script_dropped", this, "_script_dropped"); scene_tree->connect("nodes_dragged", this, "_nodes_drag_begin"); scene_tree->get_scene_tree()->connect("item_double_clicked", this, "_focus_node"); scene_tree->set_undo_redo(&editor_data->get_undo_redo()); scene_tree->set_editor_selection(editor_selection); create_dialog = memnew(CreateDialog); create_dialog->set_base_type("Node"); add_child(create_dialog); create_dialog->connect("create", this, "_create"); create_dialog->connect("favorites_updated", this, "_update_create_root_dialog"); rename_dialog = memnew(RenameDialog(scene_tree, &editor_data->get_undo_redo())); add_child(rename_dialog); script_create_dialog = memnew(ScriptCreateDialog); add_child(script_create_dialog); script_create_dialog->connect("script_created", this, "_script_created"); reparent_dialog = memnew(ReparentDialog); add_child(reparent_dialog); reparent_dialog->connect("reparent", this, "_node_reparent"); accept = memnew(AcceptDialog); add_child(accept); file = memnew(EditorFileDialog); add_child(file); file->connect("file_selected", this, "instance"); set_process_unhandled_key_input(true); delete_dialog = memnew(ConfirmationDialog); add_child(delete_dialog); delete_dialog->connect("confirmed", this, "_delete_confirm"); import_subscene_dialog = memnew(EditorSubScene); add_child(import_subscene_dialog); import_subscene_dialog->connect("subscene_selected", this, "_import_subscene"); new_scene_from_dialog = memnew(EditorFileDialog); new_scene_from_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); add_child(new_scene_from_dialog); new_scene_from_dialog->connect("file_selected", this, "_new_scene_from"); menu = memnew(PopupMenu); add_child(menu); menu->connect("id_pressed", this, "_tool_selected"); menu->set_hide_on_window_lose_focus(true); menu_subresources = memnew(PopupMenu); menu_subresources->set_name("Sub-Resources"); menu_subresources->connect("id_pressed", this, "_tool_selected"); menu->add_child(menu_subresources); first_enter = true; restore_script_editor_on_drag = false; clear_inherit_confirm = memnew(ConfirmationDialog); clear_inherit_confirm->set_text(TTR("Clear Inheritance? (No Undo!)")); clear_inherit_confirm->get_ok()->set_text(TTR("Clear")); add_child(clear_inherit_confirm); set_process_input(true); set_process(true); EDITOR_DEF("interface/editors/show_scene_tree_root_selection", true); EDITOR_DEF("_use_favorites_root_selection", false); }
/**************************************************************************** Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2011 Zynga Inc. Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "renderer/CCTextureAtlas.h" #include <stdlib.h> #include "base/ccMacros.h" #include "base/ccUTF8.h" #include "base/CCEventType.h" #include "base/CCDirector.h" #include "base/CCConfiguration.h" #include "base/CCEventDispatcher.h" #include "base/CCEventListenerCustom.h" #include "renderer/CCTextureCache.h" #include "renderer/CCGLProgram.h" #include "renderer/ccGLStateCache.h" #include "renderer/CCRenderer.h" #include "renderer/CCTexture2D.h" #include "platform/CCGL.h" //According to some tests GL_TRIANGLE_STRIP is slower, MUCH slower. Probably I'm doing something very wrong // implementation TextureAtlas NS_CC_BEGIN TextureAtlas::TextureAtlas() :_indices(nullptr) ,_dirty(false) ,_texture(nullptr) ,_quads(nullptr) #if CC_ENABLE_CACHE_TEXTURE_DATA ,_rendererRecreatedListener(nullptr) #endif {} TextureAtlas::~TextureAtlas() { CCLOGINFO("deallocing TextureAtlas: %p", this); CC_SAFE_FREE(_quads); CC_SAFE_FREE(_indices); glDeleteBuffers(2, _buffersVBO); if (Configuration::getInstance()->supportsShareableVAO()) { glDeleteVertexArrays(1, &_VAOname); GL::bindVAO(0); } CC_SAFE_RELEASE(_texture); #if CC_ENABLE_CACHE_TEXTURE_DATA Director::getInstance()->getEventDispatcher()->removeEventListener(_rendererRecreatedListener); #endif } ssize_t TextureAtlas::getTotalQuads() const { return _totalQuads; } ssize_t TextureAtlas::getCapacity() const { return _capacity; } Texture2D* TextureAtlas::getTexture() const { return _texture; } void TextureAtlas::setTexture(Texture2D * var) { CC_SAFE_RETAIN(var); CC_SAFE_RELEASE(_texture); _texture = var; } V3F_C4B_T2F_Quad* TextureAtlas::getQuads() { //if someone accesses the quads directly, presume that changes will be made _dirty = true; return _quads; } void TextureAtlas::setQuads(V3F_C4B_T2F_Quad* quads) { _quads = quads; } // TextureAtlas - alloc & init TextureAtlas * TextureAtlas::create(const std::string& file, ssize_t capacity) { TextureAtlas * textureAtlas = new (std::nothrow) TextureAtlas(); if(textureAtlas && textureAtlas->initWithFile(file, capacity)) { textureAtlas->autorelease(); return textureAtlas; } CC_SAFE_DELETE(textureAtlas); return nullptr; } TextureAtlas * TextureAtlas::createWithTexture(Texture2D *texture, ssize_t capacity) { TextureAtlas * textureAtlas = new (std::nothrow) TextureAtlas(); if (textureAtlas && textureAtlas->initWithTexture(texture, capacity)) { textureAtlas->autorelease(); return textureAtlas; } CC_SAFE_DELETE(textureAtlas); return nullptr; } bool TextureAtlas::initWithFile(const std::string& file, ssize_t capacity) { // retained in property Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(file); if (texture) { return initWithTexture(texture, capacity); } else { CCLOG("cocos2d: Could not open file: %s", file.c_str()); return false; } } bool TextureAtlas::initWithTexture(Texture2D *texture, ssize_t capacity) { CCASSERT(capacity>=0, "Capacity must be >= 0"); // CCASSERT(texture != nullptr, "texture should not be null"); _capacity = capacity; _totalQuads = 0; // retained in property this->_texture = texture; CC_SAFE_RETAIN(_texture); // Re-initialization is not allowed CCASSERT(_quads == nullptr && _indices == nullptr, "_quads and _indices should be nullptr."); _quads = (V3F_C4B_T2F_Quad*)malloc( _capacity * sizeof(V3F_C4B_T2F_Quad) ); _indices = (GLushort *)malloc( _capacity * 6 * sizeof(GLushort) ); if( ! ( _quads && _indices) && _capacity > 0) { //CCLOG("cocos2d: TextureAtlas: not enough memory"); CC_SAFE_FREE(_quads); CC_SAFE_FREE(_indices); // release texture, should set it to null, because the destruction will // release it too. see cocos2d-x issue #484 CC_SAFE_RELEASE_NULL(_texture); return false; } memset( _quads, 0, _capacity * sizeof(V3F_C4B_T2F_Quad) ); memset( _indices, 0, _capacity * 6 * sizeof(GLushort) ); #if CC_ENABLE_CACHE_TEXTURE_DATA /** listen the event that renderer was recreated on Android/WP8 */ _rendererRecreatedListener = EventListenerCustom::create(EVENT_RENDERER_RECREATED, CC_CALLBACK_1(TextureAtlas::listenRendererRecreated, this)); Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_rendererRecreatedListener, -1); #endif this->setupIndices(); if (Configuration::getInstance()->supportsShareableVAO()) { setupVBOandVAO(); } else { setupVBO(); } _dirty = true; return true; } void TextureAtlas::listenRendererRecreated(EventCustom* /*event*/) { if (Configuration::getInstance()->supportsShareableVAO()) { setupVBOandVAO(); } else { setupVBO(); } // set _dirty to true to force it rebinding buffer _dirty = true; } std::string TextureAtlas::getDescription() const { return StringUtils::format("<TextureAtlas | totalQuads = %d>", static_cast<int>(_totalQuads)); } void TextureAtlas::setupIndices() { if (_capacity == 0) return; for( int i=0; i < _capacity; i++) { _indices[i*6+0] = i*4+0; _indices[i*6+1] = i*4+1; _indices[i*6+2] = i*4+2; // inverted index. issue #179 _indices[i*6+3] = i*4+3; _indices[i*6+4] = i*4+2; _indices[i*6+5] = i*4+1; } } //TextureAtlas - VAO / VBO specific void TextureAtlas::setupVBOandVAO() { glGenVertexArrays(1, &_VAOname); GL::bindVAO(_VAOname); #define kQuadSize sizeof(_quads[0].bl) glGenBuffers(2, &_buffersVBO[0]); glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _capacity, _quads, GL_DYNAMIC_DRAW); // vertices glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, vertices)); // colors glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, colors)); // tex coords glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_TEX_COORD); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, texCoords)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(_indices[0]) * _capacity * 6, _indices, GL_STATIC_DRAW); // Must unbind the VAO before changing the element buffer. GL::bindVAO(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); CHECK_GL_ERROR_DEBUG(); } void TextureAtlas::setupVBO() { glGenBuffers(2, &_buffersVBO[0]); mapBuffers(); } void TextureAtlas::mapBuffers() { // Avoid changing the element buffer for whatever VAO might be bound. GL::bindVAO(0); glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _capacity, _quads, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(_indices[0]) * _capacity * 6, _indices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); CHECK_GL_ERROR_DEBUG(); } // TextureAtlas - Update, Insert, Move & Remove void TextureAtlas::updateQuad(V3F_C4B_T2F_Quad *quad, ssize_t index) { CCASSERT( index >= 0 && index < _capacity, "updateQuadWithTexture: Invalid index"); _totalQuads = MAX( index+1, _totalQuads); _quads[index] = *quad; _dirty = true; } void TextureAtlas::insertQuad(V3F_C4B_T2F_Quad *quad, ssize_t index) { CCASSERT( index>=0 && index<_capacity, "insertQuadWithTexture: Invalid index"); _totalQuads++; CCASSERT( _totalQuads <= _capacity, "invalid totalQuads"); // issue #575. index can be > totalQuads auto remaining = (_totalQuads-1) - index; // last object doesn't need to be moved if( remaining > 0) { // texture coordinates memmove( &_quads[index+1],&_quads[index], sizeof(_quads[0]) * remaining ); } _quads[index] = *quad; _dirty = true; } void TextureAtlas::insertQuads(V3F_C4B_T2F_Quad* quads, ssize_t index, ssize_t amount) { CCASSERT(index>=0 && amount>=0 && index+amount<=_capacity, "insertQuadWithTexture: Invalid index + amount"); _totalQuads += amount; CCASSERT( _totalQuads <= _capacity, "invalid totalQuads"); // issue #575. index can be > totalQuads auto remaining = (_totalQuads-1) - index - amount; // last object doesn't need to be moved if( remaining > 0) { // tex coordinates memmove( &_quads[index+amount],&_quads[index], sizeof(_quads[0]) * remaining ); } auto max = index + amount; int j = 0; for (ssize_t i = index; i < max ; i++) { _quads[index] = quads[j]; index++; j++; } _dirty = true; } void TextureAtlas::insertQuadFromIndex(ssize_t oldIndex, ssize_t newIndex) { CCASSERT( newIndex >= 0 && newIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); CCASSERT( oldIndex >= 0 && oldIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); if( oldIndex == newIndex ) { return; } // because it is ambiguous in iphone, so we implement abs ourselves // unsigned int howMany = std::abs( oldIndex - newIndex); auto howMany = (oldIndex - newIndex) > 0 ? (oldIndex - newIndex) : (newIndex - oldIndex); auto dst = oldIndex; auto src = oldIndex + 1; if( oldIndex > newIndex) { dst = newIndex+1; src = newIndex; } // texture coordinates V3F_C4B_T2F_Quad quadsBackup = _quads[oldIndex]; memmove( &_quads[dst],&_quads[src], sizeof(_quads[0]) * howMany ); _quads[newIndex] = quadsBackup; _dirty = true; } void TextureAtlas::removeQuadAtIndex(ssize_t index) { CCASSERT( index>=0 && index<_totalQuads, "removeQuadAtIndex: Invalid index"); auto remaining = (_totalQuads-1) - index; // last object doesn't need to be moved if( remaining ) { // texture coordinates memmove( &_quads[index],&_quads[index+1], sizeof(_quads[0]) * remaining ); } _totalQuads--; _dirty = true; } void TextureAtlas::removeQuadsAtIndex(ssize_t index, ssize_t amount) { CCASSERT(index>=0 && amount>=0 && index+amount<=_totalQuads, "removeQuadAtIndex: index + amount out of bounds"); auto remaining = (_totalQuads) - (index + amount); _totalQuads -= amount; if ( remaining ) { memmove( &_quads[index], &_quads[index+amount], sizeof(_quads[0]) * remaining ); } _dirty = true; } void TextureAtlas::removeAllQuads() { _totalQuads = 0; } // TextureAtlas - Resize bool TextureAtlas::resizeCapacity(ssize_t newCapacity) { CCASSERT(newCapacity >= 0, "capacity >= 0"); if (newCapacity == _capacity) { return true; } auto oldCapacity = _capacity; // update capacity and totalQuads _totalQuads = MIN(_totalQuads, newCapacity); _capacity = newCapacity; V3F_C4B_T2F_Quad* tmpQuads = nullptr; GLushort* tmpIndices = nullptr; // when calling initWithTexture(fileName, 0) on bada device, calloc(0, 1) will fail and return nullptr, // so here must judge whether _quads and _indices is nullptr. ssize_t _quads_size = sizeof(_quads[0]); ssize_t new_quads_size = _capacity * _quads_size; if (_quads == nullptr) { tmpQuads = (V3F_C4B_T2F_Quad*)malloc(new_quads_size); if (tmpQuads != nullptr) { memset(tmpQuads, 0, new_quads_size); } } else { tmpQuads = (V3F_C4B_T2F_Quad*)realloc(_quads, new_quads_size); if (tmpQuads != nullptr && _capacity > oldCapacity) { memset(tmpQuads + oldCapacity, 0, (_capacity - oldCapacity)*_quads_size); } _quads = nullptr; } ssize_t _indices_size = sizeof(_indices[0]); ssize_t new_size = _capacity * 6 * _indices_size; if (_indices == nullptr) { tmpIndices = (GLushort*)malloc(new_size); if (tmpIndices != nullptr) { memset(tmpIndices, 0, new_size); } } else { tmpIndices = (GLushort*)realloc(_indices, new_size); if (tmpIndices != nullptr && _capacity > oldCapacity) { memset(tmpIndices + oldCapacity, 0, (_capacity - oldCapacity) * 6 * _indices_size); } _indices = nullptr; } if (!(tmpQuads && tmpIndices)) { CCLOG("cocos2d: TextureAtlas: not enough memory"); CC_SAFE_FREE(tmpQuads); CC_SAFE_FREE(tmpIndices); CC_SAFE_FREE(_quads); CC_SAFE_FREE(_indices); _capacity = _totalQuads = 0; return false; } _quads = tmpQuads; _indices = tmpIndices; setupIndices(); mapBuffers(); _dirty = true; return true; } void TextureAtlas::increaseTotalQuadsWith(ssize_t amount) { CCASSERT(amount>=0, "amount >= 0"); _totalQuads += amount; } void TextureAtlas::moveQuadsFromIndex(ssize_t oldIndex, ssize_t amount, ssize_t newIndex) { CCASSERT(oldIndex>=0 && amount>=0 && newIndex>=0, "values must be >= 0"); CCASSERT(newIndex + amount <= _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); CCASSERT(oldIndex < _totalQuads, "insertQuadFromIndex:atIndex: Invalid index"); if( oldIndex == newIndex ) { return; } //create buffer size_t quadSize = sizeof(V3F_C4B_T2F_Quad); V3F_C4B_T2F_Quad* tempQuads = (V3F_C4B_T2F_Quad*)malloc( quadSize * amount); memcpy( tempQuads, &_quads[oldIndex], quadSize * amount ); if (newIndex < oldIndex) { // move quads from newIndex to newIndex + amount to make room for buffer memmove( &_quads[newIndex], &_quads[newIndex+amount], (oldIndex-newIndex)*quadSize); } else { // move quads above back memmove( &_quads[oldIndex], &_quads[oldIndex+amount], (newIndex-oldIndex)*quadSize); } memcpy( &_quads[newIndex], tempQuads, amount*quadSize); free(tempQuads); _dirty = true; } void TextureAtlas::moveQuadsFromIndex(ssize_t index, ssize_t newIndex) { CCASSERT(index>=0 && newIndex>=0, "values must be >= 0"); CCASSERT(newIndex + (_totalQuads - index) <= _capacity, "moveQuadsFromIndex move is out of bounds"); memmove(_quads + newIndex,_quads + index, (_totalQuads - index) * sizeof(_quads[0])); } void TextureAtlas::fillWithEmptyQuadsFromIndex(ssize_t index, ssize_t amount) { CCASSERT(index>=0 && amount>=0, "values must be >= 0"); V3F_C4B_T2F_Quad quad; memset(&quad, 0, sizeof(quad)); auto to = index + amount; for (ssize_t i = index ; i < to ; i++) { _quads[i] = quad; } } // TextureAtlas - Drawing void TextureAtlas::drawQuads() { this->drawNumberOfQuads(_totalQuads, 0); } void TextureAtlas::drawNumberOfQuads(ssize_t numberOfQuads) { CCASSERT(numberOfQuads>=0, "numberOfQuads must be >= 0"); this->drawNumberOfQuads(numberOfQuads, 0); } void TextureAtlas::drawNumberOfQuads(ssize_t numberOfQuads, ssize_t start) { CCASSERT(numberOfQuads>=0 && start>=0, "numberOfQuads and start must be >= 0"); if(!numberOfQuads) return; GL::bindTexture2D(_texture); auto conf = Configuration::getInstance(); if (conf->supportsShareableVAO() && conf->supportsMapBuffer()) { // // Using VBO and VAO // // FIXME:: update is done in draw... perhaps it should be done in a timer if (_dirty) { glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); // option 1: subdata // glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] ); // option 2: data // glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW); // option 3: orphaning + glMapBuffer glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _capacity, nullptr, GL_DYNAMIC_DRAW); void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); memcpy(buf, _quads, sizeof(_quads[0])* _totalQuads); glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); _dirty = false; } GL::bindVAO(_VAOname); #if CC_REBIND_INDICES_BUFFER glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]); #endif glDrawElements(GL_TRIANGLES, (GLsizei) numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0])) ); GL::bindVAO(0); #if CC_REBIND_INDICES_BUFFER glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); #endif // glBindVertexArray(0); } else { // // Using VBO without VAO // #define kQuadSize sizeof(_quads[0].bl) glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); // FIXME:: update is done in draw... perhaps it should be done in a timer if (_dirty) { // glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(_quads[0]) * _totalQuads , &_quads[0] ); glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _capacity, &_quads[0], GL_DYNAMIC_DRAW); _dirty = false; } GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX); // vertices glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, vertices)); // colors glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, colors)); // tex coords glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof(V3F_C4B_T2F, texCoords)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]); glDrawElements(GL_TRIANGLES, (GLsizei)numberOfQuads*6, GL_UNSIGNED_SHORT, (GLvoid*) (start*6*sizeof(_indices[0]))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,numberOfQuads*6); CHECK_GL_ERROR_DEBUG(); } NS_CC_END
/*************************************************************************/ /* Xania (M)ulti(U)ser(D)ungeon server source code */ /* (C) 2021 Xania Development Team */ /* See merc.h and README for original copyrights */ /*************************************************************************/ #include "Materials.hpp" #include <catch2/catch.hpp> #include <tuple> TEST_CASE("liquid try lookup") { SECTION("valid cases match by full name") { using std::make_tuple; Liquid::Type expected; std::string_view name; std::tie(expected, name) = GENERATE(table<Liquid::Type, std::string_view>({ make_tuple(Liquid::Type::Water, "water"), make_tuple(Liquid::Type::Beer, "beer"), make_tuple(Liquid::Type::Wine, "wine"), make_tuple(Liquid::Type::Ale, "ale"), make_tuple(Liquid::Type::DarkAle, "dark ale"), make_tuple(Liquid::Type::Whisky, "whisky"), make_tuple(Liquid::Type::Lemonade, "lemonade"), make_tuple(Liquid::Type::Firebreather, "firebreather"), make_tuple(Liquid::Type::LocalSpecialty, "local specialty"), make_tuple(Liquid::Type::SlimeMoldJuice, "slime mold juice"), make_tuple(Liquid::Type::Milk, "milk"), make_tuple(Liquid::Type::Tea, "tea"), make_tuple(Liquid::Type::Coffee, "coffee"), make_tuple(Liquid::Type::Blood, "blood"), make_tuple(Liquid::Type::SaltWater, "salt water"), make_tuple(Liquid::Type::Cola, "cola"), make_tuple(Liquid::Type::RedWine, "red wine"), })); SECTION("ok") { const auto *result = Liquid::try_lookup(name); CHECK(result == &Liquids[magic_enum::enum_integer<Liquid::Type>(expected)]); } } SECTION("partial is_name matching") { const auto *result = Liquid::try_lookup("s m j"); CHECK(result == &Liquids[magic_enum::enum_integer<Liquid::Type>(Liquid::Type::SlimeMoldJuice)]); } SECTION("invalid") { const auto *result = Liquid::try_lookup("redbull"); CHECK(!result); } } TEST_CASE("liquid get by index") { SECTION("water") { const auto *result = Liquid::get_by_index(0); CHECK(result); CHECK(result->name == "water"); CHECK(result->color == "clear"); } SECTION("red wine") { const auto *result = Liquid::get_by_index(16); CHECK(result); CHECK(result->name == "red wine"); CHECK(result->color == "red"); } SECTION("out of range") { const auto *result = Liquid::get_by_index(17); CHECK(!result); } SECTION("negative") { const auto *result = Liquid::get_by_index(-1); CHECK(!result); } } TEST_CASE("material lookup with default") { SECTION("valid cases match by full name") { using std::make_tuple; Material::Type expected; std::string_view name; std::tie(expected, name) = GENERATE(table<Material::Type, std::string_view>({ // clang-format off make_tuple(Material::Type::None, "none"), make_tuple(Material::Type::Default, "default"), make_tuple(Material::Type::Adamantite, "adamantite"), make_tuple(Material::Type::Iron, "iron"), make_tuple(Material::Type::Glass, "glass"), make_tuple(Material::Type::Bronze, "bronze"), make_tuple(Material::Type::Cloth, "cloth"), make_tuple(Material::Type::Wood, "wood"), make_tuple(Material::Type::Paper, "paper"), make_tuple(Material::Type::Steel, "steel"), make_tuple(Material::Type::Stone, "stone"), make_tuple(Material::Type::Food, "food"), make_tuple(Material::Type::Silver, "silver"), make_tuple(Material::Type::Gold, "gold"), make_tuple(Material::Type::Leather, "leather"), make_tuple(Material::Type::Vellum, "vellum"), make_tuple(Material::Type::China, "china"), make_tuple(Material::Type::Clay, "clay"), make_tuple(Material::Type::Brass, "brass"), make_tuple(Material::Type::Bone, "bone"), make_tuple(Material::Type::Platinum, "platinum"), make_tuple(Material::Type::Pearl, "pearl"), make_tuple(Material::Type::Mithril, "mithril"), make_tuple(Material::Type::Octarine, "octarine") // clang-format on })); SECTION("ok") { const auto *result = Material::lookup_with_default(name); CHECK(result == &Materials[magic_enum::enum_integer<Material::Type>(expected)]); } } SECTION("invalid uses default") { const auto *result = Material::lookup_with_default("cotton"); CHECK(result == &Materials[magic_enum::enum_integer<Material::Type>(Material::Type::Default)]); } } TEST_CASE("material get magical resilience") { SECTION("none") { const auto result = Material::get_magical_resilience(Material::Type::None); CHECK(result == 0); } SECTION("default") { const auto result = Material::get_magical_resilience(Material::Type::Default); CHECK(result == 40); } SECTION("octarine") { const auto result = Material::get_magical_resilience(Material::Type::Octarine); CHECK(result == 100); } }
/////////////////////////////////////////////////////////////////////////////////////// // Data Analysis Code Project for the External Target Facility, HIRFL-CSR, @IMP // // // // BINGER/inc/etf/TAMath/iterFit4Single.cxx // // iterFit4Single.cxx -- source file for method TAMath::iterFit4Single // // Introduction: A transmutation of iterFit4. For PDCs around the target, // // left-right ambiguity doesn't exist for X1-X2 both-fired cases. This should be made// // clear in the code. Iteration only needs to revolve around the singly fried wires. // // iterFit4Single takes care of this. But please note that left-right ambiguity still// // persists for Ma's DCs around Ta. So this method only suits for PDCs' tracking. // // // // Author: SUN Yazhou, asia.rabbit@163.com. // // Created: 2020/03/12 // // Last modified: 2020/03/12, SUN Yazhou. // // // // // // Copyright (C) 2017-2020, SUN Yazhou. // // All rights reserved. // /////////////////////////////////////////////////////////////////////////////////////// /// make sure that x, z, and r are initialized to -9999. for unfired wires /// the program relis on this to function void TAMath::IterFit4Single(const double *z, const double *x, const double *r, double *k, double *b, int *gGOOD, const int (*LAYER)[6], double d2ThrePD){ short nSingle[2]{}; // number of singly fired wires [0-1]: [PDCArr-U--D] short singleLAYER[2]{}; // [PDCArr-U--D], layer ID of the singly fired layers for(int i = 2; i--;){ if(gGOOD[i] == 1) nSingle[i] = 1; else if(gGOOD[i] != 2) TAPopMsg::Error("TAMath", "iterFit4Single: gGOOD[%d]: %d, neither 0 or 1.", i, gGOOD[i]); } // end for const short n = pow(2, nSingle[0] + nSingle[1]); // count of iterations double d2[2], kl[3], bl[3]; kl[2] = k[2]; bl[2] = b[2]; // postMagTrk's parameters // initialize kL and bL using LSM // the total d2, including contributions from dxTa and dx2 double d2Tmin = 1E200, d2T; // T: total double zt[2][6]{}, xt[2][6]{}; for(int i = 2; i--;){ for(int j = 6; j--;){ zt[i][j] = -9999.; xt[i][j] = -9999.; } } // end the initialization // assign k and b, so as to calculate theta Dsquare(z, x, k[0], b[0], gGOOD[0], LAYER[0], d2ThrePD); Dsquare(z+6, x+6, k[1], b[1], gGOOD[1], LAYER[1], d2ThrePD); double cosTheta[2], sinTheta[2]; for(int i = 0; i < 2; i++){ cosTheta[i] = 1. / sqrt(1. + k[i]*k[i]); sinTheta[i] = k[i] * cosTheta[i]; } // assign signs for X1-X2 bothly fired wires for(int I = 0; I < 2; I++){ // loop over PDCArrU-D for(int i = 0; i < 2; i++){ // loop over PDC0-1 const short s = i*2, l = I*6+s; // l, l+1: X1, X2 if(-9999. == x[l] || -9999. == x[l+1]){ if(-9999. == x[l]) singleLAYER[I] = s+1; if(-9999. == x[l+1]) singleLAYER[I] = s; continue; // not bothly fired } // end if const double dz = fabs(z[l] - z[l+1]); // dz~10. for X1-X2 wires if(dz < 15. && dz > 8.){ // adjacent layers // X1 // const double R0 = r[l] * Sign(x[l] - x[l+1]); // the signed drift distance zt[I][s] = z[l] + R0 * sinTheta[I]; xt[I][s] = x[l] - R0 * cosTheta[I]; // X2 // const double R1 = r[l+1] * Sign(x[l+1] - x[l]); zt[I][s+1] = z[l+1] + R1 * sinTheta[I]; xt[I][s+1] = x[l+1] - R1 * cosTheta[I]; } // end outer if else TAPopMsg::Error("TAMath", "iterFit4Single: peculiar, supposed to be adjacent X1X2."); } // end for over i } // end for over I for(int i = 0; i < n; i++){ // each i represents a set of r signs // assign signs to drift distances for(int I = 0; I < 2; I++){ // loop over DCTas if(nSingle[I]){ const short s = singleLAYER[I], l = I*6+s; const double R = r[l] * // the signed drift distance (2 * ((i>>(I*nSingle[0])) & 1) - 1); zt[I][s] = z[l] + R * sinTheta[I]; xt[I][s] = x[l] - R * cosTheta[I]; } // end for over j d2[I] = Dsquare(zt[I], xt[I], kl[I], bl[I], gGOOD[I], LAYER[I], d2ThrePD); } // end for over I (DCTas) d2T = d2[0] + d2[1] + Dx2DxTa_2(kl, bl); if(d2T < d2Tmin){ // acknowledge the result k[0] = kl[0]; k[1] = kl[1]; b[0] = bl[0]; b[1] = bl[1]; d2Tmin = d2T; } // end if } // end for over i } // end of IterFit4
// Tests undefining macros. //- @M defines MacroM #define M //- @M undefines MacroM #undef M #undef NEVER_DEFINED //- @M defines OtherMacroM #define M //- @M undefines OtherMacroM #undef M
#pragma once #include <served/served.hpp> void system_general_get(served::response &, const served::request &); void system_location_get(served::response &, const served::request &); void system_location_put(served::response &, const served::request &); void system_location_post(served::response &, const served::request &); void system_network_get(served::response &, const served::request &); void system_network_put(served::response &, const served::request &); void system_ui_pages_get(served::response &, const served::request &); void system_users_get(served::response &, const served::request &); void system_users_put(served::response &, const served::request &); void system_users_del(served::response &, const served::request &); void system_users_post(served::response &, const served::request &); void system_cities_get(served::response &, const served::request &); void system_users_me_get(served::response &, const served::request &); void system_survey_get(served::response &, const served::request &); void system_survey_put(served::response &, const served::request &); void system_survey_del(served::response &, const served::request &); void system_survey_post(served::response &, const served::request &); void system_pms_get(served::response &, const served::request &); void system_pms_put(served::response &, const served::request &); void system_pms_del(served::response &, const served::request &); void system_pms_post(served::response &, const served::request &); void system_vod_account_get(served::response &, const served::request &); void system_vod_account_put(served::response &, const served::request &); void system_vod_account_del(served::response &, const served::request &); void system_vod_account_post(served::response &, const served::request &); void system_permission_get(served::response &, const served::request &); void system_permission_put(served::response &, const served::request &); void system_permission_post(served::response &, const served::request &); void system_permission_del(served::response &, const served::request &); void system_weektime_get(served::response &, const served::request &); void system_weektime_put(served::response &, const served::request &); void system_weektime_del(served::response &, const served::request &); void system_weektime_post(served::response &, const served::request &); void system_backup_list_get(served::response &, const served::request &); void system_backup_get(served::response &, const served::request &); void system_backup_post(served::response &, const served::request &); void system_backup_put(served::response &, const served::request &); void system_backup_del(served::response &, const served::request &); void system_license_get(served::response &, const served::request &); void system_license_put(served::response &, const served::request &); void system_firmware_put(served::response &, const served::request &); void system_restart_get(served::response &, const served::request &); void system_stop_get(served::response &, const served::request &); void system_reboot_get(served::response &, const served::request &); void system_logout_get(served::response &, const served::request &); void system_operations_get(served::response &res, const served::request &req); void system_sensor_get(served::response &res, const served::request &req); void system_sensor_put(served::response &res, const served::request &req); void system_sensor_post(served::response &res, const served::request &req); void system_sensor_del(served::response &res, const served::request &req);
/*! @file @brief 置換ダイアログ @author Norio Nakatani @date 2001/06/23 N.Nakatani 単語単位で検索する機能を実装 */ /* Copyright (C) 1998-2001, Norio Nakatani Copyright (C) 2001, genta, Stonee, hor, YAZAKI Copyright (C) 2002, MIK, hor, novice, genta, aroka, YAZAKI Copyright (C) 2006, かろと, ryoji Copyright (C) 2007, ryoji Copyright (C) 2009, ryoji Copyright (C) 2012, Uchi Copyright (C) 2018-2021, Sakura Editor Organization This source code is designed for sakura editor. Please contact the copyright holder to use this code for other purpose. */ #include "StdAfx.h" #include "dlg/CDlgReplace.h" #include "view/CEditView.h" #include "util/shell.h" #include "util/window.h" #include "sakura_rc.h" #include "sakura.hh" //置換 CDlgReplace.cpp //@@@ 2002.01.07 add start MIK const DWORD p_helpids[] = { //11900 IDC_BUTTON_SEARCHNEXT, HIDC_REP_BUTTON_SEARCHNEXT, //下検索 IDC_BUTTON_SEARCHPREV, HIDC_REP_BUTTON_SEARCHPREV, //上検索 IDC_BUTTON_REPALCE, HIDC_REP_BUTTON_REPALCE, //置換 IDC_BUTTON_REPALCEALL, HIDC_REP_BUTTON_REPALCEALL, //全置換 IDCANCEL, HIDCANCEL_REP, //キャンセル IDC_BUTTON_HELP, HIDC_REP_BUTTON_HELP, //ヘルプ IDC_CHK_PASTE, HIDC_REP_CHK_PASTE, //クリップボードから貼り付け IDC_CHK_WORD, HIDC_REP_CHK_WORD, //単語単位 IDC_CHK_LOHICASE, HIDC_REP_CHK_LOHICASE, //大文字小文字 IDC_CHK_REGULAREXP, HIDC_REP_CHK_REGULAREXP, //正規表現 IDC_CHECK_NOTIFYNOTFOUND, HIDC_REP_CHECK_NOTIFYNOTFOUND, //見つからないときに通知 IDC_CHECK_bAutoCloseDlgReplace, HIDC_REP_CHECK_bAutoCloseDlgReplace, //自動的に閉じる IDC_COMBO_TEXT, HIDC_REP_COMBO_TEXT, //置換前 IDC_COMBO_TEXT2, HIDC_REP_COMBO_TEXT2, //置換後 IDC_RADIO_REPLACE, HIDC_REP_RADIO_REPLACE, //置換対象:置換 IDC_RADIO_INSERT, HIDC_REP_RADIO_INSERT, //置換対象:挿入 IDC_RADIO_ADD, HIDC_REP_RADIO_ADD, //置換対象:追加 IDC_RADIO_LINEDELETE, HIDC_REP_RADIO_LINEDELETE, //置換対象:行削除 IDC_RADIO_SELECTEDAREA, HIDC_REP_RADIO_SELECTEDAREA, //範囲:全体 IDC_RADIO_ALLAREA, HIDC_REP_RADIO_ALLAREA, //範囲:選択範囲 IDC_STATIC_JRE32VER, HIDC_REP_STATIC_JRE32VER, //正規表現バージョン IDC_BUTTON_SETMARK, HIDC_REP_BUTTON_SETMARK, //2002.01.16 hor 検索該当行をマーク IDC_CHECK_SEARCHALL, HIDC_REP_CHECK_SEARCHALL, //2002.01.26 hor 先頭(末尾)から再検索 IDC_CHECK_CONSECUTIVEALL, HIDC_REP_CHECK_CONSECUTIVEALL, //「すべて置換」は置換の繰返し // 2007.01.16 ryoji // IDC_STATIC, -1, 0, 0 }; //@@@ 2002.01.07 add end MIK CDlgReplace::CDlgReplace() { m_sSearchOption.Reset(); // 検索オプション m_bConsecutiveAll = FALSE; // 「すべて置換」は置換の繰返し // 2007.01.16 ryoji m_bSelectedArea = FALSE; // 選択範囲内置換 m_nReplaceTarget = 0; // 置換対象 // 2001.12.03 hor m_nPaste = FALSE; // 貼り付ける? // 2001.12.03 hor m_nReplaceCnt = 0; //すべて置換の実行結果 // 2002.02.08 hor m_bCanceled = false; //すべて置換を中断したか // 2002.02.08 hor return; } /*! コンボボックスのドロップダウンメッセージを捕捉する @date 2013.03.24 novice 新規作成 */ BOOL CDlgReplace::OnCbnDropDown( HWND hwndCtl, int wID ) { switch( wID ){ case IDC_COMBO_TEXT: if ( ::SendMessage(hwndCtl, CB_GETCOUNT, 0L, 0L) == 0) { int nSize = m_pShareData->m_sSearchKeywords.m_aSearchKeys.size(); for (int i = 0; i < nSize; ++i) { Combo_AddString( hwndCtl, m_pShareData->m_sSearchKeywords.m_aSearchKeys[i] ); } } break; case IDC_COMBO_TEXT2: if ( ::SendMessage(hwndCtl, CB_GETCOUNT, 0L, 0L) == 0) { int nSize = m_pShareData->m_sSearchKeywords.m_aReplaceKeys.size(); for (int i = 0; i < nSize; ++i) { Combo_AddString( hwndCtl, m_pShareData->m_sSearchKeywords.m_aReplaceKeys[i] ); } } break; } return CDialog::OnCbnDropDown( hwndCtl, wID ); } /* モードレスダイアログの表示 */ HWND CDlgReplace::DoModeless( HINSTANCE hInstance, HWND hwndParent, LPARAM lParam, BOOL bSelected ) { m_sSearchOption = m_pShareData->m_Common.m_sSearch.m_sSearchOption; // 検索オプション m_bConsecutiveAll = m_pShareData->m_Common.m_sSearch.m_bConsecutiveAll; // 「すべて置換」は置換の繰返し // 2007.01.16 ryoji m_bSelectedArea = m_pShareData->m_Common.m_sSearch.m_bSelectedArea; // 選択範囲内置換 m_bNOTIFYNOTFOUND = m_pShareData->m_Common.m_sSearch.m_bNOTIFYNOTFOUND; // 検索/置換 見つからないときメッセージを表示 m_bSelected = bSelected; m_ptEscCaretPos_PHY = ((CEditView*)lParam)->GetCaret().GetCaretLogicPos(); // 検索/置換開始時のカーソル位置退避 ((CEditView*)lParam)->m_bSearch = TRUE; // 検索/置換開始位置の登録有無 02/07/28 ai return CDialog::DoModeless( hInstance, hwndParent, IDD_REPLACE, lParam, SW_SHOW ); } /* モードレス時:置換・検索対象となるビューの変更 */ void CDlgReplace::ChangeView( LPARAM pcEditView ) { m_lParam = pcEditView; return; } /* ダイアログデータの設定 */ void CDlgReplace::SetData( void ) { // 検索文字列/置換後文字列リストの設定(関数化) 2010/5/26 Uchi SetCombosList(); /* 英大文字と英小文字を区別する */ ::CheckDlgButton( GetHwnd(), IDC_CHK_LOHICASE, m_sSearchOption.bLoHiCase ); // 2001/06/23 N.Nakatani /* 単語単位で探す */ ::CheckDlgButton( GetHwnd(), IDC_CHK_WORD, m_sSearchOption.bWordOnly ); /* 「すべて置換」は置換の繰返し */ // 2007.01.16 ryoji ::CheckDlgButton( GetHwnd(), IDC_CHECK_CONSECUTIVEALL, m_bConsecutiveAll ); // From Here Jun. 29, 2001 genta // 正規表現ライブラリの差し替えに伴う処理の見直し // 処理フロー及び判定条件の見直し。必ず正規表現のチェックと // 無関係にCheckRegexpVersionを通過するようにした。 if( CheckRegexpVersion( GetHwnd(), IDC_STATIC_JRE32VER, false ) && m_sSearchOption.bRegularExp){ /* 英大文字と英小文字を区別する */ ::CheckDlgButton( GetHwnd(), IDC_CHK_REGULAREXP, 1 ); // 2001/06/23 N.Nakatani /* 単語単位で探す */ ::EnableWindow( GetItemHwnd( IDC_CHK_WORD ), FALSE ); } else { ::CheckDlgButton( GetHwnd(), IDC_CHK_REGULAREXP, 0 ); /*「すべて置換」は置換の繰返し */ ::EnableWindow( GetItemHwnd( IDC_CHECK_CONSECUTIVEALL ), FALSE ); // 2007.01.16 ryoji } // To Here Jun. 29, 2001 genta /* 検索/置換 見つからないときメッセージを表示 */ ::CheckDlgButton( GetHwnd(), IDC_CHECK_NOTIFYNOTFOUND, m_bNOTIFYNOTFOUND ); /* 置換 ダイアログを自動的に閉じる */ ::CheckDlgButton( GetHwnd(), IDC_CHECK_bAutoCloseDlgReplace, m_pShareData->m_Common.m_sSearch.m_bAutoCloseDlgReplace ); /* 先頭(末尾)から再検索 2002.01.26 hor */ ::CheckDlgButton( GetHwnd(), IDC_CHECK_SEARCHALL, m_pShareData->m_Common.m_sSearch.m_bSearchAll ); // From Here 2001.12.03 hor // クリップボードから貼り付ける? ::CheckDlgButton( GetHwnd(), IDC_CHK_PASTE, m_nPaste ); // 置換対象 if(m_nReplaceTarget==0){ ::CheckDlgButton( GetHwnd(), IDC_RADIO_REPLACE, TRUE ); }else if(m_nReplaceTarget==1){ ::CheckDlgButton( GetHwnd(), IDC_RADIO_INSERT, TRUE ); }else if(m_nReplaceTarget==2){ ::CheckDlgButton( GetHwnd(), IDC_RADIO_ADD, TRUE ); }else if(m_nReplaceTarget==3){ ::CheckDlgButton( GetHwnd(), IDC_RADIO_LINEDELETE, TRUE ); ::EnableWindow( GetItemHwnd( IDC_COMBO_TEXT2 ), FALSE ); ::EnableWindow( GetItemHwnd( IDC_CHK_PASTE ), FALSE ); } // To Here 2001.12.03 hor return; } // 検索文字列/置換後文字列リストの設定 // 2010/5/26 Uchi void CDlgReplace::SetCombosList( void ) { HWND hwndCombo; /* 検索文字列 */ hwndCombo = GetItemHwnd( IDC_COMBO_TEXT ); while (Combo_GetCount(hwndCombo) > 0) { Combo_DeleteString( hwndCombo, 0); } std::wstring strText; if( !ApiWrap::DlgItem_GetText( GetHwnd(), IDC_COMBO_TEXT, strText ) || strText != m_strText ) { ::DlgItem_SetText( GetHwnd(), IDC_COMBO_TEXT, m_strText.c_str() ); } /* 置換後文字列 */ hwndCombo = GetItemHwnd( IDC_COMBO_TEXT2 ); while (Combo_GetCount(hwndCombo) > 0) { Combo_DeleteString( hwndCombo, 0); } std::wstring strText2; if( !ApiWrap::DlgItem_GetText( GetHwnd(), IDC_COMBO_TEXT2, strText2 ) || strText2 != m_strText2 ) { ::DlgItem_SetText( GetHwnd(), IDC_COMBO_TEXT2, m_strText2.c_str() ); } } /* ダイアログデータの取得 */ /* 0==条件未入力 0より大きい==正常 0より小さい==入力エラー */ int CDlgReplace::GetData( void ) { /* 英大文字と英小文字を区別する */ m_sSearchOption.bLoHiCase = (0!=IsDlgButtonChecked( GetHwnd(), IDC_CHK_LOHICASE )); // 2001/06/23 N.Nakatani /* 単語単位で探す */ m_sSearchOption.bWordOnly = (0!=IsDlgButtonChecked( GetHwnd(), IDC_CHK_WORD )); /* 「すべて置換」は置換の繰返し */ // 2007.01.16 ryoji m_bConsecutiveAll = ::IsDlgButtonChecked( GetHwnd(), IDC_CHECK_CONSECUTIVEALL ); /* 正規表現 */ m_sSearchOption.bRegularExp = (0!=IsDlgButtonChecked( GetHwnd(), IDC_CHK_REGULAREXP )); /* 選択範囲内置換 */ m_bSelectedArea = ::IsDlgButtonChecked( GetHwnd(), IDC_RADIO_SELECTEDAREA ); /* 検索/置換 見つからないときメッセージを表示 */ m_bNOTIFYNOTFOUND = ::IsDlgButtonChecked( GetHwnd(), IDC_CHECK_NOTIFYNOTFOUND ); m_pShareData->m_Common.m_sSearch.m_bConsecutiveAll = m_bConsecutiveAll; // 1==「すべて置換」は置換の繰返し // 2007.01.16 ryoji m_pShareData->m_Common.m_sSearch.m_bSelectedArea = m_bSelectedArea; // 選択範囲内置換 m_pShareData->m_Common.m_sSearch.m_bNOTIFYNOTFOUND = m_bNOTIFYNOTFOUND; // 検索/置換 見つからないときメッセージを表示 /* 検索文字列 */ ApiWrap::DlgItem_GetText( GetHwnd(), IDC_COMBO_TEXT, m_strText ); /* 置換後文字列 */ if( ::IsDlgButtonChecked( GetHwnd(), IDC_RADIO_LINEDELETE ) ){ m_strText2 = L""; }else{ ApiWrap::DlgItem_GetText( GetHwnd(), IDC_COMBO_TEXT2, m_strText2 ); } /* 置換 ダイアログを自動的に閉じる */ m_pShareData->m_Common.m_sSearch.m_bAutoCloseDlgReplace = ::IsDlgButtonChecked( GetHwnd(), IDC_CHECK_bAutoCloseDlgReplace ); /* 先頭(末尾)から再検索 2002.01.26 hor */ m_pShareData->m_Common.m_sSearch.m_bSearchAll = ::IsDlgButtonChecked( GetHwnd(), IDC_CHECK_SEARCHALL ); if( 0 < m_strText.size() ){ /* 正規表現? */ // From Here Jun. 26, 2001 genta // 正規表現ライブラリの差し替えに伴う処理の見直し int nFlag = 0x00; nFlag |= m_sSearchOption.bLoHiCase ? 0x01 : 0x00; if( m_sSearchOption.bRegularExp && !CheckRegexpSyntax( m_strText.c_str(), GetHwnd(), true, nFlag ) ){ return -1; } // To Here Jun. 26, 2001 genta 正規表現ライブラリ差し替え /* 検索文字列 */ //@@@ 2002.2.2 YAZAKI CShareData.AddToSearchKeyArr()追加に伴う変更 if( m_strText.size() < _MAX_PATH ){ CSearchKeywordManager().AddToSearchKeyArr( m_strText.c_str() ); m_pShareData->m_Common.m_sSearch.m_sSearchOption = m_sSearchOption; // 検索オプション } // 2011.12.18 viewに直接設定 CEditView* pcEditView = (CEditView*)m_lParam; if( pcEditView->m_strCurSearchKey == m_strText && pcEditView->m_sCurSearchOption == m_sSearchOption ){ }else{ pcEditView->m_strCurSearchKey = m_strText; pcEditView->m_sCurSearchOption = m_sSearchOption; pcEditView->m_bCurSearchUpdate = true; } pcEditView->m_nCurSearchKeySequence = GetDllShareData().m_Common.m_sSearch.m_nSearchKeySequence; /* 置換後文字列 */ //@@@ 2002.2.2 YAZAKI CShareData.AddToReplaceKeyArr()追加に伴う変更 if( m_strText2.size() < _MAX_PATH ){ CSearchKeywordManager().AddToReplaceKeyArr( m_strText2.c_str() ); } m_nReplaceKeySequence = GetDllShareData().m_Common.m_sSearch.m_nReplaceKeySequence; // From Here 2001.12.03 hor // クリップボードから貼り付ける? m_nPaste=IsDlgButtonChecked( GetHwnd(), IDC_CHK_PASTE ); ::EnableWindow( GetItemHwnd( IDC_COMBO_TEXT2 ), !m_nPaste ); // 置換対象 m_nReplaceTarget=0; if(::IsDlgButtonChecked( GetHwnd(), IDC_RADIO_INSERT )){ m_nReplaceTarget=1; }else if(::IsDlgButtonChecked( GetHwnd(), IDC_RADIO_ADD )){ m_nReplaceTarget=2; }else if(::IsDlgButtonChecked( GetHwnd(), IDC_RADIO_LINEDELETE )){ m_nReplaceTarget=3; m_nPaste = FALSE; ::EnableWindow( GetItemHwnd( IDC_COMBO_TEXT2 ), FALSE ); } // To Here 2001.12.03 hor // 検索文字列/置換後文字列リストの設定 2010/5/26 Uchi if (!m_bModal) { SetCombosList(); } return 1; }else{ return 0; } } BOOL CDlgReplace::OnInitDialog( HWND hwndDlg, WPARAM wParam, LPARAM lParam ) { _SetHwnd( hwndDlg ); // Jun. 26, 2001 genta // この位置で正規表現の初期化をする必要はない // 他との一貫性を保つため削除 /* ユーザーがコンボ ボックスのエディット コントロールに入力できるテキストの長さを制限する */ // Combo_LimitText( GetItemHwnd( IDC_COMBO_TEXT ), _MAX_PATH - 1 ); // Combo_LimitText( GetItemHwnd( IDC_COMBO_TEXT2 ), _MAX_PATH - 1 ); /* コンボボックスのユーザー インターフェイスを拡張インターフェースにする */ Combo_SetExtendedUI( GetItemHwnd( IDC_COMBO_TEXT ), TRUE ); Combo_SetExtendedUI( GetItemHwnd( IDC_COMBO_TEXT2 ), TRUE ); /* テキスト選択中か */ if( m_bSelected ){ ::EnableWindow( ::GetDlgItem( hwndDlg, IDC_BUTTON_SEARCHPREV ), FALSE ); // 2001.12.03 hor コメント解除 ::EnableWindow( ::GetDlgItem( hwndDlg, IDC_BUTTON_SEARCHNEXT ), FALSE ); // 2001.12.03 hor コメント解除 ::EnableWindow( ::GetDlgItem( hwndDlg, IDC_BUTTON_REPALCE ), FALSE ); // 2001.12.03 hor コメント解除 ::CheckDlgButton( GetHwnd(), IDC_RADIO_SELECTEDAREA, TRUE ); // ::CheckDlgButton( GetHwnd(), IDC_RADIO_ALLAREA, FALSE ); // 2001.12.03 hor コメント }else{ // ::EnableWindow( ::GetDlgItem( hwndDlg, IDC_RADIO_SELECTEDAREA ), FALSE ); // 2001.12.03 hor コメント // ::CheckDlgButton( GetHwnd(), IDC_RADIO_SELECTEDAREA, FALSE ); // 2001.12.03 hor コメント ::CheckDlgButton( GetHwnd(), IDC_RADIO_ALLAREA, TRUE ); } SetComboBoxDeleter(GetItemHwnd(IDC_COMBO_TEXT), &m_cRecentSearch); SetComboBoxDeleter(GetItemHwnd(IDC_COMBO_TEXT2), &m_cRecentReplace); BOOL bRet = CDialog::OnInitDialog( hwndDlg, wParam, lParam ); if( !bRet ) return bRet; // フォント設定 2012/11/27 Uchi HFONT hFontOld = (HFONT)::SendMessageAny( GetItemHwnd( IDC_COMBO_TEXT ), WM_GETFONT, 0, 0 ); HFONT hFont = SetMainFont( GetItemHwnd( IDC_COMBO_TEXT ) ); m_cFontText.SetFont( hFontOld, hFont, GetItemHwnd( IDC_COMBO_TEXT ) ); hFontOld = (HFONT)::SendMessageAny( GetItemHwnd( IDC_COMBO_TEXT2 ), WM_GETFONT, 0, 0 ); hFont = SetMainFont( GetItemHwnd( IDC_COMBO_TEXT2 ) ); m_cFontText2.SetFont( hFontOld, hFont, GetItemHwnd( IDC_COMBO_TEXT2 ) ); return bRet; } BOOL CDlgReplace::OnDestroy() { m_cFontText.ReleaseOnDestroy(); m_cFontText2.ReleaseOnDestroy(); return CDialog::OnDestroy(); } BOOL CDlgReplace::OnBnClicked( int wID ) { int nRet; CEditView* pcEditView = (CEditView*)m_lParam; switch( wID ){ case IDC_CHK_PASTE: /* テキストの貼り付け */ if( ::IsDlgButtonChecked( GetHwnd(), IDC_CHK_PASTE ) && !pcEditView->m_pcEditDoc->m_cDocEditor.IsEnablePaste() ){ OkMessage( GetHwnd(), LS(STR_DLGREPLC_CLIPBOARD) ); ::CheckDlgButton( GetHwnd(), IDC_CHK_PASTE, FALSE ); } ::EnableWindow( GetItemHwnd( IDC_COMBO_TEXT2 ), !(::IsDlgButtonChecked( GetHwnd(), IDC_CHK_PASTE)) ); return TRUE; // 置換対象 case IDC_RADIO_REPLACE: case IDC_RADIO_INSERT: case IDC_RADIO_ADD: case IDC_RADIO_LINEDELETE: if( ::IsDlgButtonChecked( GetHwnd(), IDC_RADIO_LINEDELETE ) ){ ::EnableWindow( GetItemHwnd( IDC_COMBO_TEXT2 ), FALSE ); ::EnableWindow( GetItemHwnd( IDC_CHK_PASTE ), FALSE ); }else{ ::EnableWindow( GetItemHwnd( IDC_COMBO_TEXT2 ), TRUE ); ::EnableWindow( GetItemHwnd( IDC_CHK_PASTE ), TRUE ); } return TRUE; case IDC_RADIO_SELECTEDAREA: /* 範囲範囲 */ if( ::IsDlgButtonChecked( GetHwnd(), IDC_RADIO_ALLAREA ) ){ ::EnableWindow( GetItemHwnd( IDC_BUTTON_SEARCHPREV ), TRUE ); ::EnableWindow( GetItemHwnd( IDC_BUTTON_SEARCHNEXT ), TRUE ); ::EnableWindow( GetItemHwnd( IDC_BUTTON_REPALCE ), TRUE ); }else{ ::EnableWindow( GetItemHwnd( IDC_BUTTON_SEARCHPREV ), FALSE ); ::EnableWindow( GetItemHwnd( IDC_BUTTON_SEARCHNEXT ), FALSE ); ::EnableWindow( GetItemHwnd( IDC_BUTTON_REPALCE ), FALSE ); } return TRUE; case IDC_RADIO_ALLAREA: /* ファイル全体 */ if( ::IsDlgButtonChecked( GetHwnd(), IDC_RADIO_ALLAREA ) ){ ::EnableWindow( GetItemHwnd( IDC_BUTTON_SEARCHPREV ), TRUE ); ::EnableWindow( GetItemHwnd( IDC_BUTTON_SEARCHNEXT ), TRUE ); ::EnableWindow( GetItemHwnd( IDC_BUTTON_REPALCE ), TRUE ); }else{ ::EnableWindow( GetItemHwnd( IDC_BUTTON_SEARCHPREV ), FALSE ); ::EnableWindow( GetItemHwnd( IDC_BUTTON_SEARCHNEXT ), FALSE ); ::EnableWindow( GetItemHwnd( IDC_BUTTON_REPALCE ), FALSE ); } return TRUE; // To Here 2001.12.03 hor case IDC_BUTTON_HELP: /* 「置換」のヘルプ */ //Stonee, 2001/03/12 第四引数を、機能番号からヘルプトピック番号を調べるようにした MyWinHelp( GetHwnd(), HELP_CONTEXT, ::FuncID_To_HelpContextID(F_REPLACE_DIALOG) ); // 2006.10.10 ryoji MyWinHelpに変更に変更 return TRUE; // case IDC_CHK_LOHICASE: /* 大文字と小文字を区別する */ // MYTRACE( L"IDC_CHK_LOHICASE\n" ); // return TRUE; // case IDC_CHK_WORDONLY: /* 一致する単語のみ検索 */ // MYTRACE( L"IDC_CHK_WORDONLY\n" ); // break; case IDC_CHK_REGULAREXP: /* 正規表現 */ // MYTRACE( L"IDC_CHK_REGULAREXP ::IsDlgButtonChecked( GetHwnd(), IDC_CHK_REGULAREXP ) = %d\n", ::IsDlgButtonChecked( GetHwnd(), IDC_CHK_REGULAREXP ) ); if( ::IsDlgButtonChecked( GetHwnd(), IDC_CHK_REGULAREXP ) ){ // From Here Jun. 26, 2001 genta // 正規表現ライブラリの差し替えに伴う処理の見直し if( !CheckRegexpVersion( GetHwnd(), IDC_STATIC_JRE32VER, true ) ){ ::CheckDlgButton( GetHwnd(), IDC_CHK_REGULAREXP, 0 ); }else{ // To Here Jun. 26, 2001 genta /* 英大文字と英小文字を区別する */ // Jan. 31, 2002 genta // 大文字・小文字の区別は正規表現の設定に関わらず保存する //::CheckDlgButton( GetHwnd(), IDC_CHK_LOHICASE, 1 ); //::EnableWindow( GetItemHwnd( IDC_CHK_LOHICASE ), FALSE ); // 2001/06/23 N.Nakatani /* 単語単位で探す */ ::EnableWindow( GetItemHwnd( IDC_CHK_WORD ), FALSE ); /*「すべて置換」は置換の繰返し */ ::EnableWindow( GetItemHwnd( IDC_CHECK_CONSECUTIVEALL ), TRUE ); // 2007.01.16 ryoji } }else{ /* 英大文字と英小文字を区別する */ //::EnableWindow( GetItemHwnd( IDC_CHK_LOHICASE ), TRUE ); // Jan. 31, 2002 genta // 大文字・小文字の区別は正規表現の設定に関わらず保存する //::CheckDlgButton( GetHwnd(), IDC_CHK_LOHICASE, 0 ); // 2001/06/23 N.Nakatani /* 単語単位で探す */ ::EnableWindow( GetItemHwnd( IDC_CHK_WORD ), TRUE ); /*「すべて置換」は置換の繰返し */ ::EnableWindow( GetItemHwnd( IDC_CHECK_CONSECUTIVEALL ), FALSE ); // 2007.01.16 ryoji } return TRUE; // case IDOK: /* 下検索 */ // /* ダイアログデータの取得 */ // nRet = GetData(); // if( 0 < nRet ){ // ::EndDialog( hwndDlg, 2 ); // }else // if( 0 == nRet ){ // ::EndDialog( hwndDlg, 0 ); // } // return TRUE; case IDC_BUTTON_SEARCHPREV: /* 上検索 */ nRet = GetData(); if( 0 < nRet ){ // 検索開始位置を登録 02/07/28 ai start if( FALSE != pcEditView->m_bSearch ){ pcEditView->m_ptSrchStartPos_PHY = m_ptEscCaretPos_PHY; pcEditView->m_bSearch = FALSE; }// 02/07/28 ai end /* コマンドコードによる処理振り分け */ /* 前を検索 */ pcEditView->GetCommander().HandleCommand( F_SEARCH_PREV, true, (LPARAM)GetHwnd(), 0, 0, 0 ); /* 再描画(0文字幅マッチでキャレットを表示するため) */ pcEditView->Redraw(); // 前回0文字幅マッチの消去にも必要 }else if(nRet == 0){ OkMessage( GetHwnd(), LS(STR_DLGREPLC_STR) ); } return TRUE; case IDC_BUTTON_SEARCHNEXT: /* 下検索 */ nRet = GetData(); if( 0 < nRet ){ // 検索開始位置を登録 02/07/28 ai start if( FALSE != pcEditView->m_bSearch ){ pcEditView->m_ptSrchStartPos_PHY = m_ptEscCaretPos_PHY; pcEditView->m_bSearch = FALSE; }// 02/07/28 ai end /* コマンドコードによる処理振り分け */ /* 次を検索 */ pcEditView->GetCommander().HandleCommand( F_SEARCH_NEXT, true, (LPARAM)GetHwnd(), 0, 0, 0 ); /* 再描画(0文字幅マッチでキャレットを表示するため) */ pcEditView->Redraw(); // 前回0文字幅マッチの消去にも必要 }else if(nRet == 0){ OkMessage( GetHwnd(), LS(STR_DLGREPLC_STR) ); } return TRUE; case IDC_BUTTON_SETMARK: //2002.01.16 hor 該当行マーク nRet = GetData(); if( 0 < nRet ){ pcEditView->GetCommander().HandleCommand( F_BOOKMARK_PATTERN, false, 0, 0, 0, 0 ); ::SendMessage(GetHwnd(),WM_NEXTDLGCTL,(WPARAM)GetItemHwnd( IDC_COMBO_TEXT ),TRUE); } return TRUE; case IDC_BUTTON_REPALCE: /* 置換 */ nRet = GetData(); if( 0 < nRet ){ // 置換開始位置を登録 02/07/28 ai start if( FALSE != pcEditView->m_bSearch ){ pcEditView->m_ptSrchStartPos_PHY = m_ptEscCaretPos_PHY; pcEditView->m_bSearch = FALSE; }// 02/07/28 ai end /* 置換 */ //@@@ 2002.2.2 YAZAKI 置換コマンドをCEditViewに新設 //@@@ 2002/04/08 YAZAKI 親ウィンドウのハンドルを渡すように変更。 pcEditView->GetCommander().HandleCommand( F_REPLACE, true, (LPARAM)GetHwnd(), 0, 0, 0 ); /* 再描画 */ pcEditView->GetCommander().HandleCommand( F_REDRAW, true, 0, 0, 0, 0 ); }else if(nRet == 0){ OkMessage( GetHwnd(), LS(STR_DLGREPLC_STR) ); } return TRUE; case IDC_BUTTON_REPALCEALL: /* すべて置換 */ nRet = GetData(); if( 0 < nRet ){ // 置換開始位置を登録 02/07/28 ai start if( FALSE != pcEditView->m_bSearch ){ pcEditView->m_ptSrchStartPos_PHY = m_ptEscCaretPos_PHY; pcEditView->m_bSearch = FALSE; }// 02/07/28 ai end /* すべて行置換時の処置は「すべて置換」は置換の繰返しオプションOFFの場合にして削除 2007.01.16 ryoji */ pcEditView->GetCommander().HandleCommand( F_REPLACE_ALL, true, 0, 0, 0, 0 ); pcEditView->GetCommander().HandleCommand( F_REDRAW, true, 0, 0, 0, 0 ); /* アクティブにする */ ActivateFrameWindow( GetHwnd() ); TopOkMessage( GetHwnd(), LS(STR_DLGREPLC_REPLACE), m_nReplaceCnt); if( !m_bCanceled ){ if( m_bModal ){ /* モーダルダイアログか */ /* 置換ダイアログを閉じる */ ::EndDialog( GetHwnd(), 0 ); }else{ /* 置換 ダイアログを自動的に閉じる */ if( m_pShareData->m_Common.m_sSearch.m_bAutoCloseDlgReplace ){ ::DestroyWindow( GetHwnd() ); } } } return TRUE; }else if(nRet == 0){ OkMessage( GetHwnd(), LS(STR_DLGREPLC_REPSTR) ); } return TRUE; // case IDCANCEL: // ::EndDialog( hwndDlg, 0 ); // return TRUE; } /* 基底クラスメンバ */ return CDialog::OnBnClicked( wID ); } BOOL CDlgReplace::OnActivate( WPARAM wParam, LPARAM lParam ) { // 0文字幅マッチ描画のON/OFF // 2009.11.29 ryoji CEditView* pcEditView = (CEditView*)m_lParam; CLayoutRange cRangeSel = pcEditView->GetSelectionInfo().m_sSelect; if( cRangeSel.IsValid() && cRangeSel.IsLineOne() && cRangeSel.IsOne() ) pcEditView->InvalidateRect(NULL); // アクティブ化/非アクティブ化が完了してから再描画 return CDialog::OnActivate(wParam, lParam); } //@@@ 2002.01.18 add start LPVOID CDlgReplace::GetHelpIdTable(void) { return (LPVOID)p_helpids; } //@@@ 2002.01.18 add end
#include "CResourceManager.h" CResourceManager::CResourceManager() { m_nextTextId = 1; m_nextUIId = 1; m_modified = false; } CResourceManager::~CResourceManager() { for (std::map<UINT32, PackageText*>::iterator it = m_textDatabase.begin(); it != m_textDatabase.end(); it++) { if (it->second->sourceLen > 0 && it->second->source != NULL) delete[] it->second->source; if (it->second->translationLen > 0 && it->second->translation != NULL) delete[] it->second->translation; delete it->second; } for (std::map<UINT32, PackageText*>::iterator it = m_uiDatabase.begin(); it != m_uiDatabase.end(); it++) { if (it->second->sourceLen > 0 && it->second->source != NULL) delete[] it->second->source; if (it->second->translationLen > 0 && it->second->translation != NULL) delete[] it->second->translation; delete it->second; } for (ImageMap::iterator it = m_imageDatabase.begin(); it != m_imageDatabase.end(); it++) { if (it->second->replacementLen > 0) delete[] it->second->replacement; if (it->second->titleLen > 0) delete[] it->second->title; delete[] it->second->hash; // it->second->hash = it->first delete it->second; } for (TextLookupMap::iterator it = m_fastTextLookup.begin(); it != m_fastTextLookup.end(); it++) { // PackageText objects were deleted in first loop it->second->clear(); delete it->second; } m_textDatabase.clear(); m_uiDatabase.clear(); m_imageDatabase.clear(); m_fastTextLookup.clear(); } bool CResourceManager::TranslateText(const char* original, char* buffer, int bufferSize) { UINT32 originalLen = strlen(original); TextLookupMap::const_iterator mp = m_fastTextLookup.find(originalLen); if (mp != m_fastTextLookup.end()) { for (std::vector<PackageText*>::const_iterator it = mp->second->begin(); it != mp->second->end(); it++) { if (strcmp((*it)->source, original) == 0) { if ((*it)->translationLen > 0) { strncpy(buffer, (*it)->translation, bufferSize - 1); buffer[bufferSize - 1] = '\x00'; return true; } return false; } } } m_logger->WriteLine("New dialogue line found: ").WriteText(original); PackageText* data = new PackageText; data->sourceLen = originalLen; data->translationLen = 0; data->source = new char[data->sourceLen + 1]; data->translation = NULL; strncpy(data->source, original, (data->sourceLen + 1)); m_textDatabase.insert(std::pair<UINT32, PackageText*>(m_nextTextId, data)); m_nextTextId++; m_modified = true; if (mp != m_fastTextLookup.end()) { mp->second->push_back(data); } else { std::vector<PackageText*>* vec = new std::vector<PackageText*>; vec->push_back(data); m_fastTextLookup.emplace(std::make_pair<int, std::vector<PackageText*>*>(originalLen, vec)); } return false; } bool CResourceManager::TranslateUserInterface(const char* original, char* buffer, int bufferSize) { UINT32 originalLen = strlen(original); for (std::map<UINT32, PackageText*>::const_iterator it = m_uiDatabase.begin(); it != m_uiDatabase.end(); it++) { if (originalLen == it->second->sourceLen && strcmp(it->second->source, original) == 0) { if (it->second->translationLen > 0) { strncpy(buffer, it->second->translation, bufferSize - 1); buffer[bufferSize - 1] = '\x00'; return true; } return false; } } m_logger->WriteLine("New UI line found: ").WriteText(original); PackageText* data = new PackageText; data->sourceLen = originalLen; data->translationLen = 0; data->source = new char[data->sourceLen + 1]; data->translation = NULL; strncpy(data->source, original, (data->sourceLen + 1)); m_uiDatabase.insert(std::pair<UINT32, PackageText*>(m_nextUIId, data)); m_nextUIId++; m_modified = true; return false; } unsigned char* CResourceManager::TranslateImage(const char* hash, void* imageData, ImageDimensions dimensions, INT32 depth, INT32 flags) { ImageMap::const_iterator mp = m_imageDatabase.find(hash); if (mp != m_imageDatabase.end()) { PackageImage* img = mp->second; if (img->replacementLen > 0) { return img->replacement; } return NULL; } m_logger->WriteLine("New image found: ").WriteText(hash); PackageImage* img = new PackageImage; img->depth = depth; img->flags = flags; img->height = dimensions.height; img->replacementLen = 0; img->replacement = NULL; img->titleLen = 40; img->width = dimensions.width; img->hash = new char[41]; img->title = new char[41]; strncpy(img->hash, hash, 41); strncpy(img->title, hash, 41); img->hash[40] = img->title[40] = '\x00'; m_imageDatabase.emplace(std::make_pair<const char*, PackageImage*>(img->hash, img)); #ifdef AFHOOK_DEVMODE std::wstring name = CUtils::GetGameDirectory(L"/Dump/"); name += std::wstring(hash, hash + strlen(hash)); name += L".png"; if (GetFileAttributesW(name.c_str()) == 0xFFFFFFFF) { FILE* file = _wfopen(name.c_str(), L"wb"); CMemoryStream* stream = new CMemoryStream(imageData); CImageWriter* writer = new CImageWriter(dimensions.width, dimensions.height); switch (flags & 0xFF) { case 2: if (depth & 0x4) { CImageWriter::Opaque1(stream, writer, dimensions.width, dimensions.height, depth); } else { CImageWriter::Opaque1(stream, writer, dimensions.width, dimensions.height, depth); } writer->write(file); break; case 3: CImageWriter::Transparent(stream, writer, dimensions.width, dimensions.height, depth); writer->write(file); break; default: fclose(file); } delete stream; delete writer; } #endif m_modified = true; return false; } // Loading/saving below void CResourceManager::LoadPackage(const char* filename) { int size = MultiByteToWideChar(CP_UTF8, NULL, filename, -1, NULL, 0); wchar_t* widefile = new wchar_t[size]; MultiByteToWideChar(CP_UTF8, NULL, filename, -1, widefile, size); this->LoadPackage(widefile); delete[] widefile; } void CResourceManager::LoadPackage(const std::wstring& filename) { std::ifstream loadingPackage(filename, std::ios::in | std::ios::binary); if (!loadingPackage) { m_logger->WriteLine("Unable to open package file"); return; } // Try to load header PackageHeader header; loadingPackage.read((char*) &header, sizeof(PackageHeader)); if (header.magicHeader != PACKAGE_MAGIC_HEADER) { m_logger->WriteLine("Package file has invalid header"); loadingPackage.close(); return; } // Text translations loadingPackage.seekg(header.textOffset); for (UINT32 i = 0; i < header.textCount; i++) { UINT32 id; UINT32 source; UINT32 translated; loadingPackage.read((char*) &id, 4); loadingPackage.read((char*) &source, 4); loadingPackage.read((char*) &translated, 4); if (source <= 1) { continue; } PackageText* data = new PackageText; data->sourceLen = (source - 1); data->source = new char[source]; loadingPackage.read(data->source, source); if (translated > 1) { data->translationLen = (translated - 1); data->translation = new char[translated]; loadingPackage.read(data->translation, translated); } else { data->translationLen = 0; data->translation = NULL; } m_textDatabase.insert(std::pair<UINT32, PackageText*>(id, data)); if (id >= m_nextTextId) { m_nextTextId = (id + 1); } } // UI loadingPackage.seekg(header.uiOffset); for (UINT32 i = 0; i < header.uiCount; i++) { UINT32 id; UINT32 source; UINT32 translated; loadingPackage.read((char*) &id, 4); loadingPackage.read((char*) &source, 4); loadingPackage.read((char*) &translated, 4); if (source <= 1) { // what continue; } PackageText* data = new PackageText; data->sourceLen = (source - 1); data->source = new char[source]; loadingPackage.read(data->source, source); if (translated > 1) { data->translationLen = (translated - 1); data->translation = new char[translated]; loadingPackage.read(data->translation, translated); } else { data->translationLen = 0; data->translation = NULL; } m_uiDatabase.insert(std::pair<UINT32, PackageText*>(id, data)); if (id >= m_nextUIId) { m_nextUIId = (id + 1); } } // Images loadingPackage.seekg(header.imageOffset); for (UINT32 i = 0; i < header.imageCount; i++) { PackageImage* pkg = new PackageImage; UINT32 titleLen = 0; pkg->hash = new char[41]; pkg->hash[40] = '\x00'; loadingPackage.read(pkg->hash, 40); loadingPackage.read((char*) &titleLen, 4); pkg->title = new char[titleLen]; pkg->titleLen = titleLen - 1; loadingPackage.read(pkg->title, titleLen); loadingPackage.read((char*) &pkg->width, 2); loadingPackage.read((char*) &pkg->height, 2); loadingPackage.read((char*) &pkg->flags, 4); loadingPackage.read((char*) &pkg->depth, 4); loadingPackage.read((char*) &pkg->replacementLen, 4); if (pkg->replacementLen > 0) { pkg->replacement = new unsigned char[pkg->replacementLen]; loadingPackage.read((char*) pkg->replacement, pkg->replacementLen); } else { pkg->replacement = NULL; } m_imageDatabase.insert(std::pair<const char*, PackageImage*>(pkg->hash, pkg)); } for (std::map<UINT32, PackageText*>::const_iterator it = m_textDatabase.begin(); it != m_textDatabase.end(); it++) { TextLookupMap::const_iterator mp = m_fastTextLookup.find(it->second->sourceLen); if (mp != m_fastTextLookup.end()) { mp->second->push_back(it->second); } else { std::vector<PackageText*>* vec = new std::vector<PackageText*>; vec->push_back(it->second); m_fastTextLookup.emplace(std::make_pair<int, std::vector<PackageText*>*>(it->second->sourceLen, vec)); } } m_logger->WriteLine("Package file loaded successfully"); loadingPackage.close(); } void CResourceManager::SavePackage(const char* filename) { int size = MultiByteToWideChar(CP_UTF8, NULL, filename, -1, NULL, 0); wchar_t* widefile = new wchar_t[size]; MultiByteToWideChar(CP_UTF8, NULL, filename, -1, widefile, size); this->SavePackage(widefile); delete[] widefile; } void CResourceManager::SavePackage(const std::wstring& filename) { m_modified = false; std::ofstream writer(filename, std::ios::out | std::ios::binary); if (!writer) { m_logger->WriteLine("Unable to save package file"); return; } PackageHeader header; header.magicHeader = PACKAGE_MAGIC_HEADER; header.charactersCount = 0; header.charactersOffset = 0; header.reserved1 = 0; header.reserved2 = 0; header.reserved3 = 0; header.reserved4 = 0; // Make place for header writer.write((char*) &header, sizeof(PackageHeader)); // Text header.textOffset = (UINT32) writer.tellp(); header.textCount = 0; for (std::map<UINT32, PackageText*>::const_iterator it = m_textDatabase.begin(); it != m_textDatabase.end(); it++) { UINT32 lenSource = it->second->sourceLen; UINT32 lenTranslated = it->second->translationLen; if (lenSource <= 0) { continue; } lenSource++; writer.write((char*) &it->first, 4); // id writer.write((char*) &lenSource, 4); if (lenTranslated <= 0) { lenTranslated = 0; } else { lenTranslated++; } writer.write((char*) &lenTranslated, 4); writer << it->second->source << '\x00'; if (lenTranslated > 0) { writer << it->second->translation << '\x00'; } header.textCount++; } // UI header.uiOffset = (UINT32) writer.tellp(); header.uiCount = 0; for (std::map<UINT32, PackageText*>::const_iterator it = m_uiDatabase.begin(); it != m_uiDatabase.end(); it++) { UINT32 lenSource = it->second->sourceLen; UINT32 lenTranslated = it->second->translationLen; if (lenSource <= 0) { continue; } lenSource++; writer.write((char*) &it->first, 4); writer.write((char*) &lenSource, 4); if (lenTranslated <= 0) { lenTranslated = 0; } else { lenTranslated++; } writer.write((char*) &lenTranslated, 4); writer << it->second->source << '\x00'; if (lenTranslated > 0) { writer << it->second->translation << '\x00'; } header.uiCount++; } // Images header.imageOffset = (UINT32) writer.tellp(); header.imageCount = 0; for (ImageMap::const_iterator it = m_imageDatabase.begin(); it != m_imageDatabase.end(); it++) { if (strlen(it->second->hash) != 40 || it->second->titleLen <= 0) { m_logger->WriteLine("Invalid image hash or title"); continue; } writer.write(it->second->hash, 40); UINT32 titleLen = it->second->titleLen + 1; UINT32 replacementLen = it->second->replacementLen; writer.write((char*) &titleLen, 4); writer << it->second->title << '\x00'; writer.write((char*) &it->second->width, 2); writer.write((char*) &it->second->height, 2); writer.write((char*) &it->second->flags, 4); writer.write((char*) &it->second->depth, 4); writer.write((char*) &it->second->replacementLen, 4); if (it->second->replacementLen > 0) { writer.write((char*) it->second->replacement, it->second->replacementLen); } header.imageCount++; } writer.seekp(0); writer.write((char*) &header, sizeof(PackageHeader)); writer.close(); m_logger->WriteLine("Package file successfully saved"); }
// Copyright (C) 2010 Vicente Botet // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include <boost/thread.hpp> class Worker { public: Worker() { // the thread is not-a-thread until we call start() } void start(int N) { // std::cout << "start\n"; m_Thread = boost::thread(&Worker::processQueue, this, N); // std::cout << "started\n"; } void join() { m_Thread.join(); } void processQueue(unsigned N) { float ms = N * 1e3; boost::posix_time::milliseconds workTime(ms); // std::cout << "Worker: started, will work for " // << ms << "ms" // << std::endl; // We're busy, honest! boost::this_thread::sleep(workTime); // std::cout << "Worker: completed" << std::endl; } private: boost::thread m_Thread; }; int main() { // std::cout << "main: startup" << std::endl; Worker worker; // std::cout << "main: create worker" << std::endl; worker.start(3); // std::cout << "main: waiting for thread" << std::endl; worker.join(); // std::cout << "main: done" << std::endl; return 0; }
/* Meddly: Multi-terminal and Edge-valued Decision Diagram LibrarY. Copyright (C) 2011, Iowa State University Research Foundation, Inc. This library 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 3 of the License, or (at your option) any later version. 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, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include <string.h> #include "../src/meddly.h" #include "simple_model.h" #include "kan_rs1.h" #include "kan_rs2.h" #include "kan_rs3.h" const char* kanban[] = { "X-+..............", // Tin1 "X.-+.............", // Tr1 "X.+-.............", // Tb1 "X.-.+............", // Tg1 "X.....-+.........", // Tr2 "X.....+-.........", // Tb2 "X.....-.+........", // Tg2 "X+..--+..-+......", // Ts1_23 "X.........-+.....", // Tr3 "X.........+-.....", // Tb3 "X.........-.+....", // Tg3 "X....+..-+..--+..", // Ts23_4 "X.............-+.", // Tr4 "X.............+-.", // Tb4 "X............+..-", // Tout4 "X.............-.+" // Tg4 }; // 160 states for N=1 long expected[] = { 1, 160, 4600, 58400, 454475, 2546432, 11261376, 41644800, 133865325, 384392800, 1005927208 }; using namespace MEDDLY; dd_edge buildReachsetSAT(forest* mdd, forest* mxd, int N) { // Build initial state int* initial = new int[17]; for (int i=16; i; i--) initial[i] = 0; initial[1] = initial[5] = initial[9] = initial[13] = N; dd_edge init_state(mdd); mdd->createEdge(&initial, 1, init_state); delete[] initial; // Build next-state function dd_edge nsf(mxd); buildNextStateFunction(kanban, 16, mxd, nsf); dd_edge reachable(mdd); apply(REACHABLE_STATES_DFS, init_state, nsf, reachable); return reachable; } void mark2minterm(const char* mark, int* minterm, int np) { for (; np; np--) { minterm[np] = mark[np]-48; } minterm[0] = 0; } dd_edge buildReachsetBatch(int b, forest* mdd, const char* rs[], long states) { int** batch = new int*[b]; for (int i=0; i<b; i++) { batch[i] = new int[17]; } dd_edge reachable(mdd); int i = 0; for (long s=0; s<states; s++) { if (i>=b) { dd_edge tmp(mdd); mdd->createEdge(batch, b, tmp); reachable += tmp; i = 0; } mark2minterm(rs[s]-1, batch[i], 16); i++; } if (i) { dd_edge tmp(mdd); mdd->createEdge(batch, i, tmp); reachable += tmp; } // cleanup the batch for (int i=0; i<b; i++) { delete[] batch[i]; } delete[] batch; return reachable; } bool checkRS(int N, const char* rs[]) { bool ok = true; const int batches[] = { 1000, 100, 10, 1, 0 }; int sizes[16]; for (int i=15; i>=0; i--) sizes[i] = N+1; domain* d = createDomainBottomUp(sizes, 16); forest* mdd = d->createForest(0, forest::BOOLEAN, forest::MULTI_TERMINAL); forest* mxd = d->createForest(1, forest::BOOLEAN, forest::MULTI_TERMINAL); dd_edge reachable = buildReachsetSAT(mdd, mxd, N); for (int b=0; batches[b]; b++) { printf("\tBuilding %ld markings by hand, %d at a time\n", expected[N], batches[b]); fflush(stdout); dd_edge brs = buildReachsetBatch(batches[b], mdd, rs, expected[N]); if (brs != reachable) { printf("\t\tError, didn't match\n"); ok = false; break; } } destroyDomain(d); return ok; } int main() { MEDDLY::initialize(); printf("Checking Kanban reachability set, N=1\n"); if (!checkRS(1, kanban_rs1)) return 1; printf("Checking Kanban reachability set, N=2\n"); if (!checkRS(2, kanban_rs2)) return 1; printf("Checking Kanban reachability set, N=3\n"); if (!checkRS(3, kanban_rs3)) return 1; MEDDLY::cleanup(); printf("Done\n"); return 0; }
#ifndef SK_VULKAN #define SK_VULKAN #endif #include "include/gpu/GrBackendDrawableInfo.h" #include "include/gpu/GrBackendSurface.h" #include "include/gpu/GrDirectContext.h" #include "include/gpu/vk/GrVkVulkan.h" #include "include/gpu/vk/GrVkTypes.h" #include "include/gpu/vk/GrVkBackendContext.h" #include "include/gpu/vk/GrVkExtensions.h" // Additional types not yet referenced. extern "C" void C_GrVkTypes(GrVkSurfaceInfo *) {}; extern "C" void C_GrBackendFormat_ConstructVk(GrBackendFormat* uninitialized, VkFormat format, bool willUseDRMFormatModifiers) { new(uninitialized)GrBackendFormat(GrBackendFormat::MakeVk(format, willUseDRMFormatModifiers)); } extern "C" void C_GrBackendFormat_ConstructVk2(GrBackendFormat* uninitialized, const GrVkYcbcrConversionInfo* ycbcrInfo, bool willUseDRMFormatModifiers) { new(uninitialized)GrBackendFormat(GrBackendFormat::MakeVk(*ycbcrInfo, willUseDRMFormatModifiers)); } extern "C" void C_GrBackendTexture_ConstructVk(GrBackendTexture* uninitialized, int width, int height, const GrVkImageInfo* vkInfo) { new(uninitialized)GrBackendTexture(width, height, *vkInfo); } extern "C" void C_GrBackendRenderTarget_ConstructVk(GrBackendRenderTarget* uninitialized, int width, int height, int sampleCnt, const GrVkImageInfo* vkInfo) { new(uninitialized)GrBackendRenderTarget(width, height, sampleCnt, *vkInfo); } extern "C" bool C_GrBackendDrawableInfo_getVkDrawableInfo(const GrBackendDrawableInfo* self, GrVkDrawableInfo* info) { return self->getVkDrawableInfo(info); } extern "C" void C_GPU_VK_Types(GrVkExtensionFlags *, GrVkFeatureFlags *, VkBuffer *) {} // The GrVkBackendContext struct binding's length is too short // because of the std::function that is used in it. // TODO: verify if this is actually true for the latest bindings (it doesn't seem so, because all skia-bindings testcases work and // GrVkBackendContext seems to be generated). typedef PFN_vkVoidFunction (*GetProcFn)(const char* name, VkInstance instance, VkDevice device); typedef const void* (*GetProcFnVoidPtr)(const char* name, VkInstance instance, VkDevice device); extern "C" void *C_GrVkBackendContext_New( void *instance, void *physicalDevice, void *device, void *queue, uint32_t graphicsQueueIndex, /* PFN_vkVoidFunction makes us trouble on the Rust side */ GetProcFnVoidPtr getProc, const char *const *instanceExtensions, size_t instanceExtensionCount, const char *const *deviceExtensions, size_t deviceExtensionCount) { auto vkInstance = static_cast<VkInstance>(instance); auto vkPhysicalDevice = static_cast<VkPhysicalDevice>(physicalDevice); auto vkDevice = static_cast<VkDevice>(device); auto vkGetProc = *(reinterpret_cast<GetProcFn *>(&getProc)); auto &extensions = *new GrVkExtensions(); extensions.init(vkGetProc, vkInstance, vkPhysicalDevice, instanceExtensionCount, instanceExtensions, deviceExtensionCount, deviceExtensions); auto &context = *new GrVkBackendContext(); context.fInstance = vkInstance; context.fPhysicalDevice = vkPhysicalDevice; context.fDevice = vkDevice; context.fQueue = static_cast<VkQueue>(queue); context.fGraphicsQueueIndex = graphicsQueueIndex; context.fVkExtensions = &extensions; context.fGetProc = vkGetProc; return &context; } extern "C" void C_GrVkBackendContext_Delete(void* vkBackendContext) { auto bc = static_cast<GrVkBackendContext*>(vkBackendContext); if (bc) { delete bc->fVkExtensions; } delete bc; } extern "C" void C_GrVkBackendContext_setProtectedContext(GrVkBackendContext *self, GrProtected protectedContext) { self->fProtectedContext = protectedContext; } extern "C" void C_GrVkBackendContext_setMaxAPIVersion(GrVkBackendContext *self, uint32_t maxAPIVersion) { self->fMaxAPIVersion = maxAPIVersion; } extern "C" GrDirectContext* C_GrDirectContext_MakeVulkan( const GrVkBackendContext* vkBackendContext, const GrContextOptions* options) { if (options) { return GrDirectContext::MakeVulkan(*vkBackendContext, *options).release(); } return GrDirectContext::MakeVulkan(*vkBackendContext).release(); } // // GrVkTypes.h // extern "C" bool C_GrVkAlloc_Equals(const GrVkAlloc* lhs, const GrVkAlloc* rhs) { return *lhs == *rhs; } extern "C" bool C_GrVkYcbcrConversionInfo_Equals(const GrVkYcbcrConversionInfo* lhs, const GrVkYcbcrConversionInfo* rhs) { return *lhs == *rhs; } // // gpu/GrBackendSurfaceMutableState.h // extern "C" void C_GrBackendSurfaceMutableState_ConstructVK(GrBackendSurfaceMutableState* uninitialized, VkImageLayout layout, uint32_t queueFamilyIndex) { new(uninitialized)GrBackendSurfaceMutableState(layout, queueFamilyIndex); }
#include <Common/Strategy/strategybase.h> #include <Common/config.h> #include <Common/Time/timeutil.h> #include <Common/Order/ordermanager.h> namespace EliteQuant { extern std::atomic<bool> gShutdown; StrategyBase::StrategyBase() { } StrategyBase::~StrategyBase() { } void StrategyBase::initialize() { initialized = true; } void StrategyBase::reset() { } void StrategyBase::teardown() { initialized = false; } // ************ Incoming Message Handers ********************// // ************ End Incoming Message Handers ********************// // ************ Outgoing Methods ********************// void StrategyBase::SendOrder(std::shared_ptr<Order> o) { // TODO: send o|MKT|SPY STK SMART /*lock_guard<mutex> g(oid_mtx); o->createTime = time(nullptr); o->orderStatus = OrderStatus::OS_NewBorn; o->orderId = m_orderId; // increase order id m_orderId++; */ //OrderManager::instance().trackOrder(o); TODO: send order through message queue; } void StrategyBase::SendOrderCancel(long oid) { // TODO: put it into order process queue string msg = CConfig::instance().cancel_order_msg + SERIALIZATION_SEPARATOR + std::to_string(oid); //sendmq(msg); } void StrategyBase::SendSubscriptionRequest() { } void StrategyBase::SendHistoricalBarRequest() { } void StrategyBase::SendGeneralInformation() { } void StrategyBase::SendLog() { } // ************ End Outgoing Methods ********************// }
#pragma region template 2.4 #include <bits/stdc++.h> using namespace std; template <typename T> using pq_asc = priority_queue<T, vector<T>, greater<T>>; typedef long long ll; typedef vector<ll> vi; typedef vector<vi> vvi; typedef pair<ll, ll> ii; typedef vector<ii> vii; typedef vector<string> vs; #define REP(i, n) for (ll i = 0; i < (n); ++i) #define REP1(i, n) for (ll i = 1; i <= (n); ++i) #define FOR(i, a) for (auto &i : a) #define CH(f, x, y) x = f(x, y) #define IN(T, x) \ T x; \ cin >> x; #define AIN(T, a, n) \ vector<T> a(n); \ FOR(i, a) \ cin >> i; #define A2IN(T1, a, T2, b, n) \ vector<T1> a(n); \ vector<T2> b(n); \ REP(i, n) \ cin >> a[i] >> b[i]; #define OUT(x) cout << (x) << endl; #define FOUT(x) cout << fixed << setprecision(15) << (x) << endl; #define ALL(a) (a).begin(), (a).end() #define SORT(a) sort(ALL(a)) #define RSORT(a) \ SORT(a); \ reverse(ALL(a)) #define DUMP(x) cout << #x << " = " << (x) << endl; #define DUMPA(a) \ cout << #a << " = {"; \ JOUT(ALL(a), ", ", cout) << "}" << endl; template <typename T> ostream &JOUT(T s, T e, string sep = " ", ostream &os = cout) { if (s != e) { os << *s; ++s; } while (s != e) { os << sep << *s; ++s; } return os; } ostream &YES(bool cond, string yes = "Yes", string no = "No", ostream &os = cout) { if (cond) { os << yes << endl; } else { os << no << endl; } return os; } template <typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &p) { os << '(' << p.first << ", " << p.second << ')'; return os; } template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os << '['; JOUT(ALL(v), ", ", os) << ']'; return os; } const ll INF = 1e18; const ll MOD = 1e9 + 7; #pragma endregion template int main() { IN(string, S); ll ans; if (S == "RRR") { ans = 3; } else if (S == "RRS" or S == "SRR") { ans = 2; } else if (S == "SSS") { ans = 0; } else { ans = 1; } OUT(ans); }
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2012 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 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. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``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 THE INTEL OR ITS 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. END_LEGAL */ // <ORIGINAL-AUTHOR>: Greg Lueck // <COMPONENT>: barecrt // <FILE-TYPE>: component public header #ifndef BARECRT_PROCESS_HPP #define BARECRT_PROCESS_HPP #include "fund.hpp" #include "barecrt/time.hpp" #include "barecrt/types.hpp" #if defined(FUND_HOST_IA32_LINUX) # include "barecrt/linux-ia32/resource.hpp" #elif defined(FUND_HOST_INTEL64_LINUX) # include "barecrt/linux-intel64/resource.hpp" #elif defined(FUND_HOST_IA64_LINUX) # include "barecrt/linux-ia64/resource.hpp" #elif defined(FUND_HOST_IA32_MAC) # include "barecrt/mac-ia32/resource.hpp" #elif defined(FUND_HOST_INTEL64_MAC) # include "barecrt/mac-intel64/resource.hpp" #elif defined(FUND_HOST_INTEL64_BSD) # include "barecrt/bsd-intel64/resource.hpp" #else # error "Must define O/S and architecture" #endif namespace BARECRT { /*! * Get the caller's process ID. * * @param[out] pid Receives the ID. * * @return 0 on success, else a kernel error number. */ ECODE GetPid(PID *pid); /*! * Get the caller's real user ID. * * @param[out] uid Receives the ID. * * @return 0 on success, else a kernel error number. */ ECODE GetUid(UID *pid); /*! * Get the caller's thread ID. * * @param[out] tid Receives the ID. * * @return 0 on success, else a kernel error number. */ ECODE GetTid(PID *tid); /*! * Get a resource limit for the calling process. * * @param[in] resource The resource limit to get. * @param[out] limit On success, receives the limit. * * @return 0 on success, else a kernel error number. */ ECODE GetRLimit(RESOURCE resource, RLIMIT *limit); /*! * Set a resource limit for the calling process. * * @param[in] resource The resource limit to set. * @param[in] limit The limit. * * @return 0 on success, else a kernel error number. */ ECODE SetRLimit(RESOURCE resource, const RLIMIT *limit); /*! * Yield the processor. * * @return 0 on success, else a kernel error number. */ ECODE Yield(); /*! * Get the current wall-clock time since some arbitrary reference point * that occured at (or before) the start of the calling process. * * @param[out] timeval Receives the current time. * * @return 0 on success, else a kernel error number. */ ECODE GetTime(TIMEVAL *timeval); } // namespace #endif // file guard
#include "pch.h" #include "VideoRenderer.h" #include "Common\DirectXHelper.h" #include "Windows.Graphics.DirectX.Direct3D11.interop.h" #include "AppView.h" using namespace _360VideoPlayback; using namespace concurrency; using namespace DirectX; using namespace Microsoft::WRL; using namespace std::placeholders; using namespace Windows::Foundation; using namespace Windows::Foundation::Numerics; using namespace Windows::Graphics::DirectX::Direct3D11; using namespace Windows::Media::Core; using namespace Windows::Media::Playback; using namespace Windows::UI::Input::Spatial; // Loads vertex and pixel shaders from files and instantiates the cube geometry. VideoRenderer::VideoRenderer() { m_deviceResources = _360VideoPlaybackMain::GetDeviceResources(); const CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelConstantBuffer), D3D11_BIND_CONSTANT_BUFFER); DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateBuffer( &constantBufferDesc, nullptr, &m_modelConstantBuffer)); } // Called once per frame. void VideoRenderer::Update(const DX::StepTimer& timer) { float3 scale = 10.0f; const XMMATRIX modelScale = XMMatrixScalingFromVector(XMLoadFloat3(&scale)); const XMMATRIX localTransform = modelScale; XMStoreFloat4x4(&m_modelConstantBufferData.model, XMMatrixTranspose(localTransform)); } // Renders one frame using the vertex and pixel shaders. // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3:: // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature, // a pass-through geometry shader is also used to set the render // target array index. void VideoRenderer::Render() { critical_section::scoped_lock lock(m_critical); // Loading is asynchronous. Resources must be created before drawing can occur. if (!m_loadingComplete) { return; } // Use the D3D device context to update Direct3D device-based resources. const auto context = m_deviceResources->GetD3DDeviceContext(); // Update the model transform buffer for the hologram. context->UpdateSubresource( m_modelConstantBuffer.Get(), 0, nullptr, &m_modelConstantBufferData, 0, 0 ); // Each vertex is one instance of the VertexPositionColor struct. const UINT stride = sizeof(VertexPositionTexture); const UINT offset = 0; context->IASetVertexBuffers( 0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset ); context->IASetIndexBuffer( m_indexBuffer.Get(), DXGI_FORMAT_R16_UINT, // Each index is one 16-bit unsigned integer (short). 0 ); context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context->IASetInputLayout(m_inputLayout.Get()); // Attach the vertex shader. context->VSSetShader( m_vertexShader.Get(), nullptr, 0 ); // Apply the model constant buffer to the vertex shader. context->VSSetConstantBuffers( 0, 1, m_modelConstantBuffer.GetAddressOf() ); if (!m_usingVprtShaders) { // On devices that do not support the D3D11_FEATURE_D3D11_OPTIONS3:: // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature, // a pass-through geometry shader is used to set the render target // array index. context->GSSetShader( m_geometryShader.Get(), nullptr, 0 ); } // Attach the pixel shader. context->PSSetShader( m_pixelShader.Get(), nullptr, 0 ); // Set the Texture Shader resource and samplers context->PSSetShaderResources(0, 1, m_textureView.GetAddressOf()); context->PSSetSamplers( 0, 1, m_quadTextureSamplerState.GetAddressOf() ); // Draw the objects. context->DrawIndexedInstanced( m_indexCount, // Index count per instance. 2, // Instance count. 0, // Start index location. 0, // Base vertex location. 0 // Start instance location. ); } void VideoRenderer::CreateDeviceDependentResources() { m_usingVprtShaders = m_deviceResources->GetDeviceSupportsVprt(); // Create the Texture, ShaderResource and Sampler state DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateTexture2D( &CD3D11_TEXTURE2D_DESC( DXGI_FORMAT_R8G8B8A8_UNORM, AppView::GetMediaPlayer()->PlaybackSession->NaturalVideoWidth, // Width AppView::GetMediaPlayer()->PlaybackSession->NaturalVideoHeight, // Height 1, // MipLevels 1, // ArraySize D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET ), nullptr, &m_texture ) ); DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateShaderResourceView( m_texture.Get(), nullptr, &m_textureView ) ); D3D11_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(D3D11_SAMPLER_DESC)); desc.Filter = D3D11_FILTER_ANISOTROPIC; desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP; desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP; desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; desc.MaxAnisotropy = 3; desc.MinLOD = 0; desc.MaxLOD = 3; desc.MipLODBias = 0.f; desc.BorderColor[0] = 0.f; desc.BorderColor[1] = 0.f; desc.BorderColor[2] = 0.f; desc.BorderColor[3] = 0.f; desc.ComparisonFunc = D3D11_COMPARISON_NEVER; DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateSamplerState( &desc, &m_quadTextureSamplerState ) ); CreateD3D11Surface(); LoadShaders(); } void VideoRenderer::LoadShaders() { // On devices that do support the D3D11_FEATURE_D3D11_OPTIONS3:: // VPAndRTArrayIndexFromAnyShaderFeedingRasterizer optional feature // we can avoid using a pass-through geometry shader to set the render // target array index, thus avoiding any overhead that would be // incurred by setting the geometry shader stage. std::wstring vertexShaderFileName = m_usingVprtShaders ? L"ms-appx:///VprtVertexShader.cso" : L"ms-appx:///VertexShader.cso"; // Load shaders asynchronously. task<std::vector<byte>> loadVSTask = DX::ReadDataAsync(vertexShaderFileName); task<std::vector<byte>> loadPSTask = DX::ReadDataAsync(L"ms-appx:///PixelShader.cso"); task<std::vector<byte>> loadGSTask; if (!m_usingVprtShaders) { // Load the pass-through geometry shader. loadGSTask = DX::ReadDataAsync(L"ms-appx:///GeometryShader.cso"); } // After the vertex shader file is loaded, create the shader and input layout. task<void> createVSTask = loadVSTask.then([this](const std::vector<byte>& fileData) { DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateVertexShader( fileData.data(), fileData.size(), nullptr, &m_vertexShader ) ); constexpr std::array<D3D11_INPUT_ELEMENT_DESC, 2> vertexDesc = { { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 1, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, } }; DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateInputLayout( vertexDesc.data(), static_cast<UINT>(vertexDesc.size()), fileData.data(), static_cast<UINT>(fileData.size()), &m_inputLayout ) ); }); // After the pixel shader file is loaded, create the shader and constant buffer. task<void> createPSTask = loadPSTask.then([this](const std::vector<byte>& fileData) { DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreatePixelShader( fileData.data(), fileData.size(), nullptr, &m_pixelShader ) ); }); task<void> createGSTask; if (!m_usingVprtShaders) { // After the pass-through geometry shader file is loaded, create the shader. createGSTask = loadGSTask.then([this](const std::vector<byte>& fileData) { DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateGeometryShader( fileData.data(), fileData.size(), nullptr, &m_geometryShader ) ); }); } // Once all shaders are loaded, create the mesh. task<void> shaderTaskGroup = m_usingVprtShaders ? (createPSTask && createVSTask) : (createPSTask && createVSTask && createGSTask); task<void> createSphereTask = shaderTaskGroup.then([this]() { ComputeSphere(16, true); }); // Once the Sphere is created, the object is ready to be rendered. createSphereTask.then([this]() { m_loadingComplete = true; }); } void VideoRenderer::ReleaseDeviceDependentResources() { m_loadingComplete = false; m_usingVprtShaders = false; m_vertexShader.Reset(); m_inputLayout.Reset(); m_pixelShader.Reset(); m_geometryShader.Reset(); m_modelConstantBuffer.Reset(); m_vertexBuffer.Reset(); m_indexBuffer.Reset(); if (m_videoFrameAvailToken.Value) { if (AppView::GetMediaPlayer() != nullptr) { AppView::GetMediaPlayer()->VideoFrameAvailable -= m_videoFrameAvailToken; } } } void VideoRenderer::ComputeSphere(unsigned short tessellation, bool invertn) { if (tessellation < 3) throw std::out_of_range("tesselation parameter out of range"); unsigned short verticalSegments = tessellation; unsigned short horizontalSegments = tessellation * 2; const unsigned short vertCount = (verticalSegments + 1) * (horizontalSegments + 1); unsigned short indexCount = (verticalSegments) * (horizontalSegments + 1) * 6; float radius = 0.5f; // Diameter of the default Sphere will always be 1 to stay aligned std::vector<VertexPositionTexture> sphereVertices; for (unsigned short i = 0; i <= verticalSegments; i++) { float v = 1 - (float)i / verticalSegments; float latitude = (i * XM_PI / verticalSegments) - XM_PIDIV2; float dy, dxz; XMScalarSinCos(&dy, &dxz, latitude); // Create a single ring of vertices at this latitude. for (unsigned short j = 0; j <= horizontalSegments; j++) { float u = (float)j / horizontalSegments; float longitude = j * XM_2PI / horizontalSegments; float dx, dz; XMScalarSinCos(&dx, &dz, longitude); dx *= dxz; dz *= dxz; XMVECTOR normal = XMVectorSet(dx, dy, dz, 0) * radius; XMFLOAT3 normalFloat3; XMStoreFloat3(&normalFloat3, normal); VertexPositionTexture vert; vert.position = normalFloat3; vert.textureCoordinate = XMFLOAT2(1.0f - u, v); sphereVertices.push_back(vert); } } std::vector<unsigned short> sphereIndices; // Fill the index buffer with triangles joining each pair of latitude rings. unsigned short stride = horizontalSegments + 1; for (unsigned short i = 0; i < verticalSegments; i++) { for (unsigned short j = 0; j <= horizontalSegments; j++) { unsigned short nextI = i + 1; unsigned short nextJ = (j + 1) % stride; if (!invertn) { sphereIndices.push_back(i * stride + j); sphereIndices.push_back(nextI * stride + j); sphereIndices.push_back(i * stride + nextJ); sphereIndices.push_back(i * stride + nextJ); sphereIndices.push_back(nextI * stride + j); sphereIndices.push_back(nextI * stride + nextJ); } else { sphereIndices.push_back(nextI * stride + j); sphereIndices.push_back(i * stride + j); sphereIndices.push_back(i * stride + nextJ); sphereIndices.push_back(nextI * stride + j); sphereIndices.push_back(i * stride + nextJ); sphereIndices.push_back(nextI * stride + nextJ); } } } D3D11_SUBRESOURCE_DATA vertexBufferData = { 0 }; vertexBufferData.pSysMem = sphereVertices.data(); vertexBufferData.SysMemPitch = 0; vertexBufferData.SysMemSlicePitch = 0; const CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(VertexPositionTexture) * vertCount, D3D11_BIND_VERTEX_BUFFER); DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateBuffer( &vertexBufferDesc, &vertexBufferData, &m_vertexBuffer ) ); m_indexCount = indexCount; D3D11_SUBRESOURCE_DATA indexBufferData = { 0 }; indexBufferData.pSysMem = sphereIndices.data(); indexBufferData.SysMemPitch = 0; indexBufferData.SysMemSlicePitch = 0; CD3D11_BUFFER_DESC indexBufferDesc(sizeof(unsigned short) * indexCount, D3D11_BIND_INDEX_BUFFER); DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateBuffer( &indexBufferDesc, &indexBufferData, &m_indexBuffer ) ); } void VideoRenderer::CreateD3D11Surface() { Microsoft::WRL::ComPtr<IDXGISurface> spDXGIInterfaceAccess; DX::ThrowIfFailed(m_texture->QueryInterface(IID_PPV_ARGS(&spDXGIInterfaceAccess))); m_surface = CreateDirect3DSurface(spDXGIInterfaceAccess.Get()); m_videoFrameAvailToken = AppView::GetMediaPlayer()->VideoFrameAvailable += ref new TypedEventHandler<MediaPlayer^, Platform::Object^>( std::bind(&VideoRenderer::OnVideoFrameAvailable, this)); AppView::GetMediaPlayer()->Play(); } void VideoRenderer::OnVideoFrameAvailable() { critical_section::scoped_lock lock(m_critical); AppView::GetMediaPlayer()->CopyFrameToVideoSurface(m_surface); }