<commit_before>/**
 * @file LoaderUtils.cpp
 * @brief Utils to load Dart objects
 */

#include "DartLoader.h"
#include <dynamics/SkeletonDynamics.h>
#include <kinematics/TrfmTranslate.h>
#include <kinematics/TrfmRotateEuler.h>
#include <kinematics/TrfmRotateAxis.h>
#include <kinematics/Dof.h>
#include <kinematics/Joint.h>
#include <kinematics/Shape.h>
#include <kinematics/ShapeMesh.h>
#include <kinematics/ShapeSphere.h>
#include <kinematics/ShapeBox.h>
#include <kinematics/ShapeCylinder.h>
#include <dynamics/BodyNodeDynamics.h>
#include <iostream>

/**
 * @function add_XyzRpy
 */
void DartLoader::add_XyzRpy( kinematics::Joint* _joint,
			     double _x, double _y, double _z,
			     double _rr, double _rp, double _ry ) {

  kinematics::Transformation* trans;

  trans = new kinematics::TrfmTranslateX( new kinematics::Dof(_x) );
  _joint->addTransform( trans, false );

  trans = new kinematics::TrfmTranslateY( new kinematics::Dof(_y) );
  _joint->addTransform( trans, false );

  trans = new kinematics::TrfmTranslateZ( new kinematics::Dof(_z) );
  _joint->addTransform( trans, false );

  trans = new kinematics::TrfmRotateEulerZ(new ::kinematics::Dof(_ry ));
  _joint->addTransform(trans, false);

  trans = new kinematics::TrfmRotateEulerY(new ::kinematics::Dof( _rp ));
  _joint->addTransform(trans, false);

  trans = new kinematics::TrfmRotateEulerX(new ::kinematics::Dof( _rr ));
  _joint->addTransform(trans, false);
}

/**
 * @function add_DOF
 */
void DartLoader::add_DOF( dynamics::SkeletonDynamics* _skel,
			  kinematics::Joint* _joint,
			  double _val, double _min, double _max,
			  int _DOF_TYPE,
			  double _x, double _y, double _z  ) {

  kinematics::Transformation* trans;

  if(_DOF_TYPE == GOLEM_X) {
    trans = new kinematics::TrfmTranslateX(new kinematics::Dof(0, _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if(_DOF_TYPE == GOLEM_Y) {
    trans = new kinematics::TrfmTranslateY(new kinematics::Dof(0, _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if(_DOF_TYPE == GOLEM_Z) {
    trans = new kinematics::TrfmTranslateZ(new kinematics::Dof(0, _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if(_DOF_TYPE == GOLEM_YAW) {
    trans = new kinematics::TrfmRotateEulerZ(new kinematics::Dof(0, _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if(_DOF_TYPE == GOLEM_PITCH) {
    trans = new kinematics::TrfmRotateEulerY(new kinematics::Dof(0, _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if(_DOF_TYPE == GOLEM_ROLL) {
    trans = new kinematics::TrfmRotateEulerX(new kinematics::Dof(0,  _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if( _DOF_TYPE == GOLEM_ARBITRARY_ROTATION ) {
    Eigen::Vector3d axis; axis << _x, _y, _z;
    trans = new kinematics::TrfmRotateAxis( axis, new kinematics::Dof(0,  _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if( _DOF_TYPE == GOLEM_FLOATING ) {

    trans = new kinematics::TrfmTranslateX( new kinematics::Dof( 0, "floatingX" ), "Tfx" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

    trans = new kinematics::TrfmTranslateY( new kinematics::Dof( 0, "floatingY" ), "Tfy" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

    trans = new kinematics::TrfmTranslateZ( new kinematics::Dof( 0, "floatingZ" ), "Tfz" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

    trans = new kinematics::TrfmRotateEulerZ( new kinematics::Dof( 0, "floatingYaw" ), "Tfry" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

    trans = new kinematics::TrfmRotateEulerY( new kinematics::Dof( 0, "floatingPitch" ), "Tfrp" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

    trans = new kinematics::TrfmRotateEulerX( new kinematics::Dof( 0, "floatingRoll" ), "Tfrr" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

  }

  else {
    if(debug) std::cerr << " WATCH OUT! THIS SHOULD NOT HAPPEN, NO DOF SET" << std::endl;
  }

}

/**
 * @function add_VizShape
 */
bool  DartLoader::add_VizShape( dynamics::BodyNodeDynamics* _node,
				boost::shared_ptr<urdf::Visual> _viz,
				std::string _rootToSkelPath ) {
  // Variables to use
  kinematics::Shape* shape;
  const aiScene* model;
  urdf::Pose pose;

  // Origin
  pose = _viz->origin;

  // Type of Geometry

  //-- SPHERE
  if( _viz->geometry->type == urdf::Geometry::SPHERE ) {

    boost::shared_ptr<urdf::Sphere> sphere = boost::static_pointer_cast<urdf::Sphere>( _viz->geometry );
    shape = new kinematics::ShapeSphere( sphere->radius );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    // Set in node
    _node->setVizShape(shape);

  }

  //-- BOX
  else if( _viz->geometry->type == urdf::Geometry::BOX ) {

    boost::shared_ptr<urdf::Box> box = boost::static_pointer_cast<urdf::Box>( _viz->geometry );
    Eigen::Vector3d dim; dim<< box->dim.x, box->dim.y, box->dim.z;
    shape = new kinematics::ShapeBox( dim );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    // Set in node
    _node->setVizShape(shape);

  }

  //-- CYLINDER
  else if( _viz->geometry->type == urdf::Geometry::CYLINDER ) {

    boost::shared_ptr<urdf::Cylinder> cylinder = boost::static_pointer_cast<urdf::Cylinder>( _viz->geometry );
    shape = new kinematics::ShapeCylinder( cylinder->radius, cylinder->length );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    // Set in node
    _node->setVizShape(shape);

  }

  //-- Mesh : Save the path
  else if( _viz->geometry->type == urdf::Geometry::MESH ) {

    boost::shared_ptr<urdf::Mesh> mesh = boost::static_pointer_cast<urdf::Mesh>( _viz->geometry );
    std::string fullPath = _rootToSkelPath;
    fullPath.append( mesh->filename );

    // Load aiScene visualization
    model = kinematics::ShapeMesh::loadMesh( fullPath );

    if( model == NULL ) {
      std::cout<< "[add_VizShape] [ERROR] Not loading model "<< fullPath<<" (NULL) \n";
      return false;
    }

    // Set shape as mesh
    shape = new kinematics::ShapeMesh( Eigen::Vector3d( 1, 1, 1), model );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    if(debug) std::cerr << "[debug] Loading visual model: " << fullPath << std::endl;

    // Set in node
    _node->setVizShape(shape);

  } // end if (mesh)

  else {
    std::cout<< "[set_VizShape] No MESH, BOX, CYLINDER OR SPHERE! Exiting"<<std::endl;
    return false;
  }

  return true;
}

/**
 * @function pose2Affine3d
 */
Eigen::Affine3d DartLoader::pose2Affine3d( urdf::Pose _pose ) {

  Eigen::Affine3d transform = Eigen::Affine3d::Identity();

    // Set xyz
    Eigen::Vector3d t;
    t[0] = _pose.position.x;
    t[1] = _pose.position.y;
    t[2] = _pose.position.z;
    transform.translation() = t;

    // Set rpy
    double roll, pitch, yaw;
    _pose.rotation.getRPY( roll, pitch, yaw );
    Eigen::Matrix3d rot;
    rot  = Eigen::AngleAxisd( yaw, Eigen::Vector3d::UnitZ())* Eigen::AngleAxisd( pitch, Eigen::Vector3d::UnitY())* Eigen::AngleAxisd( roll, Eigen::Vector3d::UnitX() );
    transform.matrix().block(0,0,3,3) = rot;

    return transform;
}

/**
 * @function add_ColShape
 */
bool  DartLoader::add_ColShape( dynamics::BodyNodeDynamics* _node,
				boost::shared_ptr<urdf::Collision> _col,
				std::string _rootToSkelPath ) {

  // Variables to use
  kinematics::Shape* shape;
  const aiScene* model;
  urdf::Pose pose;

  // Origin
  pose = _col->origin;

  // Type of Geometry

  //-- Mesh : Save the path
  if( _col->geometry->type == urdf::Geometry::MESH ) {

    boost::shared_ptr<urdf::Mesh> mesh = boost::static_pointer_cast<urdf::Mesh>( _col->geometry );
    std::string fullPath = _rootToSkelPath;
    fullPath.append( mesh->filename );

    // Load aiScene visualization
    model = kinematics::ShapeMesh::loadMesh( fullPath );

    if( model == NULL ) {
      std::cout<< "[add_ColShape] [ERROR] Not loading model "<< fullPath<<" (NULL) \n";
      return false;
    }

    // Set shape as mesh
    shape = new kinematics::ShapeMesh( Eigen::Vector3d( 1, 1, 1), model );

    // Set its pose
    Eigen::Affine3d transform = Eigen::Affine3d::Identity();
    // Set xyz
    Eigen::Vector3d t;
    t[0] = pose.position.x;
    t[1] = pose.position.y;
    t[2] = pose.position.z;
    transform.translation() = t;
    // Set rpy
    double roll, pitch, yaw;
    pose.rotation.getRPY( roll, pitch, yaw );
    Eigen::Matrix3d rot;
    rot  = Eigen::AngleAxisd( yaw, Eigen::Vector3d::UnitZ())* Eigen::AngleAxisd( pitch, Eigen::Vector3d::UnitY())* Eigen::AngleAxisd( roll, Eigen::Vector3d::UnitX() );
    transform.matrix().block(0,0,3,3) = rot;

    // Set it into shape
    shape->setTransform( transform );

    if(debug) std::cerr << "[debug] Loading visual model: " << fullPath << std::endl;

    // Set in node
    _node->setColShape(shape);

  } // end if (mesh)

  else {
    std::cout<< "[set_ColShape] No MESH, BOX, CYLINDER OR SPHERE! Exiting"<<std::endl;
    return false;
  }

  return true;

}

<commit_msg>Added BOX, CYLINDER, SPHERE as parsed types for colShape<commit_after>/**
 * @file LoaderUtils.cpp
 * @brief Utils to load Dart objects
 */

#include "DartLoader.h"
#include <dynamics/SkeletonDynamics.h>
#include <kinematics/TrfmTranslate.h>
#include <kinematics/TrfmRotateEuler.h>
#include <kinematics/TrfmRotateAxis.h>
#include <kinematics/Dof.h>
#include <kinematics/Joint.h>
#include <kinematics/Shape.h>
#include <kinematics/ShapeMesh.h>
#include <kinematics/ShapeSphere.h>
#include <kinematics/ShapeBox.h>
#include <kinematics/ShapeCylinder.h>
#include <dynamics/BodyNodeDynamics.h>
#include <iostream>

/**
 * @function add_XyzRpy
 */
void DartLoader::add_XyzRpy( kinematics::Joint* _joint,
			     double _x, double _y, double _z,
			     double _rr, double _rp, double _ry ) {

  kinematics::Transformation* trans;

  trans = new kinematics::TrfmTranslateX( new kinematics::Dof(_x) );
  _joint->addTransform( trans, false );

  trans = new kinematics::TrfmTranslateY( new kinematics::Dof(_y) );
  _joint->addTransform( trans, false );

  trans = new kinematics::TrfmTranslateZ( new kinematics::Dof(_z) );
  _joint->addTransform( trans, false );

  trans = new kinematics::TrfmRotateEulerZ(new ::kinematics::Dof(_ry ));
  _joint->addTransform(trans, false);

  trans = new kinematics::TrfmRotateEulerY(new ::kinematics::Dof( _rp ));
  _joint->addTransform(trans, false);

  trans = new kinematics::TrfmRotateEulerX(new ::kinematics::Dof( _rr ));
  _joint->addTransform(trans, false);
}

/**
 * @function add_DOF
 */
void DartLoader::add_DOF( dynamics::SkeletonDynamics* _skel,
			  kinematics::Joint* _joint,
			  double _val, double _min, double _max,
			  int _DOF_TYPE,
			  double _x, double _y, double _z  ) {

  kinematics::Transformation* trans;

  if(_DOF_TYPE == GOLEM_X) {
    trans = new kinematics::TrfmTranslateX(new kinematics::Dof(0, _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if(_DOF_TYPE == GOLEM_Y) {
    trans = new kinematics::TrfmTranslateY(new kinematics::Dof(0, _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if(_DOF_TYPE == GOLEM_Z) {
    trans = new kinematics::TrfmTranslateZ(new kinematics::Dof(0, _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if(_DOF_TYPE == GOLEM_YAW) {
    trans = new kinematics::TrfmRotateEulerZ(new kinematics::Dof(0, _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if(_DOF_TYPE == GOLEM_PITCH) {
    trans = new kinematics::TrfmRotateEulerY(new kinematics::Dof(0, _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if(_DOF_TYPE == GOLEM_ROLL) {
    trans = new kinematics::TrfmRotateEulerX(new kinematics::Dof(0,  _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if( _DOF_TYPE == GOLEM_ARBITRARY_ROTATION ) {
    Eigen::Vector3d axis; axis << _x, _y, _z;
    trans = new kinematics::TrfmRotateAxis( axis, new kinematics::Dof(0,  _joint->getName() ), "T_dof");
    _joint->addTransform(trans, true);
    _joint->getDof(0)->setMin(_min);
    _joint->getDof(0)->setMax(_max);
    _skel->addTransform(trans);
  }
  else if( _DOF_TYPE == GOLEM_FLOATING ) {

    trans = new kinematics::TrfmTranslateX( new kinematics::Dof( 0, "floatingX" ), "Tfx" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

    trans = new kinematics::TrfmTranslateY( new kinematics::Dof( 0, "floatingY" ), "Tfy" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

    trans = new kinematics::TrfmTranslateZ( new kinematics::Dof( 0, "floatingZ" ), "Tfz" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

    trans = new kinematics::TrfmRotateEulerZ( new kinematics::Dof( 0, "floatingYaw" ), "Tfry" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

    trans = new kinematics::TrfmRotateEulerY( new kinematics::Dof( 0, "floatingPitch" ), "Tfrp" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

    trans = new kinematics::TrfmRotateEulerX( new kinematics::Dof( 0, "floatingRoll" ), "Tfrr" );
    _joint->addTransform( trans, true );
    _skel->addTransform( trans );

  }

  else {
    if(debug) std::cerr << " WATCH OUT! THIS SHOULD NOT HAPPEN, NO DOF SET" << std::endl;
  }

}

/**
 * @function add_VizShape
 */
bool  DartLoader::add_VizShape( dynamics::BodyNodeDynamics* _node,
				boost::shared_ptr<urdf::Visual> _viz,
				std::string _rootToSkelPath ) {
  // Variables to use
  kinematics::Shape* shape;
  const aiScene* model;
  urdf::Pose pose;

  // Origin
  pose = _viz->origin;

  // Type of Geometry

  //-- SPHERE
  if( _viz->geometry->type == urdf::Geometry::SPHERE ) {

    boost::shared_ptr<urdf::Sphere> sphere = boost::static_pointer_cast<urdf::Sphere>( _viz->geometry );
    shape = new kinematics::ShapeSphere( sphere->radius );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    // Set in node
    _node->setVizShape(shape);

  }

  //-- BOX
  else if( _viz->geometry->type == urdf::Geometry::BOX ) {

    boost::shared_ptr<urdf::Box> box = boost::static_pointer_cast<urdf::Box>( _viz->geometry );
    Eigen::Vector3d dim; dim<< box->dim.x, box->dim.y, box->dim.z;
    shape = new kinematics::ShapeBox( dim );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    // Set in node
    _node->setVizShape(shape);

  }

  //-- CYLINDER
  else if( _viz->geometry->type == urdf::Geometry::CYLINDER ) {

    boost::shared_ptr<urdf::Cylinder> cylinder = boost::static_pointer_cast<urdf::Cylinder>( _viz->geometry );
    shape = new kinematics::ShapeCylinder( cylinder->radius, cylinder->length );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    // Set in node
    _node->setVizShape(shape);

  }

  //-- Mesh : Save the path
  else if( _viz->geometry->type == urdf::Geometry::MESH ) {

    boost::shared_ptr<urdf::Mesh> mesh = boost::static_pointer_cast<urdf::Mesh>( _viz->geometry );
    std::string fullPath = _rootToSkelPath;
    fullPath.append( mesh->filename );

    // Load aiScene visualization
    model = kinematics::ShapeMesh::loadMesh( fullPath );

    if( model == NULL ) {
      std::cout<< "[add_VizShape] [ERROR] Not loading model "<< fullPath<<" (NULL) \n";
      return false;
    }

    // Set shape as mesh
    shape = new kinematics::ShapeMesh( Eigen::Vector3d( 1, 1, 1), model );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    if(debug) std::cerr << "[debug] Loading visual model: " << fullPath << std::endl;

    // Set in node
    _node->setVizShape(shape);

  } // end if (mesh)

  else {
    std::cout<< "[set_VizShape] No MESH, BOX, CYLINDER OR SPHERE! Exiting"<<std::endl;
    return false;
  }

  return true;
}

/**
 * @function add_ColShape
 */
bool  DartLoader::add_ColShape( dynamics::BodyNodeDynamics* _node,
				boost::shared_ptr<urdf::Collision> _col,
				std::string _rootToSkelPath ) {

  // Variables to use
  kinematics::Shape* shape;
  const aiScene* model;
  urdf::Pose pose;

  // Origin
  pose = _col->origin;

  // Type of Geometry

  //-- SPHERE
  if( _col->geometry->type == urdf::Geometry::SPHERE ) {

    boost::shared_ptr<urdf::Sphere> sphere = boost::static_pointer_cast<urdf::Sphere>( _col->geometry );
    shape = new kinematics::ShapeSphere( sphere->radius );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    // Set in node
    _node->setColShape(shape);

  }

  //-- BOX
  else if( _col->geometry->type == urdf::Geometry::BOX ) {

    boost::shared_ptr<urdf::Box> box = boost::static_pointer_cast<urdf::Box>( _col->geometry );
    Eigen::Vector3d dim; dim<< box->dim.x, box->dim.y, box->dim.z;
    shape = new kinematics::ShapeBox( dim );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    // Set in node
    _node->setColShape(shape);

  }

  //-- CYLINDER
  else if( _col->geometry->type == urdf::Geometry::CYLINDER ) {

    boost::shared_ptr<urdf::Cylinder> cylinder = boost::static_pointer_cast<urdf::Cylinder>( _col->geometry );
    shape = new kinematics::ShapeCylinder( cylinder->radius, cylinder->length );

    // Set its pose
    Eigen::Affine3d transform;
    transform = pose2Affine3d( pose );

    // Set it into shape
    shape->setTransform( transform );

    // Set in node
    _node->setColShape(shape);

  }

  //-- Mesh
  if( _col->geometry->type == urdf::Geometry::MESH ) {

    boost::shared_ptr<urdf::Mesh> mesh = boost::static_pointer_cast<urdf::Mesh>( _col->geometry );
    std::string fullPath = _rootToSkelPath;
    fullPath.append( mesh->filename );

    // Load aiScene visualization
    model = kinematics::ShapeMesh::loadMesh( fullPath );

    if( model == NULL ) {
      std::cout<< "[add_ColShape] [ERROR] Not loading model "<< fullPath<<" (NULL) \n";
      return false;
    }

    // Set shape as mesh
    shape = new kinematics::ShapeMesh( Eigen::Vector3d( 1, 1, 1), model );

    // Set its pose
    Eigen::Affine3d transform = Eigen::Affine3d::Identity();
    // Set xyz
    Eigen::Vector3d t;
    t[0] = pose.position.x;
    t[1] = pose.position.y;
    t[2] = pose.position.z;
    transform.translation() = t;
    // Set rpy
    double roll, pitch, yaw;
    pose.rotation.getRPY( roll, pitch, yaw );
    Eigen::Matrix3d rot;
    rot  = Eigen::AngleAxisd( yaw, Eigen::Vector3d::UnitZ())* Eigen::AngleAxisd( pitch, Eigen::Vector3d::UnitY())* Eigen::AngleAxisd( roll, Eigen::Vector3d::UnitX() );
    transform.matrix().block(0,0,3,3) = rot;

    // Set it into shape
    shape->setTransform( transform );

    if(debug) std::cerr << "[debug] Loading visual model: " << fullPath << std::endl;

    // Set in node
    _node->setColShape(shape);

  } // end if (mesh)

  else {
    std::cout<< "[set_ColShape] No MESH, BOX, CYLINDER OR SPHERE! Exiting"<<std::endl;
    return false;
  }

  return true;

}

/**
 * @function pose2Affine3d
 */
Eigen::Affine3d DartLoader::pose2Affine3d( urdf::Pose _pose ) {

  Eigen::Affine3d transform = Eigen::Affine3d::Identity();

    // Set xyz
    Eigen::Vector3d t;
    t[0] = _pose.position.x;
    t[1] = _pose.position.y;
    t[2] = _pose.position.z;
    transform.translation() = t;

    // Set rpy
    double roll, pitch, yaw;
    _pose.rotation.getRPY( roll, pitch, yaw );
    Eigen::Matrix3d rot;
    rot  = Eigen::AngleAxisd( yaw, Eigen::Vector3d::UnitZ())* Eigen::AngleAxisd( pitch, Eigen::Vector3d::UnitY())* Eigen::AngleAxisd( roll, Eigen::Vector3d::UnitX() );
    transform.matrix().block(0,0,3,3) = rot;

    return transform;
}
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* 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 "VirtualMachinePoolXML.h"
#include <stdexcept>

int VirtualMachinePoolXML::set_up()
{
    ostringstream   oss;
    int             rc;

    rc = PoolXML::set_up();

    if ( rc == 0 )
    {
        oss.str("");
        oss << "Pending and rescheduling VMs:" << endl;

        map<int,ObjectXML*>::iterator it;

        for (it=objects.begin();it!=objects.end();it++)
        {
            oss << " " << it->first;
        }

        NebulaLog::log("VM",Log::DEBUG,oss);
    }

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void VirtualMachinePoolXML::add_object(xmlNodePtr node)
{
    if ( node == 0 || node->children == 0 || node->children->next==0 )
    {
        NebulaLog::log("VM",Log::ERROR,
                       "XML Node does not represent a valid Virtual Machine");
        return;
    }

    VirtualMachineXML* vm = new VirtualMachineXML(node);

    objects.insert(pair<int,ObjectXML*>(vm->get_oid(),vm));
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePoolXML::load_info(xmlrpc_c::value &result)
{
    try
    {
        client->call(client->get_endpoint(),        // serverUrl
                     "one.vmpool.info",             // methodName
                     "siiii",                       // arguments format
                     &result,                       // resultP
                     client->get_oneauth().c_str(), // auth string
                     -2,                            // VM from all users
                     -1,                            // start_id (none)
                     -1,                            // end_id (none)
                     -1);                           // not in DONE state
        return 0;
    }
    catch (exception const& e)
    {
        ostringstream   oss;
        oss << "Exception raised: " << e.what();

        NebulaLog::log("VM", Log::ERROR, oss);

        return -1;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePoolXML::dispatch(int vid, int hid, bool resched) const
{
    ostringstream               oss;
    xmlrpc_c::value             deploy_result;

    if (resched == true)
    {
        oss << "Rescheduling ";
    }
    else
    {
        oss << "Dispatching ";
    }

    oss << "virtual machine " << vid << " to host " << hid;

    NebulaLog::log("VM",Log::INFO,oss);

    try
    {
        //TODO Get live migration from config file
        if (resched == true)
        {
            client->call(client->get_endpoint(),           // serverUrl
                         "one.vm.migrate",                 // methodName
                         "siib",                           // arguments format
                         &deploy_result,                   // resultP
                         client->get_oneauth().c_str(),    // argument 0 (AUTH)
                         vid,                              // argument 1 (VM)
                         hid,                              // argument 2 (HOST)
                         live_resched);                    // argument 3 (LIVE)
        }
        else
        {
            client->call(client->get_endpoint(),           // serverUrl
                         "one.vm.deploy",                  // methodName
                         "sii",                            // arguments format
                         &deploy_result,                   // resultP
                         client->get_oneauth().c_str(),    // argument 0 (AUTH)
                         vid,                              // argument 1 (VM)
                         hid);                             // argument 2 (HOST)
        }
    }
    catch (exception const& e)
    {
        oss.str("");
        oss << "Exception raised: " << e.what() << '\n';

        NebulaLog::log("VM",Log::ERROR,oss);

        return -1;
    }

    // See how ONE handled the deployment

    vector<xmlrpc_c::value> values =
                    xmlrpc_c::value_array(deploy_result).vectorValueValue();

    bool   success = xmlrpc_c::value_boolean( values[0] );

    if ( !success )
    {
        string message = xmlrpc_c::value_string(  values[1] );

        oss.str("");
        oss << "Error deploying virtual machine " << vid
            << " to HID: " << hid << ". Reason: " << message;

        NebulaLog::log("VM",Log::ERROR,oss);

        return -1;
    }

    return 0;
}
<commit_msg>Feature #1338: Update scheduler deploy and migrate xml-rpc calls<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2012, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* 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 "VirtualMachinePoolXML.h"
#include <stdexcept>

int VirtualMachinePoolXML::set_up()
{
    ostringstream   oss;
    int             rc;

    rc = PoolXML::set_up();

    if ( rc == 0 )
    {
        oss.str("");
        oss << "Pending and rescheduling VMs:" << endl;

        map<int,ObjectXML*>::iterator it;

        for (it=objects.begin();it!=objects.end();it++)
        {
            oss << " " << it->first;
        }

        NebulaLog::log("VM",Log::DEBUG,oss);
    }

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void VirtualMachinePoolXML::add_object(xmlNodePtr node)
{
    if ( node == 0 || node->children == 0 || node->children->next==0 )
    {
        NebulaLog::log("VM",Log::ERROR,
                       "XML Node does not represent a valid Virtual Machine");
        return;
    }

    VirtualMachineXML* vm = new VirtualMachineXML(node);

    objects.insert(pair<int,ObjectXML*>(vm->get_oid(),vm));
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePoolXML::load_info(xmlrpc_c::value &result)
{
    try
    {
        client->call(client->get_endpoint(),        // serverUrl
                     "one.vmpool.info",             // methodName
                     "siiii",                       // arguments format
                     &result,                       // resultP
                     client->get_oneauth().c_str(), // auth string
                     -2,                            // VM from all users
                     -1,                            // start_id (none)
                     -1,                            // end_id (none)
                     -1);                           // not in DONE state
        return 0;
    }
    catch (exception const& e)
    {
        ostringstream   oss;
        oss << "Exception raised: " << e.what();

        NebulaLog::log("VM", Log::ERROR, oss);

        return -1;
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int VirtualMachinePoolXML::dispatch(int vid, int hid, bool resched) const
{
    ostringstream               oss;
    xmlrpc_c::value             deploy_result;

    if (resched == true)
    {
        oss << "Rescheduling ";
    }
    else
    {
        oss << "Dispatching ";
    }

    oss << "virtual machine " << vid << " to host " << hid;

    NebulaLog::log("VM",Log::INFO,oss);

    try
    {
        if (resched == true)
        {
            client->call(client->get_endpoint(),           // serverUrl
                         "one.vm.migrate",                 // methodName
                         "siibb",                          // arguments format
                         &deploy_result,                   // resultP
                         client->get_oneauth().c_str(),    // argument 0 (AUTH)
                         vid,                              // argument 1 (VM)
                         hid,                              // argument 2 (HOST)
                         live_resched,                     // argument 3 (LIVE)
                         false);                           // argument 4 (ENFORCE)
        }
        else
        {
            client->call(client->get_endpoint(),           // serverUrl
                         "one.vm.deploy",                  // methodName
                         "siib",                           // arguments format
                         &deploy_result,                   // resultP
                         client->get_oneauth().c_str(),    // argument 0 (AUTH)
                         vid,                              // argument 1 (VM)
                         hid,                              // argument 2 (HOST)
                         false);                           // argument 3 (ENFORCE)
        }
    }
    catch (exception const& e)
    {
        oss.str("");
        oss << "Exception raised: " << e.what() << '\n';

        NebulaLog::log("VM",Log::ERROR,oss);

        return -1;
    }

    // See how ONE handled the deployment

    vector<xmlrpc_c::value> values =
                    xmlrpc_c::value_array(deploy_result).vectorValueValue();

    bool   success = xmlrpc_c::value_boolean( values[0] );

    if ( !success )
    {
        string message = xmlrpc_c::value_string(  values[1] );

        oss.str("");
        oss << "Error deploying virtual machine " << vid
            << " to HID: " << hid << ". Reason: " << message;

        NebulaLog::log("VM",Log::ERROR,oss);

        return -1;
    }

    return 0;
}
<|endoftext|>


<commit_before>#ifndef __STAN__MCMC__BASE__LEAPFROG__BETA__
#define __STAN__MCMC__BASE__LEAPFROG__BETA__

#include <iostream>
#include <iomanip>
#include <stan/mcmc/hmc/integrators/base_integrator.hpp>

namespace stan {

  namespace mcmc {

    template <typename H, typename P>
    class base_leapfrog: public base_integrator<H, P> {

    public:

      void evolve(P& z, H& hamiltonian, const double epsilon) {

        begin_update_p(z, hamiltonian, 0.5 * epsilon);

        update_q(z, hamiltonian, epsilon);
        hamiltonian.update(z);

        end_update_p(z, hamiltonian, 0.5 * epsilon);

      }

      void verbose_evolve(P& z, H& hamiltonian, const double epsilon, std::ostream* error_stream = 0) {

        std::cout.precision(6);
        int width = 14;
        int nColumn = 4;

        std::cout << "Verbose Hamiltonian Evolution, Step Size = " << epsilon << ":" << std::endl;
        std::cout << "    " << std::setw(nColumn * width) << std::setfill('-') << "" << std::setfill(' ') << std::endl;
        std::cout << "    "
                  << std::setw(width) << std::left << "Poisson"
                  << std::setw(width) << std::left << "Initial"
                  << std::setw(width) << std::left << "Current"
                  << std::setw(width) << std::left << "DeltaH"
                  << std::endl;
        std::cout << "    "
                  << std::setw(width) << std::left << "Operator"
                  << std::setw(width) << std::left << "Hamiltonian"
                  << std::setw(width) << std::left << "Hamiltonian"
                  << std::setw(width) << std::left << "/ Stepsize^{2}"
                  << std::endl;
        std::cout << "    " << std::setw(nColumn * width) << std::setfill('-') << "" << std::setfill(' ') << std::endl;

        double H0 = hamiltonian.H(z);

        begin_update_p(z, hamiltonian, 0.5 * epsilon);

        double H1 = hamiltonian.H(z);

        std::cout << "    "
                  << std::setw(width) << std::left << "hat{V}/2"
                  << std::setw(width) << std::left << H0
                  << std::setw(width) << std::left << H1
                  << std::setw(width) << std::left << (H1 - H0) / (epsilon * epsilon)
                  << std::endl;

        update_q(z, hamiltonian, epsilon);
        hamiltonian.update(z, error_stream);

        double H2 = hamiltonian.H(z);

        std::cout << "    "
                  << std::setw(width) << std::left << "hat{T}"
                  << std::setw(width) << std::left << H0
                  << std::setw(width) << std::left << H2
                  << std::setw(width) << std::left << (H2 - H0) / (epsilon * epsilon)
                  << std::endl;

        end_update_p(z, hamiltonian, 0.5 * epsilon);

        double H3 = hamiltonian.H(z);

        std::cout << "    "
                  << std::setw(width) << std::left << "hat{V}/2"
                  << std::setw(width) << std::left << H0
                  << std::setw(width) << std::left << H3
                  << std::setw(width) << std::left << (H3 - H0) / (epsilon * epsilon)
                  << std::endl;

        std::cout << "    " << std::setw(nColumn * width) << std::setfill('-') << "" << std::setfill(' ') << std::endl;

      }

      virtual void begin_update_p(P& z, H& hamiltonian, double epsilon) = 0;
      virtual void update_q(P& z, H& hamiltonian, double epsilon) = 0;
      virtual void end_update_p(P& z, H& hamiltonian, double epsilon) = 0;

    };

  } // mcmc

} // stan

#endif
<commit_msg>Fixed bug in verbose_evolve<commit_after>#ifndef __STAN__MCMC__BASE__LEAPFROG__BETA__
#define __STAN__MCMC__BASE__LEAPFROG__BETA__

#include <iostream>
#include <iomanip>
#include <stan/mcmc/hmc/integrators/base_integrator.hpp>

namespace stan {

  namespace mcmc {

    template <typename H, typename P>
    class base_leapfrog: public base_integrator<H, P> {

    public:

      void evolve(P& z, H& hamiltonian, const double epsilon) {

        begin_update_p(z, hamiltonian, 0.5 * epsilon);

        update_q(z, hamiltonian, epsilon);
        hamiltonian.update(z);

        end_update_p(z, hamiltonian, 0.5 * epsilon);

      }

      void verbose_evolve(P& z, H& hamiltonian, const double epsilon) {

        std::cout.precision(6);
        int width = 14;
        int nColumn = 4;

        std::cout << "Verbose Hamiltonian Evolution, Step Size = " << epsilon << ":" << std::endl;
        std::cout << "    " << std::setw(nColumn * width) << std::setfill('-') << "" << std::setfill(' ') << std::endl;
        std::cout << "    "
                  << std::setw(width) << std::left << "Poisson"
                  << std::setw(width) << std::left << "Initial"
                  << std::setw(width) << std::left << "Current"
                  << std::setw(width) << std::left << "DeltaH"
                  << std::endl;
        std::cout << "    "
                  << std::setw(width) << std::left << "Operator"
                  << std::setw(width) << std::left << "Hamiltonian"
                  << std::setw(width) << std::left << "Hamiltonian"
                  << std::setw(width) << std::left << "/ Stepsize^{2}"
                  << std::endl;
        std::cout << "    " << std::setw(nColumn * width) << std::setfill('-') << "" << std::setfill(' ') << std::endl;

        double H0 = hamiltonian.H(z);

        begin_update_p(z, hamiltonian, 0.5 * epsilon);

        double H1 = hamiltonian.H(z);

        std::cout << "    "
                  << std::setw(width) << std::left << "hat{V}/2"
                  << std::setw(width) << std::left << H0
                  << std::setw(width) << std::left << H1
                  << std::setw(width) << std::left << (H1 - H0) / (epsilon * epsilon)
                  << std::endl;

        update_q(z, hamiltonian, epsilon);
        hamiltonian.update(z);

        double H2 = hamiltonian.H(z);

        std::cout << "    "
                  << std::setw(width) << std::left << "hat{T}"
                  << std::setw(width) << std::left << H0
                  << std::setw(width) << std::left << H2
                  << std::setw(width) << std::left << (H2 - H0) / (epsilon * epsilon)
                  << std::endl;

        end_update_p(z, hamiltonian, 0.5 * epsilon);

        double H3 = hamiltonian.H(z);

        std::cout << "    "
                  << std::setw(width) << std::left << "hat{V}/2"
                  << std::setw(width) << std::left << H0
                  << std::setw(width) << std::left << H3
                  << std::setw(width) << std::left << (H3 - H0) / (epsilon * epsilon)
                  << std::endl;

        std::cout << "    " << std::setw(nColumn * width) << std::setfill('-') << "" << std::setfill(' ') << std::endl;

      }

      virtual void begin_update_p(P& z, H& hamiltonian, double epsilon) = 0;
      virtual void update_q(P& z, H& hamiltonian, double epsilon) = 0;
      virtual void end_update_p(P& z, H& hamiltonian, double epsilon) = 0;

    };

  } // mcmc

} // stan

#endif
<|endoftext|>


<commit_before>//===--- Stmt.cpp - Swift Language Statement ASTs -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements the Stmt class and subclasses.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/Stmt.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Pattern.h"
#include "llvm/ADT/PointerUnion.h"

using namespace swift;

//===----------------------------------------------------------------------===//
// Stmt methods.
//===----------------------------------------------------------------------===//

// Only allow allocation of Stmts using the allocator in ASTContext.
void *Stmt::operator new(size_t Bytes, ASTContext &C,
                         unsigned Alignment) {
  return C.Allocate(Bytes, Alignment);
}

StringRef Stmt::getKindName(StmtKind K) {
  switch (K) {
#define STMT(Id, Parent) case StmtKind::Id: return #Id;
#include "swift/AST/StmtNodes.def"
  }
  llvm_unreachable("bad StmtKind");
}

// Helper functions to check statically whether a method has been
// overridden from its implementation in Stmt.  The sort of thing you
// need when you're avoiding v-tables.
namespace {
  template <typename ReturnType, typename Class>
  constexpr bool isOverriddenFromStmt(ReturnType (Class::*)() const) {
    return true;
  }
  template <typename ReturnType>
  constexpr bool isOverriddenFromStmt(ReturnType (Stmt::*)() const) {
    return false;
  }

  template <bool IsOverridden> struct Dispatch;

  /// Dispatch down to a concrete override.
  template <> struct Dispatch<true> {
    template <class T> static SourceLoc getStartLoc(const T *S) {
      return S->getStartLoc();
    }
    template <class T> static SourceLoc getEndLoc(const T *S) {
      return S->getEndLoc();
    }
    template <class T> static SourceRange getSourceRange(const T *S) {
      return S->getSourceRange();
    }
  };

  /// Default implementations for when a method isn't overridden.
  template <> struct Dispatch<false> {
    template <class T> static SourceLoc getStartLoc(const T *S) {
      return S->getSourceRange().Start;
    }
    template <class T> static SourceLoc getEndLoc(const T *S) {
      return S->getSourceRange().End;
    }
    template <class T> static SourceRange getSourceRange(const T *S) {
      return { S->getStartLoc(), S->getEndLoc() };
    }
  };
}

template <class T> static SourceRange getSourceRangeImpl(const T *S) {
  static_assert(isOverriddenFromStmt(&T::getSourceRange) ||
                (isOverriddenFromStmt(&T::getStartLoc) &&
                 isOverriddenFromStmt(&T::getEndLoc)),
                "Stmt subclass must implement either getSourceRange() "
                "or getStartLoc()/getEndLoc()");
  return Dispatch<isOverriddenFromStmt(&T::getSourceRange)>::getSourceRange(S);
}

SourceRange Stmt::getSourceRange() const {
  switch (getKind()) {
#define STMT(ID, PARENT)                                           \
  case StmtKind::ID: return getSourceRangeImpl(cast<ID##Stmt>(this));
#include "swift/AST/StmtNodes.def"
  }

  llvm_unreachable("statement type not handled!");
}

template <class T> static SourceLoc getStartLocImpl(const T *S) {
  return Dispatch<isOverriddenFromStmt(&T::getStartLoc)>::getStartLoc(S);
}
SourceLoc Stmt::getStartLoc() const {
  switch (getKind()) {
#define STMT(ID, PARENT)                                           \
  case StmtKind::ID: return getStartLocImpl(cast<ID##Stmt>(this));
#include "swift/AST/StmtNodes.def"
  }

  llvm_unreachable("statement type not handled!");
}

template <class T> static SourceLoc getEndLocImpl(const T *S) {
  return Dispatch<isOverriddenFromStmt(&T::getEndLoc)>::getEndLoc(S);
}
SourceLoc Stmt::getEndLoc() const {
  switch (getKind()) {
#define STMT(ID, PARENT)                                           \
  case StmtKind::ID: return getEndLocImpl(cast<ID##Stmt>(this));
#include "swift/AST/StmtNodes.def"
  }

  llvm_unreachable("statement type not handled!");
}

BraceStmt::BraceStmt(SourceLoc lbloc, ArrayRef<ASTNode> elts,
                     SourceLoc rbloc, Optional<bool> implicit)
  : Stmt(StmtKind::Brace, getDefaultImplicitFlag(implicit, lbloc)),
    NumElements(elts.size()), LBLoc(lbloc), RBLoc(rbloc)
{
  std::uninitialized_copy(elts.begin(), elts.end(),
                          getTrailingObjects<ASTNode>());
}

BraceStmt *BraceStmt::create(ASTContext &ctx, SourceLoc lbloc,
                             ArrayRef<ASTNode> elts, SourceLoc rbloc,
                             Optional<bool> implicit) {
  assert(std::none_of(elts.begin(), elts.end(),
                      [](ASTNode node) -> bool { return node.isNull(); }) &&
         "null element in BraceStmt");
  void *Buffer = ctx.Allocate(totalSizeToAlloc<ASTNode>(elts.size()),
                              alignof(BraceStmt));
  return ::new(Buffer) BraceStmt(lbloc, elts, rbloc, implicit);
}

SourceLoc ReturnStmt::getStartLoc() const {
  if (ReturnLoc.isInvalid() && Result)
    return Result->getStartLoc();
  return ReturnLoc;
}
SourceLoc ReturnStmt::getEndLoc() const {
  return (Result ? Result->getEndLoc() : ReturnLoc);
}

SourceLoc ThrowStmt::getEndLoc() const { return SubExpr->getEndLoc(); }

SourceLoc DeferStmt::getEndLoc() const {
  return tempDecl->getBody()->getEndLoc();
}

/// Dig the original user's body of the defer out for AST fidelity.
BraceStmt *DeferStmt::getBodyAsWritten() const {
  return tempDecl->getBody();
}

bool LabeledStmt::isPossibleContinueTarget() const {
  switch (getKind()) {
#define LABELED_STMT(ID, PARENT)
#define STMT(ID, PARENT) case StmtKind::ID:
#include "swift/AST/StmtNodes.def"
    llvm_unreachable("not a labeled statement");

  // Sema has diagnostics with hard-coded expectations about what
  // statements return false from this method.
  case StmtKind::If:
  case StmtKind::Guard:
  case StmtKind::Switch:
    return false;

  case StmtKind::Do:
  case StmtKind::DoCatch:
  case StmtKind::RepeatWhile:
  case StmtKind::For:
  case StmtKind::ForEach:
  case StmtKind::While:
    return true;
  }
  llvm_unreachable("statement kind unhandled!");
}

bool LabeledStmt::requiresLabelOnJump() const {
  switch (getKind()) {
#define LABELED_STMT(ID, PARENT)
#define STMT(ID, PARENT) case StmtKind::ID:
#include "swift/AST/StmtNodes.def"
    llvm_unreachable("not a labeled statement");

  case StmtKind::If:
  case StmtKind::Do:
  case StmtKind::DoCatch:
  case StmtKind::Guard: // Guard doesn't allow labels, so no break/continue.
    return true;

  case StmtKind::RepeatWhile:
  case StmtKind::For:
  case StmtKind::ForEach:
  case StmtKind::Switch:
  case StmtKind::While:
    return false;
  }
  llvm_unreachable("statement kind unhandled!");
}

void ForEachStmt::setPattern(Pattern *p) {
  Pat = p;
  Pat->markOwnedByStatement(this);
}

void CatchStmt::setErrorPattern(Pattern *pattern) {
  ErrorPattern = pattern;
  ErrorPattern->markOwnedByStatement(this);
}

DoCatchStmt *DoCatchStmt::create(ASTContext &ctx, LabeledStmtInfo labelInfo,
                                 SourceLoc doLoc, Stmt *body,
                                 ArrayRef<CatchStmt*> catches,
                                 Optional<bool> implicit) {
  void *mem = ctx.Allocate(totalSizeToAlloc<CatchStmt*>(catches.size()),
                           alignof(DoCatchStmt));
  return ::new (mem) DoCatchStmt(labelInfo, doLoc, body, catches, implicit);
}

bool DoCatchStmt::isSyntacticallyExhaustive() const {
  for (auto clause : getCatches()) {
    if (clause->isSyntacticallyExhaustive())
      return true;
  }
  return false;
}

void LabeledConditionalStmt::setCond(StmtCondition e) {
  // When set a condition into a Conditional Statement, inform each of the
  // variables bound in any patterns that this is the owning statement for the
  // pattern.
  for (auto &elt : e)
    if (auto pat = elt.getPatternOrNull())
      pat->markOwnedByStatement(this);

  Cond = e;
}

bool CatchStmt::isSyntacticallyExhaustive() const {
  // It cannot have a guard expression and the pattern cannot be refutable.
  return getGuardExpr() == nullptr &&
         !getErrorPattern()->isRefutablePattern();
}

PoundAvailableInfo *PoundAvailableInfo::create(ASTContext &ctx,
                                               SourceLoc PoundLoc,
                                       ArrayRef<AvailabilitySpec *> queries,
                                                     SourceLoc RParenLoc) {
  unsigned size = totalSizeToAlloc<AvailabilitySpec *>(queries.size());
  void *Buffer = ctx.Allocate(size, alignof(PoundAvailableInfo));
  return ::new (Buffer) PoundAvailableInfo(PoundLoc, queries, RParenLoc);
}

SourceLoc PoundAvailableInfo::getEndLoc() const {
  if (RParenLoc.isInvalid()) {
    if (NumQueries == 0) {
      return PoundLoc;
    }
    return getQueries()[NumQueries - 1]->getSourceRange().End;
  }
  return RParenLoc;
}

void PoundAvailableInfo::
getPlatformKeywordRanges(SmallVectorImpl<CharSourceRange> &PlatformRanges) {
  for (unsigned int i = 0; i < NumQueries; i ++) {
    auto *VersionSpec =
      dyn_cast<VersionConstraintAvailabilitySpec>(getQueries()[i]);
    if (!VersionSpec)
      continue;

    auto Loc = VersionSpec->getPlatformLoc();
    auto Platform = VersionSpec->getPlatform();
    switch (Platform) {
    case PlatformKind::none:
      break;
#define AVAILABILITY_PLATFORM(X, PrettyName)                          \
  case PlatformKind::X:                                               \
    PlatformRanges.push_back(CharSourceRange(Loc, strlen(#X)));       \
    break;
#include "swift/AST/PlatformKinds.def"
    }
  }
}

SourceRange StmtConditionElement::getSourceRange() const {
  switch (getKind()) {
  case StmtConditionElement::CK_Boolean:
    return getBoolean()->getSourceRange();
  case StmtConditionElement::CK_Availability:
    return getAvailability()->getSourceRange();
  case StmtConditionElement::CK_PatternBinding:
    SourceLoc Start;
    if (IntroducerLoc.isValid())
      Start = IntroducerLoc;
    else
      Start = getPattern()->getStartLoc();

    return SourceRange(Start, getInitializer()->getEndLoc());
  }
}

SourceLoc StmtConditionElement::getStartLoc() const {
  switch (getKind()) {
  case StmtConditionElement::CK_Boolean:
    return getBoolean()->getStartLoc();
  case StmtConditionElement::CK_Availability:
    return getAvailability()->getStartLoc();
  case StmtConditionElement::CK_PatternBinding:
    if (IntroducerLoc.isValid())
      return IntroducerLoc;
    return getPattern()->getStartLoc();
  }
}

SourceLoc StmtConditionElement::getEndLoc() const {
  switch (getKind()) {
  case StmtConditionElement::CK_Boolean:
    return getBoolean()->getEndLoc();
  case StmtConditionElement::CK_Availability:
    return getAvailability()->getEndLoc();
  case StmtConditionElement::CK_PatternBinding:
    return getInitializer()->getEndLoc();
  }
}

static StmtCondition exprToCond(Expr *C, ASTContext &Ctx) {
  StmtConditionElement Arr[] = { StmtConditionElement(C) };
  return Ctx.AllocateCopy(Arr);
}

IfStmt::IfStmt(SourceLoc IfLoc, Expr *Cond, Stmt *Then, SourceLoc ElseLoc,
               Stmt *Else, Optional<bool> implicit, ASTContext &Ctx)
  : IfStmt(LabeledStmtInfo(), IfLoc, exprToCond(Cond, Ctx), Then, ElseLoc, Else,
           implicit) {
}

GuardStmt::GuardStmt(SourceLoc GuardLoc, Expr *Cond, Stmt *Body,
                     Optional<bool> implicit, ASTContext &Ctx)
  : GuardStmt(GuardLoc, exprToCond(Cond, Ctx), Body, implicit) {

}

SourceLoc RepeatWhileStmt::getEndLoc() const { return Cond->getEndLoc(); }

SourceRange CaseLabelItem::getSourceRange() const {
  if (auto *E = getGuardExpr())
    return { CasePattern->getStartLoc(), E->getEndLoc() };
  return CasePattern->getSourceRange();
}
SourceLoc CaseLabelItem::getStartLoc() const {
  return CasePattern->getStartLoc();
}
SourceLoc CaseLabelItem::getEndLoc() const {
  if (auto *E = getGuardExpr())
    return E->getEndLoc();
  return CasePattern->getEndLoc();
}

CaseStmt::CaseStmt(SourceLoc CaseLoc, ArrayRef<CaseLabelItem> CaseLabelItems,
                   bool HasBoundDecls, SourceLoc ColonLoc, Stmt *Body,
                   Optional<bool> Implicit)
    : Stmt(StmtKind::Case, getDefaultImplicitFlag(Implicit, CaseLoc)),
      CaseLoc(CaseLoc), ColonLoc(ColonLoc),
      BodyAndHasBoundDecls(Body, HasBoundDecls),
      NumPatterns(CaseLabelItems.size()) {
  assert(NumPatterns > 0 && "case block must have at least one pattern");
  MutableArrayRef<CaseLabelItem> Items{ getTrailingObjects<CaseLabelItem>(),
                                        NumPatterns };

  for (unsigned i = 0; i < NumPatterns; ++i) {
    new (&Items[i]) CaseLabelItem(CaseLabelItems[i]);
    Items[i].getPattern()->markOwnedByStatement(this);
  }
}

CaseStmt *CaseStmt::create(ASTContext &C, SourceLoc CaseLoc,
                           ArrayRef<CaseLabelItem> CaseLabelItems,
                           bool HasBoundDecls, SourceLoc ColonLoc, Stmt *Body,
                           Optional<bool> Implicit) {
  void *Mem = C.Allocate(totalSizeToAlloc<CaseLabelItem>(CaseLabelItems.size()),
                         alignof(CaseStmt));
  return ::new (Mem) CaseStmt(CaseLoc, CaseLabelItems, HasBoundDecls, ColonLoc,
                              Body, Implicit);
}

SwitchStmt *SwitchStmt::create(LabeledStmtInfo LabelInfo, SourceLoc SwitchLoc,
                               Expr *SubjectExpr,
                               SourceLoc LBraceLoc,
                               ArrayRef<CaseStmt *> Cases,
                               SourceLoc RBraceLoc,
                               ASTContext &C) {
  void *p = C.Allocate(totalSizeToAlloc<CaseStmt *>(Cases.size()),
                       alignof(SwitchStmt));
  SwitchStmt *theSwitch = ::new (p) SwitchStmt(LabelInfo, SwitchLoc,
                                               SubjectExpr, LBraceLoc,
                                               Cases.size(), RBraceLoc);
  std::uninitialized_copy(Cases.begin(), Cases.end(),
                          theSwitch->getTrailingObjects<CaseStmt *>());
  return theSwitch;
}
<commit_msg>[gardening] "unsigned int" → "unsigned" (more idiomatic in LLVM style)<commit_after>//===--- Stmt.cpp - Swift Language Statement ASTs -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements the Stmt class and subclasses.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/Stmt.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Pattern.h"
#include "llvm/ADT/PointerUnion.h"

using namespace swift;

//===----------------------------------------------------------------------===//
// Stmt methods.
//===----------------------------------------------------------------------===//

// Only allow allocation of Stmts using the allocator in ASTContext.
void *Stmt::operator new(size_t Bytes, ASTContext &C,
                         unsigned Alignment) {
  return C.Allocate(Bytes, Alignment);
}

StringRef Stmt::getKindName(StmtKind K) {
  switch (K) {
#define STMT(Id, Parent) case StmtKind::Id: return #Id;
#include "swift/AST/StmtNodes.def"
  }
  llvm_unreachable("bad StmtKind");
}

// Helper functions to check statically whether a method has been
// overridden from its implementation in Stmt.  The sort of thing you
// need when you're avoiding v-tables.
namespace {
  template <typename ReturnType, typename Class>
  constexpr bool isOverriddenFromStmt(ReturnType (Class::*)() const) {
    return true;
  }
  template <typename ReturnType>
  constexpr bool isOverriddenFromStmt(ReturnType (Stmt::*)() const) {
    return false;
  }

  template <bool IsOverridden> struct Dispatch;

  /// Dispatch down to a concrete override.
  template <> struct Dispatch<true> {
    template <class T> static SourceLoc getStartLoc(const T *S) {
      return S->getStartLoc();
    }
    template <class T> static SourceLoc getEndLoc(const T *S) {
      return S->getEndLoc();
    }
    template <class T> static SourceRange getSourceRange(const T *S) {
      return S->getSourceRange();
    }
  };

  /// Default implementations for when a method isn't overridden.
  template <> struct Dispatch<false> {
    template <class T> static SourceLoc getStartLoc(const T *S) {
      return S->getSourceRange().Start;
    }
    template <class T> static SourceLoc getEndLoc(const T *S) {
      return S->getSourceRange().End;
    }
    template <class T> static SourceRange getSourceRange(const T *S) {
      return { S->getStartLoc(), S->getEndLoc() };
    }
  };
}

template <class T> static SourceRange getSourceRangeImpl(const T *S) {
  static_assert(isOverriddenFromStmt(&T::getSourceRange) ||
                (isOverriddenFromStmt(&T::getStartLoc) &&
                 isOverriddenFromStmt(&T::getEndLoc)),
                "Stmt subclass must implement either getSourceRange() "
                "or getStartLoc()/getEndLoc()");
  return Dispatch<isOverriddenFromStmt(&T::getSourceRange)>::getSourceRange(S);
}

SourceRange Stmt::getSourceRange() const {
  switch (getKind()) {
#define STMT(ID, PARENT)                                           \
  case StmtKind::ID: return getSourceRangeImpl(cast<ID##Stmt>(this));
#include "swift/AST/StmtNodes.def"
  }

  llvm_unreachable("statement type not handled!");
}

template <class T> static SourceLoc getStartLocImpl(const T *S) {
  return Dispatch<isOverriddenFromStmt(&T::getStartLoc)>::getStartLoc(S);
}
SourceLoc Stmt::getStartLoc() const {
  switch (getKind()) {
#define STMT(ID, PARENT)                                           \
  case StmtKind::ID: return getStartLocImpl(cast<ID##Stmt>(this));
#include "swift/AST/StmtNodes.def"
  }

  llvm_unreachable("statement type not handled!");
}

template <class T> static SourceLoc getEndLocImpl(const T *S) {
  return Dispatch<isOverriddenFromStmt(&T::getEndLoc)>::getEndLoc(S);
}
SourceLoc Stmt::getEndLoc() const {
  switch (getKind()) {
#define STMT(ID, PARENT)                                           \
  case StmtKind::ID: return getEndLocImpl(cast<ID##Stmt>(this));
#include "swift/AST/StmtNodes.def"
  }

  llvm_unreachable("statement type not handled!");
}

BraceStmt::BraceStmt(SourceLoc lbloc, ArrayRef<ASTNode> elts,
                     SourceLoc rbloc, Optional<bool> implicit)
  : Stmt(StmtKind::Brace, getDefaultImplicitFlag(implicit, lbloc)),
    NumElements(elts.size()), LBLoc(lbloc), RBLoc(rbloc)
{
  std::uninitialized_copy(elts.begin(), elts.end(),
                          getTrailingObjects<ASTNode>());
}

BraceStmt *BraceStmt::create(ASTContext &ctx, SourceLoc lbloc,
                             ArrayRef<ASTNode> elts, SourceLoc rbloc,
                             Optional<bool> implicit) {
  assert(std::none_of(elts.begin(), elts.end(),
                      [](ASTNode node) -> bool { return node.isNull(); }) &&
         "null element in BraceStmt");
  void *Buffer = ctx.Allocate(totalSizeToAlloc<ASTNode>(elts.size()),
                              alignof(BraceStmt));
  return ::new(Buffer) BraceStmt(lbloc, elts, rbloc, implicit);
}

SourceLoc ReturnStmt::getStartLoc() const {
  if (ReturnLoc.isInvalid() && Result)
    return Result->getStartLoc();
  return ReturnLoc;
}
SourceLoc ReturnStmt::getEndLoc() const {
  return (Result ? Result->getEndLoc() : ReturnLoc);
}

SourceLoc ThrowStmt::getEndLoc() const { return SubExpr->getEndLoc(); }

SourceLoc DeferStmt::getEndLoc() const {
  return tempDecl->getBody()->getEndLoc();
}

/// Dig the original user's body of the defer out for AST fidelity.
BraceStmt *DeferStmt::getBodyAsWritten() const {
  return tempDecl->getBody();
}

bool LabeledStmt::isPossibleContinueTarget() const {
  switch (getKind()) {
#define LABELED_STMT(ID, PARENT)
#define STMT(ID, PARENT) case StmtKind::ID:
#include "swift/AST/StmtNodes.def"
    llvm_unreachable("not a labeled statement");

  // Sema has diagnostics with hard-coded expectations about what
  // statements return false from this method.
  case StmtKind::If:
  case StmtKind::Guard:
  case StmtKind::Switch:
    return false;

  case StmtKind::Do:
  case StmtKind::DoCatch:
  case StmtKind::RepeatWhile:
  case StmtKind::For:
  case StmtKind::ForEach:
  case StmtKind::While:
    return true;
  }
  llvm_unreachable("statement kind unhandled!");
}

bool LabeledStmt::requiresLabelOnJump() const {
  switch (getKind()) {
#define LABELED_STMT(ID, PARENT)
#define STMT(ID, PARENT) case StmtKind::ID:
#include "swift/AST/StmtNodes.def"
    llvm_unreachable("not a labeled statement");

  case StmtKind::If:
  case StmtKind::Do:
  case StmtKind::DoCatch:
  case StmtKind::Guard: // Guard doesn't allow labels, so no break/continue.
    return true;

  case StmtKind::RepeatWhile:
  case StmtKind::For:
  case StmtKind::ForEach:
  case StmtKind::Switch:
  case StmtKind::While:
    return false;
  }
  llvm_unreachable("statement kind unhandled!");
}

void ForEachStmt::setPattern(Pattern *p) {
  Pat = p;
  Pat->markOwnedByStatement(this);
}

void CatchStmt::setErrorPattern(Pattern *pattern) {
  ErrorPattern = pattern;
  ErrorPattern->markOwnedByStatement(this);
}

DoCatchStmt *DoCatchStmt::create(ASTContext &ctx, LabeledStmtInfo labelInfo,
                                 SourceLoc doLoc, Stmt *body,
                                 ArrayRef<CatchStmt*> catches,
                                 Optional<bool> implicit) {
  void *mem = ctx.Allocate(totalSizeToAlloc<CatchStmt*>(catches.size()),
                           alignof(DoCatchStmt));
  return ::new (mem) DoCatchStmt(labelInfo, doLoc, body, catches, implicit);
}

bool DoCatchStmt::isSyntacticallyExhaustive() const {
  for (auto clause : getCatches()) {
    if (clause->isSyntacticallyExhaustive())
      return true;
  }
  return false;
}

void LabeledConditionalStmt::setCond(StmtCondition e) {
  // When set a condition into a Conditional Statement, inform each of the
  // variables bound in any patterns that this is the owning statement for the
  // pattern.
  for (auto &elt : e)
    if (auto pat = elt.getPatternOrNull())
      pat->markOwnedByStatement(this);

  Cond = e;
}

bool CatchStmt::isSyntacticallyExhaustive() const {
  // It cannot have a guard expression and the pattern cannot be refutable.
  return getGuardExpr() == nullptr &&
         !getErrorPattern()->isRefutablePattern();
}

PoundAvailableInfo *PoundAvailableInfo::create(ASTContext &ctx,
                                               SourceLoc PoundLoc,
                                       ArrayRef<AvailabilitySpec *> queries,
                                                     SourceLoc RParenLoc) {
  unsigned size = totalSizeToAlloc<AvailabilitySpec *>(queries.size());
  void *Buffer = ctx.Allocate(size, alignof(PoundAvailableInfo));
  return ::new (Buffer) PoundAvailableInfo(PoundLoc, queries, RParenLoc);
}

SourceLoc PoundAvailableInfo::getEndLoc() const {
  if (RParenLoc.isInvalid()) {
    if (NumQueries == 0) {
      return PoundLoc;
    }
    return getQueries()[NumQueries - 1]->getSourceRange().End;
  }
  return RParenLoc;
}

void PoundAvailableInfo::
getPlatformKeywordRanges(SmallVectorImpl<CharSourceRange> &PlatformRanges) {
  for (unsigned i = 0; i < NumQueries; i++) {
    auto *VersionSpec =
      dyn_cast<VersionConstraintAvailabilitySpec>(getQueries()[i]);
    if (!VersionSpec)
      continue;

    auto Loc = VersionSpec->getPlatformLoc();
    auto Platform = VersionSpec->getPlatform();
    switch (Platform) {
    case PlatformKind::none:
      break;
#define AVAILABILITY_PLATFORM(X, PrettyName)                          \
  case PlatformKind::X:                                               \
    PlatformRanges.push_back(CharSourceRange(Loc, strlen(#X)));       \
    break;
#include "swift/AST/PlatformKinds.def"
    }
  }
}

SourceRange StmtConditionElement::getSourceRange() const {
  switch (getKind()) {
  case StmtConditionElement::CK_Boolean:
    return getBoolean()->getSourceRange();
  case StmtConditionElement::CK_Availability:
    return getAvailability()->getSourceRange();
  case StmtConditionElement::CK_PatternBinding:
    SourceLoc Start;
    if (IntroducerLoc.isValid())
      Start = IntroducerLoc;
    else
      Start = getPattern()->getStartLoc();

    return SourceRange(Start, getInitializer()->getEndLoc());
  }
}

SourceLoc StmtConditionElement::getStartLoc() const {
  switch (getKind()) {
  case StmtConditionElement::CK_Boolean:
    return getBoolean()->getStartLoc();
  case StmtConditionElement::CK_Availability:
    return getAvailability()->getStartLoc();
  case StmtConditionElement::CK_PatternBinding:
    if (IntroducerLoc.isValid())
      return IntroducerLoc;
    return getPattern()->getStartLoc();
  }
}

SourceLoc StmtConditionElement::getEndLoc() const {
  switch (getKind()) {
  case StmtConditionElement::CK_Boolean:
    return getBoolean()->getEndLoc();
  case StmtConditionElement::CK_Availability:
    return getAvailability()->getEndLoc();
  case StmtConditionElement::CK_PatternBinding:
    return getInitializer()->getEndLoc();
  }
}

static StmtCondition exprToCond(Expr *C, ASTContext &Ctx) {
  StmtConditionElement Arr[] = { StmtConditionElement(C) };
  return Ctx.AllocateCopy(Arr);
}

IfStmt::IfStmt(SourceLoc IfLoc, Expr *Cond, Stmt *Then, SourceLoc ElseLoc,
               Stmt *Else, Optional<bool> implicit, ASTContext &Ctx)
  : IfStmt(LabeledStmtInfo(), IfLoc, exprToCond(Cond, Ctx), Then, ElseLoc, Else,
           implicit) {
}

GuardStmt::GuardStmt(SourceLoc GuardLoc, Expr *Cond, Stmt *Body,
                     Optional<bool> implicit, ASTContext &Ctx)
  : GuardStmt(GuardLoc, exprToCond(Cond, Ctx), Body, implicit) {

}

SourceLoc RepeatWhileStmt::getEndLoc() const { return Cond->getEndLoc(); }

SourceRange CaseLabelItem::getSourceRange() const {
  if (auto *E = getGuardExpr())
    return { CasePattern->getStartLoc(), E->getEndLoc() };
  return CasePattern->getSourceRange();
}
SourceLoc CaseLabelItem::getStartLoc() const {
  return CasePattern->getStartLoc();
}
SourceLoc CaseLabelItem::getEndLoc() const {
  if (auto *E = getGuardExpr())
    return E->getEndLoc();
  return CasePattern->getEndLoc();
}

CaseStmt::CaseStmt(SourceLoc CaseLoc, ArrayRef<CaseLabelItem> CaseLabelItems,
                   bool HasBoundDecls, SourceLoc ColonLoc, Stmt *Body,
                   Optional<bool> Implicit)
    : Stmt(StmtKind::Case, getDefaultImplicitFlag(Implicit, CaseLoc)),
      CaseLoc(CaseLoc), ColonLoc(ColonLoc),
      BodyAndHasBoundDecls(Body, HasBoundDecls),
      NumPatterns(CaseLabelItems.size()) {
  assert(NumPatterns > 0 && "case block must have at least one pattern");
  MutableArrayRef<CaseLabelItem> Items{ getTrailingObjects<CaseLabelItem>(),
                                        NumPatterns };

  for (unsigned i = 0; i < NumPatterns; ++i) {
    new (&Items[i]) CaseLabelItem(CaseLabelItems[i]);
    Items[i].getPattern()->markOwnedByStatement(this);
  }
}

CaseStmt *CaseStmt::create(ASTContext &C, SourceLoc CaseLoc,
                           ArrayRef<CaseLabelItem> CaseLabelItems,
                           bool HasBoundDecls, SourceLoc ColonLoc, Stmt *Body,
                           Optional<bool> Implicit) {
  void *Mem = C.Allocate(totalSizeToAlloc<CaseLabelItem>(CaseLabelItems.size()),
                         alignof(CaseStmt));
  return ::new (Mem) CaseStmt(CaseLoc, CaseLabelItems, HasBoundDecls, ColonLoc,
                              Body, Implicit);
}

SwitchStmt *SwitchStmt::create(LabeledStmtInfo LabelInfo, SourceLoc SwitchLoc,
                               Expr *SubjectExpr,
                               SourceLoc LBraceLoc,
                               ArrayRef<CaseStmt *> Cases,
                               SourceLoc RBraceLoc,
                               ASTContext &C) {
  void *p = C.Allocate(totalSizeToAlloc<CaseStmt *>(Cases.size()),
                       alignof(SwitchStmt));
  SwitchStmt *theSwitch = ::new (p) SwitchStmt(LabelInfo, SwitchLoc,
                                               SubjectExpr, LBraceLoc,
                                               Cases.size(), RBraceLoc);
  std::uninitialized_copy(Cases.begin(), Cases.end(),
                          theSwitch->getTrailingObjects<CaseStmt *>());
  return theSwitch;
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2014 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 mavlink_stream.cpp
 * Mavlink messages stream implementation.
 *
 * @author Anton Babushkin <anton.babushkin@me.com>
 */

#include <stdlib.h>

#include "mavlink_stream.h"
#include "mavlink_main.h"

MavlinkStream::MavlinkStream(Mavlink *mavlink) :
	next(nullptr),
	_mavlink(mavlink),
	_interval(1000000),
	_last_sent(0 /* 0 means unlimited - updates on every iteration */)
{
}

MavlinkStream::~MavlinkStream()
{
}

/**
 * Set messages interval in ms
 */
void
MavlinkStream::set_interval(const unsigned int interval)
{
	_interval = interval;
}

/**
 * Update subscriptions and send message if necessary
 */
int
MavlinkStream::update(const hrt_abstime t)
{
	// If the message has never been sent before we want
	// to send it immediately and can return right away
	if (_last_sent == 0) {
		// this will give different messages on the same run a different
		// initial timestamp which will help spacing them out
		// on the link scheduling
		_last_sent = hrt_absolute_time();
#ifndef __PX4_QURT
		send(t);
#endif
		return 0;
	}

	int64_t dt = t - _last_sent;
	int interval = _interval;

	if (!const_rate()) {
		interval /= _mavlink->get_rate_mult();
	}

	// send the message if it is due or
	// if it will overrun the next scheduled send interval
	// by 40% of the interval time. This helps to avoid
	// sending a scheduled message on average slower than
	// scheduled. Doing this at 50% would risk sending
	// the message too often as the loop runtime of the app
	// needs to be accounted for as well.
	// This method is not theoretically optimal but a suitable
	// stopgap as it hits its deadlines well (0.5 Hz, 50 Hz and 250 Hz)

	if (dt > (interval - (_mavlink->get_main_loop_delay() / 10) * 4)) {
		// interval expired, send message
#ifndef __PX4_QURT
		send(t);
#endif
		// do not use the actual time but increment at a fixed rate
		// so that processing delays do not distort the average rate
		_last_sent = _last_sent + interval;

		return 0;
	}

	return -1;
}
<commit_msg>MAVLink stream: Guard against an interval value of zero<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2014 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 mavlink_stream.cpp
 * Mavlink messages stream implementation.
 *
 * @author Anton Babushkin <anton.babushkin@me.com>
 */

#include <stdlib.h>

#include "mavlink_stream.h"
#include "mavlink_main.h"

MavlinkStream::MavlinkStream(Mavlink *mavlink) :
	next(nullptr),
	_mavlink(mavlink),
	_interval(1000000),
	_last_sent(0 /* 0 means unlimited - updates on every iteration */)
{
}

MavlinkStream::~MavlinkStream()
{
}

/**
 * Set messages interval in ms
 */
void
MavlinkStream::set_interval(const unsigned int interval)
{
	_interval = interval;
}

/**
 * Update subscriptions and send message if necessary
 */
int
MavlinkStream::update(const hrt_abstime t)
{
	// If the message has never been sent before we want
	// to send it immediately and can return right away
	if (_last_sent == 0) {
		// this will give different messages on the same run a different
		// initial timestamp which will help spacing them out
		// on the link scheduling
		_last_sent = hrt_absolute_time();
#ifndef __PX4_QURT
		send(t);
#endif
		return 0;
	}

	int64_t dt = t - _last_sent;
	int interval = _interval;

	if (!const_rate()) {
		interval /= _mavlink->get_rate_mult();
	}

	// send the message if it is due or
	// if it will overrun the next scheduled send interval
	// by 40% of the interval time. This helps to avoid
	// sending a scheduled message on average slower than
	// scheduled. Doing this at 50% would risk sending
	// the message too often as the loop runtime of the app
	// needs to be accounted for as well.
	// This method is not theoretically optimal but a suitable
	// stopgap as it hits its deadlines well (0.5 Hz, 50 Hz and 250 Hz)

	if (dt > (interval - (_mavlink->get_main_loop_delay() / 10) * 4)) {
		// interval expired, send message
#ifndef __PX4_QURT
		send(t);
#endif
		// if the interval is non-zero do not use the actual time but
		// increment at a fixed rate, so that processing delays do not
		// distort the average rate
		_last_sent = (interval > 0) ? _last_sent + interval : t;

		return 0;
	}

	return -1;
}
<|endoftext|>


<commit_before>// Copyright 2018 The StateChart 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 "statechart/internal/function_dispatcher_impl.h"

#include <glog/logging.h>

#include "statechart/internal/function_dispatcher_builtin.h"
#include "statechart/platform/map_util.h"
#include "absl/memory/memory.h"

namespace state_chart {

namespace internal {

std::vector<string> JsonValuesToStrings(
    const std::vector<const Json::Value*>& values) {
  std::vector<string> json_strs;
  for (const auto* json_value : values) {
    json_strs.push_back(Json::FastWriter().write(*json_value));
  }
  return json_strs;
}

}  // namespace internal

FunctionDispatcherImpl::FunctionDispatcherImpl() {
  RegisterFunction("ContainsKey", &builtin::ContainsKey);
  RegisterFunction("FindFirstWithKeyValue", &builtin::FindFirstWithKeyValue);
}

FunctionDispatcherImpl::FunctionDispatcherImpl(
    const FunctionDispatcherImpl& other) {
  for (const auto& entry : other.function_map_) {
    function_map_.emplace(entry.first, entry.second->Clone());
  }
}

// override
bool FunctionDispatcherImpl::HasFunction(const string& function_name) const {
  return gtl::ContainsKey(function_map_, function_name);
}

// override
bool FunctionDispatcherImpl::Execute(
    const string& function_name, const std::vector<const Json::Value*>& inputs,
    Json::Value* return_value) {
  if (!HasFunction(function_name)) {
    LOG(INFO) << "No function registered for name : " << function_name;
    return false;
  }
  return function_map_.at(function_name)->Execute(inputs, return_value);
}

}  // namespace state_chart
<commit_msg>Clean up function_dispatcher_impl.cc includes<commit_after>// Copyright 2018 The StateChart 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 "statechart/internal/function_dispatcher_impl.h"

#include <glog/logging.h>

#include "statechart/internal/function_dispatcher_builtin.h"
#include "statechart/platform/map_util.h"

namespace state_chart {

namespace internal {

std::vector<string> JsonValuesToStrings(
    const std::vector<const Json::Value*>& values) {
  std::vector<string> json_strs;
  for (const auto* json_value : values) {
    json_strs.push_back(Json::FastWriter().write(*json_value));
  }
  return json_strs;
}

}  // namespace internal

FunctionDispatcherImpl::FunctionDispatcherImpl() {
  RegisterFunction("ContainsKey", &builtin::ContainsKey);
  RegisterFunction("FindFirstWithKeyValue", &builtin::FindFirstWithKeyValue);
}

FunctionDispatcherImpl::FunctionDispatcherImpl(
    const FunctionDispatcherImpl& other) {
  for (const auto& entry : other.function_map_) {
    function_map_.emplace(entry.first, entry.second->Clone());
  }
}

// override
bool FunctionDispatcherImpl::HasFunction(const string& function_name) const {
  return gtl::ContainsKey(function_map_, function_name);
}

// override
bool FunctionDispatcherImpl::Execute(
    const string& function_name, const std::vector<const Json::Value*>& inputs,
    Json::Value* return_value) {
  if (!HasFunction(function_name)) {
    LOG(INFO) << "No function registered for name : " << function_name;
    return false;
  }
  return function_map_.at(function_name)->Execute(inputs, return_value);
}

}  // namespace state_chart
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tdsingleton.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2004-03-25 14:49:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _STOC_RDBTDP_BASE_HXX
#include "base.hxx"
#endif

using namespace com::sun::star;

namespace stoc_rdbtdp
{

//__________________________________________________________________________________________________
// virtual
SingletonTypeDescriptionImpl::~SingletonTypeDescriptionImpl()
{
    delete _pServiceTD;

    g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}

// XTypeDescription
//__________________________________________________________________________________________________
// virtual
TypeClass SingletonTypeDescriptionImpl::getTypeClass()
    throw(::com::sun::star::uno::RuntimeException)
{
    return TypeClass_SINGLETON;
}
//__________________________________________________________________________________________________
// virtual
OUString SingletonTypeDescriptionImpl::getName()
    throw(::com::sun::star::uno::RuntimeException)
{
    return _aName;
}

// XSingletonTypeDescription
//__________________________________________________________________________________________________
// virtual
Reference< XServiceTypeDescription > SAL_CALL
SingletonTypeDescriptionImpl::getService()
    throw(::com::sun::star::uno::RuntimeException)
{
    if ( !_pServiceTD )
    {
        Reference< XServiceTypeDescription > * pServiceTD
            = new Reference< XServiceTypeDescription >();
        try
        {
            _xTDMgr->getByHierarchicalName( _aServiceName ) >>= *pServiceTD;
        }
        catch ( NoSuchElementException const & )
        {
        }
        OSL_ENSURE( (*pServiceTD).is(), "### no type description for service!" );

        ClearableMutexGuard aGuard( getMutex() );
        if ( _pServiceTD )
        {
            aGuard.clear();
            delete pServiceTD;
        }
        else
        {
            _pServiceTD = pServiceTD;
        }
    }

    return *_pServiceTD;
}

}

<commit_msg>INTEGRATION: CWS sb14 (1.1.104); FILE MERGED 2004/03/16 17:27:28 sb 1.1.104.3: #i21150# Fixed some minor mistakes. 2004/03/05 12:36:51 sb 1.1.104.2: #i21150# Added support for service constructors; cleanup. 2004/02/19 14:23:59 sb 1.1.104.1: #i21150# Support for single-interface--based services and interface-based singletons.<commit_after>/*************************************************************************
 *
 *  $RCSfile: tdsingleton.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-03-31 08:07:48 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _STOC_RDBTDP_BASE_HXX
#include "base.hxx"
#endif

using namespace com::sun::star;

namespace stoc_rdbtdp
{

void SingletonTypeDescriptionImpl::init() {
    {
        MutexGuard guard(getMutex());
        if (_xInterfaceTD.is() || _xServiceTD.is()) {
            return;
        }
    }
    Reference< XTypeDescription > base;
    try {
        base = Reference< XTypeDescription >(
            _xTDMgr->getByHierarchicalName(_aBaseName), UNO_QUERY_THROW);
    } catch (NoSuchElementException const & e) {
        throw RuntimeException(
            (OUString(
                RTL_CONSTASCII_USTRINGPARAM(
                    "com.sun.star.container.NoSuchElementException: "))
             + e.Message),
            static_cast< OWeakObject * >(this));
    }
    MutexGuard guard(getMutex());
    if (!_xInterfaceTD.is() && !_xServiceTD.is()) {
        switch (base->getTypeClass()) {
        case TypeClass_INTERFACE:
            _xInterfaceTD = Reference< XInterfaceTypeDescription >(
                base, UNO_QUERY_THROW);
            break;

        case TypeClass_SERVICE:
            _xServiceTD = Reference< XServiceTypeDescription >(
                base, UNO_QUERY_THROW);
            break;

        default:
            throw RuntimeException(
                OUString(
                    RTL_CONSTASCII_USTRINGPARAM(
                        "Singleton is based on neither interface nor service")),
                static_cast< OWeakObject * >(this));
        }
    }
    OSL_ASSERT(_xInterfaceTD.is() ^ _xServiceTD.is());
}

//__________________________________________________________________________________________________
// virtual
SingletonTypeDescriptionImpl::~SingletonTypeDescriptionImpl()
{
    g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}

// XTypeDescription
//__________________________________________________________________________________________________
// virtual
TypeClass SingletonTypeDescriptionImpl::getTypeClass()
    throw(::com::sun::star::uno::RuntimeException)
{
    return TypeClass_SINGLETON;
}
//__________________________________________________________________________________________________
// virtual
OUString SingletonTypeDescriptionImpl::getName()
    throw(::com::sun::star::uno::RuntimeException)
{
    return _aName;
}

// XSingletonTypeDescription
//__________________________________________________________________________________________________
// virtual
Reference< XServiceTypeDescription > SAL_CALL
SingletonTypeDescriptionImpl::getService()
    throw(::com::sun::star::uno::RuntimeException)
{
    init();
    return _xServiceTD;
}

// XSingletonTypeDescription2
//______________________________________________________________________________
// virtual
sal_Bool SAL_CALL
SingletonTypeDescriptionImpl::isInterfaceBased()
    throw(::com::sun::star::uno::RuntimeException)
{
    init();
    return _xInterfaceTD.is();
}

//______________________________________________________________________________
// virtual
Reference< XInterfaceTypeDescription > SAL_CALL
SingletonTypeDescriptionImpl::getInterface()
    throw(::com::sun::star::uno::RuntimeException)
{
    init();
    return _xInterfaceTD;
}

}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -fsyntax-only -Wno-compare-distinct-pointer-type -verify %s
// expected-no-diagnostics
// rdar://12501960

void Foo(int **thing, const int **thingMax)
{
        if ((thing + 3) > thingMax)
                return;
}
<commit_msg>Update test case.<commit_after>// RUN: %clang_cc1 -fsyntax-only -Wno-compare-distinct-pointer-types -verify %s
// expected-no-diagnostics
// rdar://12501960

void Foo(int **thing, const int **thingMax)
{
        if ((thing + 3) > thingMax)
                return;
}
<|endoftext|>


<commit_before>#include "MethodResult.h"
#include "json/JSONIterator.h"
#include "ext/rho/rhoruby.h"

#include "common/RhodesApp.h"

using namespace rho::json;

rho::String CMethodResult::toJSON()
{
    rho::String strRes;
    if ( m_ResType == eStringArray )
    {
        strRes = "[";
        for( int i = 0; i < m_arStrRes.size(); i++ )
        {
            if ( i > 0 )
                strRes += ",";

            strRes += CJSONEntry::quoteValue(m_arStrRes[i]);
        }

        strRes += "]";
    }else if ( m_ResType == eStringHash )
    {
        strRes = "{";

        for ( rho::Hashtable<rho::String, rho::String>::iterator it = m_hashStrRes.begin(); it != m_hashStrRes.end(); ++it)
        {
            if ( it != m_hashStrRes.begin() )
                strRes += ",";

            strRes += CJSONEntry::quoteValue(it->first) + ":" + CJSONEntry::quoteValue(it->second);
        }

        strRes += "}";
    }else if ( m_ResType == eString)
    {
        strRes = m_strRes;
    }else if ( m_ResType == eArgError )
    {
        strRes = "{'_RhoArgError':" + CJSONEntry::quoteValue(m_strError) + "}";
    }else if ( m_ResType == eError)
    {
        strRes = "{'_RhoRuntimeError':" + CJSONEntry::quoteValue(m_strError) + "}";
    }

    return strRes;
}

VALUE CMethodResult::toRuby()
{
    if ( m_ResType == eStringArray )
    {
        CHoldRubyValue valArray(rho_ruby_create_array());

        for( int i = 0; i < m_arStrRes.size(); i++ )
        {
            VALUE valObj = rho_ruby_create_string( m_arStrRes[i].c_str() );
            rho_ruby_add_to_array( valArray, valObj );
        }

        return valArray;
    }else if ( m_ResType == eStringHash )
    {
        CHoldRubyValue valHash(rho_ruby_createHash());

        for ( rho::Hashtable<rho::String, rho::String>::iterator it = m_hashStrRes.begin(); it != m_hashStrRes.end(); ++it)
        {
            addStrToHash( valHash, it->first.c_str(), it->second.c_str() );
        }

        return valHash;
    }else if ( m_ResType == eString)
    {
        return rho_ruby_create_string(m_strRes.c_str());
    }else if ( m_ResType == eArgError)
    {
        rho_ruby_raise_argerror(m_strError.c_str());
    }else if ( m_ResType == eError)
    {
        rho_ruby_raise_runtime(m_strError.c_str());
    }

    return rho_ruby_get_NIL();
}

class CRubyCallbackResult : public rho::ICallbackObject
{
    CMethodResult m_oResult;
public:
    CRubyCallbackResult(const CMethodResult& oResult) : m_oResult(oResult){}
    ~CRubyCallbackResult(){}

    virtual unsigned long getObjectValue()
    {
        m_oResult.convertStringParamToHash();
        return m_oResult.toRuby();
    }

};

void CMethodResult::callCallback()
{
    //TODO: support JSON callbacks

    if ( m_ResType != eNone && m_strRubyCallback.length() != 0 )
    {
        rho::String strResBody = "rho_callback=1";
        if ( m_strCallbackParam.length() > 0 )
            strResBody += "&" + m_strCallbackParam;

        strResBody += "&" + RHODESAPP().addCallbackObject( new CRubyCallbackResult( *this ), "body");

        //TODO: call in async mode
        getNetRequest().pushData( RHODESAPP().canonicalizeRhoUrl(m_strRubyCallback), strResBody, null );

        m_ResType = eNone;
    }
}
<commit_msg>api_generator:c++:make callback calls asynchronously<commit_after>#include "MethodResult.h"
#include "json/JSONIterator.h"
#include "ext/rho/rhoruby.h"

#include "common/RhodesApp.h"

using namespace rho::json;

rho::String CMethodResult::toJSON()
{
    rho::String strRes;
    if ( m_ResType == eStringArray )
    {
        strRes = "[";
        for( int i = 0; i < m_arStrRes.size(); i++ )
        {
            if ( i > 0 )
                strRes += ",";

            strRes += CJSONEntry::quoteValue(m_arStrRes[i]);
        }

        strRes += "]";
    }else if ( m_ResType == eStringHash )
    {
        strRes = "{";

        for ( rho::Hashtable<rho::String, rho::String>::iterator it = m_hashStrRes.begin(); it != m_hashStrRes.end(); ++it)
        {
            if ( it != m_hashStrRes.begin() )
                strRes += ",";

            strRes += CJSONEntry::quoteValue(it->first) + ":" + CJSONEntry::quoteValue(it->second);
        }

        strRes += "}";
    }else if ( m_ResType == eString)
    {
        strRes = m_strRes;
    }else if ( m_ResType == eArgError )
    {
        strRes = "{'_RhoArgError':" + CJSONEntry::quoteValue(m_strError) + "}";
    }else if ( m_ResType == eError)
    {
        strRes = "{'_RhoRuntimeError':" + CJSONEntry::quoteValue(m_strError) + "}";
    }

    return strRes;
}

VALUE CMethodResult::toRuby()
{
    if ( m_ResType == eStringArray )
    {
        CHoldRubyValue valArray(rho_ruby_create_array());

        for( int i = 0; i < m_arStrRes.size(); i++ )
        {
            VALUE valObj = rho_ruby_create_string( m_arStrRes[i].c_str() );
            rho_ruby_add_to_array( valArray, valObj );
        }

        return valArray;
    }else if ( m_ResType == eStringHash )
    {
        CHoldRubyValue valHash(rho_ruby_createHash());

        for ( rho::Hashtable<rho::String, rho::String>::iterator it = m_hashStrRes.begin(); it != m_hashStrRes.end(); ++it)
        {
            addStrToHash( valHash, it->first.c_str(), it->second.c_str() );
        }

        return valHash;
    }else if ( m_ResType == eString)
    {
        return rho_ruby_create_string(m_strRes.c_str());
    }else if ( m_ResType == eArgError)
    {
        rho_ruby_raise_argerror(m_strError.c_str());
    }else if ( m_ResType == eError)
    {
        rho_ruby_raise_runtime(m_strError.c_str());
    }

    return rho_ruby_get_NIL();
}

class CRubyCallbackResult : public rho::ICallbackObject
{
    CMethodResult m_oResult;
public:
    CRubyCallbackResult(const CMethodResult& oResult) : m_oResult(oResult){}
    ~CRubyCallbackResult(){}

    virtual unsigned long getObjectValue()
    {
        m_oResult.convertStringParamToHash();
        return m_oResult.toRuby();
    }

};

void CMethodResult::callCallback()
{
    //TODO: support JSON callbacks

    if ( m_ResType != eNone && m_strRubyCallback.length() != 0 )
    {
        rho::String strResBody = RHODESAPP().addCallbackObject( new CRubyCallbackResult( *this ), "body");

        RHODESAPP().callCallbackWithData( m_strRubyCallback, strResBody, m_strCallbackParam, false);

        m_ResType = eNone;
    }
}
<|endoftext|>