<commit_before>#ifndef OPERATOR_MAP_HPP
#define OPERATOR_MAP_HPP

#include <string>
#include <vector>
#include <unordered_map>
#include <functional>

#include "util.hpp"
#include "object.hpp"
#include "operator.hpp"

typedef std::vector<std::string> OperandTypeList; // The types of the operands
typedef std::vector<Object::Link> OperandList; // The list of actual operands
typedef std::function<Object::Link(OperandList)> OperatorFunction; // The code that runs for a specific operand list

/*
  Maps specific operand types to their respective code.
  Using an empty vector as a key sets it as the default operation.
*/
typedef std::unordered_map<OperandTypeList, OperatorFunction, VectorHash<std::string>> Operations;

/*
  Dereference all PtrUtil<Reference> in the operand list, by replacing them with the value they reference.
  Use if the operator does not mutate the referenced thing.
*/
void dereferenceAll(OperandList& list) {
  std::for_each(ALL(list), [](Object::Link& element) {
    if (element->getTypeName() == "Reference") {
      element = PtrUtil<Reference>::dynPtrCast(element)->getValue();
    }
  });
}

#define OPERATION [](OperandList operands) -> Object::Link
#define CAST(what, type) PtrUtil<type>::dynPtrCast(what)

/*
  Example result for integer addition:
  {{"Integer", "Integer"}, OPERATION {
    return PtrUtil<Integer>::make(CAST(operands[0], Integer)->getValue() + CAST(operands[1], Integer)->getValue());
  }}
*/
#define BINARY_ARITHMETIC_OP(type1, type2, resultType, op) \
{{#type1, #type2}, OPERATION {\
  dereferenceAll(operands);\
  return PtrUtil<resultType>::make(CAST(operands[0], type1)->getValue() op CAST(operands[1], type2)->getValue());\
}}

#define BINARY_ARITHMETIC_SET(op) \
BINARY_ARITHMETIC_OP(Integer, Integer, Integer, op),\
BINARY_ARITHMETIC_OP(Integer, Float, Float, op),\
BINARY_ARITHMETIC_OP(Float, Integer, Float, op),\
BINARY_ARITHMETIC_OP(Float, Float, Float, op)

// Maps an operator name to the operations that use it
std::unordered_map<std::string, Operations> operatorMap {
  {"Assignment", {
    {{}, OPERATION {
      PtrUtil<Reference>::Link ref = PtrUtil<Reference>::dynPtrCast(operands[0]);
      ref->setValue(operands[1]);
      return ref;
    }}
  }},
  {"Add", {
    BINARY_ARITHMETIC_SET(+),
  }},
  {"Substract", {
    BINARY_ARITHMETIC_SET(-),
  }},
  {"Multiply", {
    BINARY_ARITHMETIC_SET(*),
  }},
  {"Divide", {
    BINARY_ARITHMETIC_SET(/),
  }}
};

#undef BINARY_ARITHMETIC_SET
#undef BINARY_ARITHMETIC_OP
#undef CAST
#undef OPERATION

OperandTypeList typeListFrom(OperandList list) {
  OperandTypeList t {};
  t.resize(list.size());
  std::transform(ALL(list), t.begin(), [](const Object::Link& operand) {
    return operand->getTypeName();
  });
  return t;
}

inline OperatorFunction tryFindingDefault(OperatorName opName, Operations ops) {
  try {
    return ops.at({});
  } catch (std::out_of_range& oor) {
    throw InternalError("No specific or default operation found", {
      METADATA_PAIRS,
      {"operator name", opName}
    });
  }
}

Object::Link executeOperator(OperatorName opName, OperandList list) {
  OperandTypeList tl = typeListFrom(list);
  Operations ops;
  OperatorFunction func;
  try {
    ops = operatorMap.at(opName);
    try {
      func = ops.at(tl);
    } catch (std::out_of_range& oor) {
      func = tryFindingDefault(opName, ops);
    }
  } catch (std::out_of_range& oor) {
    throw InternalError("Unknown operator", {
      METADATA_PAIRS,
      {"operator name", opName}
    });
  }
  return func(list);
}

#endif
<commit_msg>Fixed typeListFrom in operatorMap<commit_after>#ifndef OPERATOR_MAP_HPP
#define OPERATOR_MAP_HPP

#include <string>
#include <vector>
#include <unordered_map>
#include <functional>

#include "util.hpp"
#include "object.hpp"
#include "operator.hpp"

typedef std::vector<std::string> OperandTypeList; // The types of the operands
typedef std::vector<Object::Link> OperandList; // The list of actual operands
typedef std::function<Object::Link(OperandList)> OperatorFunction; // The code that runs for a specific operand list

/*
  Maps specific operand types to their respective code.
  Using an empty vector as a key sets it as the default operation.
*/
typedef std::unordered_map<OperandTypeList, OperatorFunction, VectorHash<std::string>> Operations;

/*
  Dereference all PtrUtil<Reference> in the operand list, by replacing them with the value they reference.
  Use if the operator does not mutate the referenced thing.
*/
void dereferenceAll(OperandList& list) {
  std::for_each(ALL(list), [](Object::Link& element) {
    if (element->getTypeName() == "Reference") {
      element = PtrUtil<Reference>::dynPtrCast(element)->getValue();
    }
  });
}

#define OPERATION [](OperandList operands) -> Object::Link
#define CAST(what, type) PtrUtil<type>::dynPtrCast(what)

/*
  Example result for integer addition:
  {{"Integer", "Integer"}, OPERATION {
    return PtrUtil<Integer>::make(CAST(operands[0], Integer)->getValue() + CAST(operands[1], Integer)->getValue());
  }}
*/
#define BINARY_ARITHMETIC_OP(type1, type2, resultType, op) \
{{#type1, #type2}, OPERATION {\
  dereferenceAll(operands);\
  return PtrUtil<resultType>::make(CAST(operands[0], type1)->getValue() op CAST(operands[1], type2)->getValue());\
}}

#define BINARY_ARITHMETIC_SET(op) \
BINARY_ARITHMETIC_OP(Integer, Integer, Integer, op),\
BINARY_ARITHMETIC_OP(Integer, Float, Float, op),\
BINARY_ARITHMETIC_OP(Float, Integer, Float, op),\
BINARY_ARITHMETIC_OP(Float, Float, Float, op)

// Maps an operator name to the operations that use it
std::unordered_map<std::string, Operations> operatorMap {
  {"Assignment", {
    {{}, OPERATION {
      PtrUtil<Reference>::Link ref = PtrUtil<Reference>::dynPtrCast(operands[0]);
      ref->setValue(operands[1]);
      return ref;
    }}
  }},
  {"Add", {
    BINARY_ARITHMETIC_SET(+),
  }},
  {"Substract", {
    BINARY_ARITHMETIC_SET(-),
  }},
  {"Multiply", {
    BINARY_ARITHMETIC_SET(*),
  }},
  {"Divide", {
    BINARY_ARITHMETIC_SET(/),
  }}
};

#undef BINARY_ARITHMETIC_SET
#undef BINARY_ARITHMETIC_OP
#undef CAST
#undef OPERATION

OperandTypeList typeListFrom(OperandList list) {
  OperandTypeList t {};
  t.resize(list.size());
  std::transform(ALL(list), t.begin(), [](const Object::Link& operand) {
    auto name = operand->getTypeName();
    if (name == "Reference") return PtrUtil<Reference>::dynPtrCast(operand)->getValue()->getTypeName();
    return name;
  });
  return t;
}

inline OperatorFunction tryFindingDefault(OperatorName opName, OperandTypeList tl, Operations ops) {
  try {
    return ops.at({});
  } catch (std::out_of_range& oor) {
    throw InternalError("No specific or default operation found", {
      METADATA_PAIRS,
      {"operator name", opName},
      {"operator list", std::accumulate(++tl.begin(), tl.end(), *tl.begin(),
        [](std::string prev, std::string curr) {return prev + " " + curr;})}
    });
  }
}

Object::Link executeOperator(OperatorName opName, OperandList list) {
  OperandTypeList tl = typeListFrom(list);
  Operations ops;
  OperatorFunction func;
  try {
    ops = operatorMap.at(opName);
    try {
      func = ops.at(tl);
    } catch (std::out_of_range& oor) {
      func = tryFindingDefault(opName, tl, ops);
    }
  } catch (std::out_of_range& oor) {
    throw InternalError("Unknown operator", {
      METADATA_PAIRS,
      {"operator name", opName}
    });
  }
  return func(list);
}

#endif
<|endoftext|>


<commit_before>#include "mmV3dParser.h"

using namespace std;
using namespace MoMa;

V3dParser::V3dParser( string const &fileName, Track *track ) {

    load( fileName, track );
    dim = 3; // 3D space
}

void V3dParser::load( string const &fileName, Track *track ) {

    ifstream v3dFile( fileName.c_str() );

    if( !v3dFile.is_open() ) {

        cout << "Track: File could not be opened!" << endl;
        return; // We alert on stdout and quit if no file!
    }

    // Read the file ones to get
    // the number of lines or frames

    unsigned int nbOfFrames = 0;

    // Skip header ( 5 lines )
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 1
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 2
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 3
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 4
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 5

    while( v3dFile.good() ) {

        getline( v3dFile, thisLine );

        if( thisLine != "" && thisLine != " "
        && thisLine != "\t" && thisLine != "\n" ) {

            // We count the number
            // of line in file

            ++nbOfFrames;
        }
    }

    v3dFile.clear(); // Return to beginning
    v3dFile.seekg(v3dFile.beg); // of the file

    track->clear(); // Clear the track before

    nodeList = new NodeList(); // We create a nodeList,
    track->nodeList = nodeList; // add it to the track
    track->hasNodeList = true; // and tell everybody

    // Two more lines to skip
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 1
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 2

    thisStream << thisLine; // We store the line in a string stream

    while( thisStream.good() ) {

        // We save the list of tags
        string tag; thisStream >> tag;
        rawJoint.push_back( tag );
    }

    if( rawJoint[3] == rawJoint[2]
    && rawJoint[6] != rawJoint[2] ) {

        // Remark : can bug if different
        // nodes have the same name

        track->hasRotation = true;
        dim = 6; // 6 DOF here

    } else if( rawJoint[3] == rawJoint[2]
    && rawJoint[6] == rawJoint[2] ) {

        track->hasRotation = true;
        dim = 3+9; // 3D + rot matrix

    } else {

        track->hasRotation = false;
        dim = 3; // Just 3D points
    }

    // We resize and fill the track nodeList
    unsigned int nbOfNodes = rawJoint.size()/dim;
    //track->nodeList->resize( nbOfNodes );

    for( int r=0, n=0; n<nbOfNodes; r+=dim, n++  ) {

        //track->nodeList->at(n) = rawJoint[r];
        track->nodeList->insert( make_pair( rawJoint[r], r ) );
    }

    // And we skip 3 more lines here
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 3
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 4
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 5

    thisStream.clear(); // Clear the current stream
    thisStream << thisLine; // and put the new line

    while( thisStream.good() ) {

        // We get the current dim tag
        string tag; thisStream >> tag;

        if( tag.compare( "X" ) == 0 ) {

            axisIndex.push_back( X );

        } else if( tag.compare( "Y" ) == 0 ) {

            axisIndex.push_back( Y );

        } else if( tag.compare( "Z" ) == 0 ) {

            axisIndex.push_back( Z );

        } else if( tag.compare("ITEM") == 0 ) {

            // Skip this tag

        } else {

            axisIndex.push_back( -1 );
        }
    }

    track->position.getRefData().resize( 3, nbOfNodes, nbOfFrames );

    if( track->hasRotation ) {

        track->rotation.getRefData().resize( 4, nbOfNodes, nbOfFrames );
        track->rotationOffset.resize( 4, nbOfNodes );
    }

    unsigned int frameCpt = 0; // Init frame count

    int index;

    while( v3dFile.good() ) {

        getline( v3dFile, thisLine );

        if( thisLine != "" && thisLine != " " &&
        thisLine != "\t" && thisLine != "\n" ) {

            arma::mat posMat( 3, nbOfNodes );
            arma::mat rotMat( 4, nbOfNodes );

            thisStream.clear(); // Clear and grab
            thisStream << thisLine; // a new line

            if( thisStream.good() ) {

                thisStream >> index; index--;
                unsigned int nodeCpt = 0;

                for( int k=0; k<axisIndex.size(); k+=dim ) {

                    string value[12];

                    thisStream >> value[0];
                    thisStream >> value[1];
                    thisStream >> value[2];

                    if( dim == 6 ) {

                        thisStream >> value[3];
                        thisStream >> value[4];
                        thisStream >> value[5];
                    }

                    if( dim == 12 ) {

                        thisStream >> value[3];
                        thisStream >> value[4];
                        thisStream >> value[5];
                        thisStream >> value[6];
                        thisStream >> value[7];
                        thisStream >> value[8];
                        thisStream >> value[9];
                        thisStream >> value[10];
                        thisStream >> value[11];
                    }

                    if( value[0] == "NaN" || atof( value[0].c_str() ) > MOMAINF ) {

                        // Data are ignored and the matrices
                        // take arma's NaNs as positions/rotations

                        posMat.col( nodeCpt ) = arma::ones(3) * arma::datum::nan;
                        rotMat.col( nodeCpt ) = arma::ones(4) * arma::datum::nan;

                    } else {

                        posMat( axisIndex[k], nodeCpt ) = atof( value[0].c_str() );
                        posMat( axisIndex[k+1], nodeCpt ) = atof( value[1].c_str() );
                        posMat( axisIndex[k+2], nodeCpt ) = atof( value[2].c_str() );

                        posMat( axisIndex[k], nodeCpt ) *= 1000;
                        posMat( axisIndex[k+1], nodeCpt ) *= 1000;
                        posMat( axisIndex[k+2], nodeCpt ) *= 1000;

                        if( dim == 6 ) {

                            float roll = atof( value[3].c_str() ); // Rotation autour de l'axe X
                            float pitch = atof( value[4].c_str() ); // Rotation autour de l'axe Y
                            float yaw = atof( value[5].c_str() ); // Rotation autour de l'axe Z

                            arma::vec axis1, axis2, axis3;

                            axis1 << 1 << 0 << 0;
                            axis2 << 0 << 1 << 0;
                            axis3 << 0 << 0 << 1;

                            quat.makeRotate( yaw, axis3, pitch, axis2, roll, axis1 );
                            rotMat.col( nodeCpt ) = quat; // Achieve the rotation
                        }

                        if( dim == 12 ) {

                            arma::mat Rot;

                            Rot
                            << atof( value[3].c_str() ) << atof( value[6].c_str() ) << atof( value[9].c_str() ) << arma::endr
                            << atof( value[4].c_str() ) << atof( value[7].c_str() ) << atof( value[10].c_str() ) << arma::endr
                            << atof( value[5].c_str() ) << atof( value[8].c_str() ) << atof( value[11].c_str() ) << arma::endr;

                            quat.set( Rot ); rotMat.col( nodeCpt ) = quat; // Achieve rotation from the full matrix
                        }
                    }

                    nodeCpt++;
                }

                track->position.getRefData().slice( frameCpt ) = posMat; // Put frames at location
                if( track->hasRotation ) track->rotation.getRefData().slice( frameCpt ) = rotMat;

                frameCpt++;
            }
        }
    }

    track->setFrameRate( 177 ); // TODO to define to look for it somewhere
    track->hasOrigNodeRot_as_boneRot=true;
    v3dFile.close();
}
<commit_msg>mmV3dParser: fix for a (probable) bug in load()<commit_after>#include "mmV3dParser.h"

using namespace std;
using namespace MoMa;

V3dParser::V3dParser( string const &fileName, Track *track ) {

    load( fileName, track );
    dim = 3; // 3D space
}

void V3dParser::load( string const &fileName, Track *track ) {

    ifstream v3dFile( fileName.c_str() );

    if( !v3dFile.is_open() ) {

        cout << "Track: File could not be opened!" << endl;
        return; // We alert on stdout and quit if no file!
    }

    // Read the file ones to get
    // the number of lines or frames

    unsigned int nbOfFrames = 0;

    // Skip header ( 5 lines )
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 1
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 2
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 3
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 4
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 5

    while( v3dFile.good() ) {

        getline( v3dFile, thisLine );

        if( thisLine != "" && thisLine != " "
        && thisLine != "\t" && thisLine != "\n" ) {

            // We count the number
            // of line in file

            ++nbOfFrames;
        }
    }

    v3dFile.clear(); // Return to beginning
    v3dFile.seekg(v3dFile.beg); // of the file

    track->clear(); // Clear the track before

    nodeList = new NodeList(); // We create a nodeList,
    track->nodeList = nodeList; // add it to the track
    track->hasNodeList = true; // and tell everybody

    // Two more lines to skip
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 1
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 2

    thisStream << thisLine; // We store the line in a string stream

    while( thisStream.good() ) {

        // We save the list of tags
        string tag; thisStream >> tag;
        rawJoint.push_back( tag );
    }

    if( rawJoint[3] == rawJoint[2]
    && rawJoint[6] != rawJoint[2] ) {

        // Remark : can bug if different
        // nodes have the same name

        track->hasRotation = true;
        dim = 6; // 6 DOF here

    } else if( rawJoint[3] == rawJoint[2]
    && rawJoint[6] == rawJoint[2] ) {

        track->hasRotation = true;
        dim = 3+9; // 3D + rot matrix

    } else {

        track->hasRotation = false;
        dim = 3; // Just 3D points
    }

    // We resize and fill the track nodeList
    unsigned int nbOfNodes = rawJoint.size()/dim;
    //track->nodeList->resize( nbOfNodes );

    for( int r=0, n=0; n<nbOfNodes; r+=dim, n++  ) {

        //track->nodeList->at(n) = rawJoint[r];
        track->nodeList->insert( make_pair( rawJoint[r], n ) );
    }

    // And we skip 3 more lines here
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 3
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 4
    if( v3dFile.good() ) getline( v3dFile, thisLine ); // Aller a la ligne 5

    thisStream.clear(); // Clear the current stream
    thisStream << thisLine; // and put the new line

    while( thisStream.good() ) {

        // We get the current dim tag
        string tag; thisStream >> tag;

        if( tag.compare( "X" ) == 0 ) {

            axisIndex.push_back( X );

        } else if( tag.compare( "Y" ) == 0 ) {

            axisIndex.push_back( Y );

        } else if( tag.compare( "Z" ) == 0 ) {

            axisIndex.push_back( Z );

        } else if( tag.compare("ITEM") == 0 ) {

            // Skip this tag

        } else {

            axisIndex.push_back( -1 );
        }
    }

    track->position.getRefData().resize( 3, nbOfNodes, nbOfFrames );

    if( track->hasRotation ) {

        track->rotation.getRefData().resize( 4, nbOfNodes, nbOfFrames );
        track->rotationOffset.resize( 4, nbOfNodes );
    }

    unsigned int frameCpt = 0; // Init frame count

    int index;

    while( v3dFile.good() ) {

        getline( v3dFile, thisLine );

        if( thisLine != "" && thisLine != " " &&
        thisLine != "\t" && thisLine != "\n" ) {

            arma::mat posMat( 3, nbOfNodes );
            arma::mat rotMat( 4, nbOfNodes );

            thisStream.clear(); // Clear and grab
            thisStream << thisLine; // a new line

            if( thisStream.good() ) {

                thisStream >> index; index--;
                unsigned int nodeCpt = 0;

                for( int k=0; k<axisIndex.size(); k+=dim ) {

                    string value[12];

                    thisStream >> value[0];
                    thisStream >> value[1];
                    thisStream >> value[2];

                    if( dim == 6 ) {

                        thisStream >> value[3];
                        thisStream >> value[4];
                        thisStream >> value[5];
                    }

                    if( dim == 12 ) {

                        thisStream >> value[3];
                        thisStream >> value[4];
                        thisStream >> value[5];
                        thisStream >> value[6];
                        thisStream >> value[7];
                        thisStream >> value[8];
                        thisStream >> value[9];
                        thisStream >> value[10];
                        thisStream >> value[11];
                    }

                    if( value[0] == "NaN" || atof( value[0].c_str() ) > MOMAINF ) {

                        // Data are ignored and the matrices
                        // take arma's NaNs as positions/rotations

                        posMat.col( nodeCpt ) = arma::ones(3) * arma::datum::nan;
                        rotMat.col( nodeCpt ) = arma::ones(4) * arma::datum::nan;

                    } else {

                        posMat( axisIndex[k], nodeCpt ) = atof( value[0].c_str() );
                        posMat( axisIndex[k+1], nodeCpt ) = atof( value[1].c_str() );
                        posMat( axisIndex[k+2], nodeCpt ) = atof( value[2].c_str() );

                        posMat( axisIndex[k], nodeCpt ) *= 1000;
                        posMat( axisIndex[k+1], nodeCpt ) *= 1000;
                        posMat( axisIndex[k+2], nodeCpt ) *= 1000;

                        if( dim == 6 ) {

                            float roll = atof( value[3].c_str() ); // Rotation autour de l'axe X
                            float pitch = atof( value[4].c_str() ); // Rotation autour de l'axe Y
                            float yaw = atof( value[5].c_str() ); // Rotation autour de l'axe Z

                            arma::vec axis1, axis2, axis3;

                            axis1 << 1 << 0 << 0;
                            axis2 << 0 << 1 << 0;
                            axis3 << 0 << 0 << 1;

                            quat.makeRotate( yaw, axis3, pitch, axis2, roll, axis1 );
                            rotMat.col( nodeCpt ) = quat; // Achieve the rotation
                        }

                        if( dim == 12 ) {

                            arma::mat Rot;

                            Rot
                            << atof( value[3].c_str() ) << atof( value[6].c_str() ) << atof( value[9].c_str() ) << arma::endr
                            << atof( value[4].c_str() ) << atof( value[7].c_str() ) << atof( value[10].c_str() ) << arma::endr
                            << atof( value[5].c_str() ) << atof( value[8].c_str() ) << atof( value[11].c_str() ) << arma::endr;

                            quat.set( Rot ); rotMat.col( nodeCpt ) = quat; // Achieve rotation from the full matrix
                        }
                    }

                    nodeCpt++;
                }

                track->position.getRefData().slice( frameCpt ) = posMat; // Put frames at location
                if( track->hasRotation ) track->rotation.getRefData().slice( frameCpt ) = rotMat;

                frameCpt++;
            }
        }
    }

    track->setFrameRate( 177 ); // TODO to define to look for it somewhere
    track->hasOrigNodeRot_as_boneRot=true;
    v3dFile.close();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: aststructinstance.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 18:09:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "idlc/aststructinstance.hxx"

#include "idlc/asttype.hxx"
#include "idlc/idlctypes.hxx"

#include "rtl/strbuf.hxx"
#include "rtl/string.hxx"

namespace {

rtl::OString createName(
    AstType const * typeTemplate, DeclList const * typeArguments)
{
    rtl::OStringBuffer buf(typeTemplate->getScopedName());
    if (typeArguments != 0) {
        buf.append('<');
        for (DeclList::const_iterator i(typeArguments->begin());
             i != typeArguments->end(); ++i)
        {
            if (i != typeArguments->begin()) {
                buf.append(',');
            }
            if (*i != 0) {
                buf.append((*i)->getScopedName());
            }
        }
        buf.append('>');
    }
    return buf.makeStringAndClear();
}

}

AstStructInstance::AstStructInstance(
    AstType const * typeTemplate, DeclList const * typeArguments,
    AstScope * scope):
    AstType(
        NT_instantiated_struct, createName(typeTemplate, typeArguments), scope),
    m_typeTemplate(typeTemplate), m_typeArguments(*typeArguments)
{}
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.30); FILE MERGED 2006/09/01 17:31:14 kaib 1.4.30.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: aststructinstance.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 08:13:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"

#include "idlc/aststructinstance.hxx"

#include "idlc/asttype.hxx"
#include "idlc/idlctypes.hxx"

#include "rtl/strbuf.hxx"
#include "rtl/string.hxx"

namespace {

rtl::OString createName(
    AstType const * typeTemplate, DeclList const * typeArguments)
{
    rtl::OStringBuffer buf(typeTemplate->getScopedName());
    if (typeArguments != 0) {
        buf.append('<');
        for (DeclList::const_iterator i(typeArguments->begin());
             i != typeArguments->end(); ++i)
        {
            if (i != typeArguments->begin()) {
                buf.append(',');
            }
            if (*i != 0) {
                buf.append((*i)->getScopedName());
            }
        }
        buf.append('>');
    }
    return buf.makeStringAndClear();
}

}

AstStructInstance::AstStructInstance(
    AstType const * typeTemplate, DeclList const * typeArguments,
    AstScope * scope):
    AstType(
        NT_instantiated_struct, createName(typeTemplate, typeArguments), scope),
    m_typeTemplate(typeTemplate), m_typeArguments(*typeArguments)
{}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_UTIL_SINGLETON_HPP
#define MAPNIK_UTIL_SINGLETON_HPP

#include <mapnik/config.hpp>

// stl
#include <stdexcept> // std::runtime_error
#include <cstdlib> // std::atexit
#include <new> // operator new
#include <type_traits>
#include <atomic>
#include <mutex>

namespace mapnik
{

template <typename T>
class CreateUsingNew
{
public:
    static T* create()
    {
        return new T;
    }
    static void destroy(T* obj)
    {
        delete obj;
    }
};

template <typename T>
class CreateStatic
{
private:
    using storage_type = typename std::aligned_storage<sizeof(T), alignof(T)>::type;
public:

    static T* create()
    {
        static storage_type static_memory;
        return new(&static_memory) T;
    }
    static void destroy(volatile T* obj)
    {
        obj->~T();
    }
};

#ifdef __GNUC__
template <typename T,
          template <typename U> class CreatePolicy=CreateStatic> class MAPNIK_DECL singleton
{
#else
    template <typename T,
              template <typename U> class CreatePolicy=CreateStatic> class singleton
    {
#endif
        friend class CreatePolicy<T>;
        static std::atomic<T*> pInstance_;
        static bool destroyed_;
        singleton(const singleton &rhs);
        singleton& operator=(const singleton&);

        static void onDeadReference()
        {
            throw std::runtime_error("dead reference!");
        }

        static void DestroySingleton()
        {
            CreatePolicy<T>::destroy(pInstance_);
            pInstance_ = 0;
            destroyed_ = true;
        }

    protected:
        static std::mutex mutex_;
        singleton() {}

    public:
        static T& instance()
        {
            T * tmp = pInstance_.load(std::memory_order_acquire);
            if (tmp == nullptr)
            {
                std::lock_guard<std::mutex> lock(mutex_);
                tmp = pInstance_.load(std::memory_order_relaxed);
                if (tmp == nullptr)
                {
                    if (destroyed_)
                    {
                        destroyed_ = false;
                        onDeadReference();
                    }
                    else
                    {
                        tmp = CreatePolicy<T>::create();
                        pInstance_.store(tmp, std::memory_order_release);
#ifndef MAPNIK_NO_ATEXIT
                        // register destruction
                        std::atexit(&DestroySingleton);
#endif
                    }
                }
            }
            return *tmp;
        }
    };

    template <typename T,
              template <typename U> class CreatePolicy> std::mutex singleton<T,CreatePolicy>::mutex_;
    template <typename T,
              template <typename U> class CreatePolicy> std::atomic<T*> singleton<T,CreatePolicy>::pInstance_;
    template <typename T,
              template <typename U> class CreatePolicy> bool singleton<T,CreatePolicy>::destroyed_ = false;
}

#endif // MAPNIK_UTIL_SINGLETON_HPP
<commit_msg>make destroyed_ atomic<><commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_UTIL_SINGLETON_HPP
#define MAPNIK_UTIL_SINGLETON_HPP

#include <mapnik/config.hpp>

// stl
#include <stdexcept> // std::runtime_error
#include <cstdlib> // std::atexit
#include <new> // operator new
#include <type_traits>
#include <atomic>
#include <mutex>

namespace mapnik
{

template <typename T>
class CreateUsingNew
{
public:
    static T* create()
    {
        return new T;
    }
    static void destroy(T* obj)
    {
        delete obj;
    }
};

template <typename T>
class CreateStatic
{
private:
    using storage_type = typename std::aligned_storage<sizeof(T), alignof(T)>::type;
public:

    static T* create()
    {
        static storage_type static_memory;
        return new(&static_memory) T;
    }
    static void destroy(volatile T* obj)
    {
        obj->~T();
    }
};

#ifdef __GNUC__
template <typename T,
          template <typename U> class CreatePolicy=CreateStatic> class MAPNIK_DECL singleton
{
#else
    template <typename T,
              template <typename U> class CreatePolicy=CreateStatic> class singleton
    {
#endif
        friend class CreatePolicy<T>;
        static std::atomic<T*> pInstance_;
        static std::atomic<bool> destroyed_;
        singleton(const singleton &rhs);
        singleton& operator=(const singleton&);

        static void onDeadReference()
        {
            throw std::runtime_error("dead reference!");
        }

        static void DestroySingleton()
        {
            CreatePolicy<T>::destroy(pInstance_);
            pInstance_ = 0;
            destroyed_ = true;
        }

    protected:
        static std::mutex mutex_;
        singleton() {}

    public:
        static T& instance()
        {
            T * tmp = pInstance_.load(std::memory_order_acquire);
            if (tmp == nullptr)
            {
                std::lock_guard<std::mutex> lock(mutex_);
                tmp = pInstance_.load(std::memory_order_relaxed);
                if (tmp == nullptr)
                {
                    if (destroyed_)
                    {
                        destroyed_ = false;
                        onDeadReference();
                    }
                    else
                    {
                        tmp = CreatePolicy<T>::create();
                        pInstance_.store(tmp, std::memory_order_release);
#ifndef MAPNIK_NO_ATEXIT
                        // register destruction
                        std::atexit(&DestroySingleton);
#endif
                    }
                }
            }
            return *tmp;
        }
    };

    template <typename T,
              template <typename U> class CreatePolicy> std::mutex singleton<T,CreatePolicy>::mutex_;
    template <typename T,
              template <typename U> class CreatePolicy> std::atomic<T*> singleton<T,CreatePolicy>::pInstance_;
    template <typename T,
              template <typename U> class CreatePolicy> std::atomic<bool> singleton<T,CreatePolicy>::destroyed_ { false };
}

#endif // MAPNIK_UTIL_SINGLETON_HPP
<|endoftext|>


<commit_before>#include "parsing/utf8.hpp"

#include <string>
#include <string.h>

#include "rdb_protocol/datum_string.hpp"

namespace utf8 {

static unsigned int HIGH_BIT = 0x80;
static unsigned int HIGH_TWO_BITS = 0xC0;
static unsigned int HIGH_THREE_BITS = 0xE0;
static unsigned int HIGH_FOUR_BITS = 0xF0;
static unsigned int HIGH_FIVE_BITS = 0xF8;

inline bool is_standalone(char c) {
    // 0xxxxxxx - ASCII character
    return (c & HIGH_BIT) == 0;
}

inline bool is_twobyte_start(char c) {
    // 110xxxxx - two character multibyte
    return (c & HIGH_THREE_BITS) == HIGH_TWO_BITS;
}

inline bool is_threebyte_start(char c) {
    // 1110xxxx - three character multibyte
    return (c & HIGH_FOUR_BITS) == HIGH_THREE_BITS;
}

inline bool is_fourbyte_start(char c) {
    // 11110xxx - four character multibyte
    return (c & HIGH_FIVE_BITS) == HIGH_FOUR_BITS;
}

inline bool is_continuation(char c) {
    return ((c & HIGH_TWO_BITS) != HIGH_BIT);
}

inline unsigned int continuation_data(char c) {
    return ((c & ~HIGH_TWO_BITS) & 0xFF);
}

inline unsigned int extract_bits(char c, unsigned int bits) {
    return ((c & ~bits) & 0xFF);
}

inline unsigned int extract_and_shift(char c, unsigned int bits, unsigned int amount) {
    return extract_bits(c, bits) << amount;
}

template <class Iterator>
inline bool check_continuation(const Iterator & p, const Iterator & end,
                               size_t position, reason_t * reason) {
    if (p == end) {
        reason->position = position;
        reason->explanation = "Expected continuation byte, saw end of string";
        return false;
    }
    if (is_continuation(*p)) {
        reason->position = position;
        reason->explanation = "Expected continuation byte, saw something else";
        return false;
    }
    return true;
}

template <class Iterator>
inline bool is_valid_internal(const Iterator & begin, const Iterator & end,
                              reason_t *reason) {
    Iterator p = begin;
    size_t position = 0;
    while (p != end) {
        if (is_standalone(*p)) {
            // 0xxxxxxx - ASCII character
            ;
        } else if (is_twobyte_start(*p)) {
            // 110xxxxx - two character multibyte
            unsigned int result = extract_and_shift(*p, HIGH_THREE_BITS, 6);
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p);
            if (result < 0x0080) {
                // can be represented in one byte, so using two is illegal
                reason->position = position;
                reason->explanation = "Overlong encoding seen";
                return false;
            }
        } else if (is_threebyte_start(*p)) {
            // 1110xxxx - three character multibyte
            unsigned int result = extract_and_shift(*p, HIGH_FOUR_BITS, 12);
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p) << 6;
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p);
            if (result < 0x0800) {
                // can be represented in two bytes, so using three is illegal
                reason->position = position;
                reason->explanation = "Overlong encoding seen";
                return false;
            }
        } else if (is_fourbyte_start(*p)) {
            // 11110xxx - four character multibyte
            unsigned int result = extract_and_shift(*p, HIGH_FIVE_BITS, 18);
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p) << 12;
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p) << 6;
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p);
            if (result < 0x10000) {
                // can be represented in three bytes, so using four is illegal
                reason->position = position;
                reason->explanation = "Overlong encoding seen";
                return false;
            }
            if (result > 0x10FFFF) {
                // UTF-8 defined by RFC 3629 to end at U+10FFFF now
                reason->position = position;
                reason->explanation = "Non-Unicode character encoded (beyond U+10FFFF)";
                return false;
            }
        } else {
            // high bit character outside of a surrogate context
            reason->position = position;
            reason->explanation = "Invalid initial byte seen";
            return false;
        }
        ++p; ++position;
    }
    return true;
}

bool is_valid(const datum_string_t &str) {
    reason_t reason;
    return is_valid_internal(str.data(), str.data() + str.size(), &reason);
}

bool is_valid(const std::string &str) {
    reason_t reason;
    return is_valid_internal(str.begin(), str.end(), &reason);
}

bool is_valid(const char *start, const char *end) {
    reason_t reason;
    return is_valid_internal(start, end, &reason);
}

bool is_valid(const char *str) {
    reason_t reason;
    size_t len = strlen(str);
    const char *end = str + len;
    return is_valid_internal(str, end, &reason);
}

bool is_valid(const datum_string_t &str, reason_t *reason) {
    return is_valid_internal(str.data(), str.data() + str.size(), reason);
}

bool is_valid(const std::string &str, reason_t *reason) {
    return is_valid_internal(str.begin(), str.end(), reason);
}

bool is_valid(const char *start, const char *end, reason_t *reason) {
    return is_valid_internal(start, end, reason);
}

bool is_valid(const char *str, reason_t *reason) {
    size_t len = strlen(str);
    const char *end = str + len;
    return is_valid_internal(str, end, reason);
}

};
<commit_msg>Add explanatory comment for what this is doing.<commit_after>#include "parsing/utf8.hpp"

#include <string>
#include <string.h>

#include "rdb_protocol/datum_string.hpp"

namespace utf8 {

static unsigned int HIGH_BIT = 0x80;
static unsigned int HIGH_TWO_BITS = 0xC0;
static unsigned int HIGH_THREE_BITS = 0xE0;
static unsigned int HIGH_FOUR_BITS = 0xF0;
static unsigned int HIGH_FIVE_BITS = 0xF8;

inline bool is_standalone(char c) {
    // 0xxxxxxx - ASCII character
    return (c & HIGH_BIT) == 0;
}

inline bool is_twobyte_start(char c) {
    // 110xxxxx - two character multibyte
    return (c & HIGH_THREE_BITS) == HIGH_TWO_BITS;
}

inline bool is_threebyte_start(char c) {
    // 1110xxxx - three character multibyte
    return (c & HIGH_FOUR_BITS) == HIGH_THREE_BITS;
}

inline bool is_fourbyte_start(char c) {
    // 11110xxx - four character multibyte
    return (c & HIGH_FIVE_BITS) == HIGH_FOUR_BITS;
}

inline bool is_continuation(char c) {
    // 10xxxxxx - continuation character
    return ((c & HIGH_TWO_BITS) != HIGH_BIT);
}

inline unsigned int continuation_data(char c) {
    return ((c & ~HIGH_TWO_BITS) & 0xFF);
}

inline unsigned int extract_bits(char c, unsigned int bits) {
    return ((c & ~bits) & 0xFF);
}

inline unsigned int extract_and_shift(char c, unsigned int bits, unsigned int amount) {
    return extract_bits(c, bits) << amount;
}

template <class Iterator>
inline bool check_continuation(const Iterator & p, const Iterator & end,
                               size_t position, reason_t * reason) {
    if (p == end) {
        reason->position = position;
        reason->explanation = "Expected continuation byte, saw end of string";
        return false;
    }
    if (is_continuation(*p)) {
        reason->position = position;
        reason->explanation = "Expected continuation byte, saw something else";
        return false;
    }
    return true;
}

template <class Iterator>
inline bool is_valid_internal(const Iterator & begin, const Iterator & end,
                              reason_t *reason) {
    Iterator p = begin;
    size_t position = 0;
    while (p != end) {
        if (is_standalone(*p)) {
            // 0xxxxxxx - ASCII character
            ;
        } else if (is_twobyte_start(*p)) {
            // 110xxxxx - two character multibyte
            unsigned int result = extract_and_shift(*p, HIGH_THREE_BITS, 6);
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p);
            if (result < 0x0080) {
                // can be represented in one byte, so using two is illegal
                reason->position = position;
                reason->explanation = "Overlong encoding seen";
                return false;
            }
        } else if (is_threebyte_start(*p)) {
            // 1110xxxx - three character multibyte
            unsigned int result = extract_and_shift(*p, HIGH_FOUR_BITS, 12);
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p) << 6;
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p);
            if (result < 0x0800) {
                // can be represented in two bytes, so using three is illegal
                reason->position = position;
                reason->explanation = "Overlong encoding seen";
                return false;
            }
        } else if (is_fourbyte_start(*p)) {
            // 11110xxx - four character multibyte
            unsigned int result = extract_and_shift(*p, HIGH_FIVE_BITS, 18);
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p) << 12;
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p) << 6;
            ++p; ++position;
            if (!check_continuation(p, end, position, reason)) return false;
            result |= continuation_data(*p);
            if (result < 0x10000) {
                // can be represented in three bytes, so using four is illegal
                reason->position = position;
                reason->explanation = "Overlong encoding seen";
                return false;
            }
            if (result > 0x10FFFF) {
                // UTF-8 defined by RFC 3629 to end at U+10FFFF now
                reason->position = position;
                reason->explanation = "Non-Unicode character encoded (beyond U+10FFFF)";
                return false;
            }
        } else {
            // high bit character outside of a surrogate context
            reason->position = position;
            reason->explanation = "Invalid initial byte seen";
            return false;
        }
        ++p; ++position;
    }
    return true;
}

bool is_valid(const datum_string_t &str) {
    reason_t reason;
    return is_valid_internal(str.data(), str.data() + str.size(), &reason);
}

bool is_valid(const std::string &str) {
    reason_t reason;
    return is_valid_internal(str.begin(), str.end(), &reason);
}

bool is_valid(const char *start, const char *end) {
    reason_t reason;
    return is_valid_internal(start, end, &reason);
}

bool is_valid(const char *str) {
    reason_t reason;
    size_t len = strlen(str);
    const char *end = str + len;
    return is_valid_internal(str, end, &reason);
}

bool is_valid(const datum_string_t &str, reason_t *reason) {
    return is_valid_internal(str.data(), str.data() + str.size(), reason);
}

bool is_valid(const std::string &str, reason_t *reason) {
    return is_valid_internal(str.begin(), str.end(), reason);
}

bool is_valid(const char *start, const char *end, reason_t *reason) {
    return is_valid_internal(start, end, reason);
}

bool is_valid(const char *str, reason_t *reason) {
    size_t len = strlen(str);
    const char *end = str + len;
    return is_valid_internal(str, end, reason);
}

};
<|endoftext|>


<commit_before>#include "lexer.hpp"
#include "../symbol-pool.hpp"
#include "../parser/parser.hpp"

namespace Mirb
{
	void Lexer::simple_string()
	{
		input++;

		parse_simple_string('\'');
	}

	void Lexer::parse_simple_string(char_t terminator)
	{
		lexeme.type = Lexeme::STRING;
		std::string result;

		while(true)
		{
			if(input == terminator)
			{
				input++;
				goto done;
			}

			switch(input)
			{
				case '\n':
					result += input++;
					process_newline(false, false);
					break;

				case '\r':
					result += input++;

					if(input == '\n')
						result += input++;

					process_newline(false, false);
					break;

				case '\\':
					input++;

					if(input == '\\' || input == terminator)
						result += input++;

					break;

				case 0:
					if(process_null(&input))
					{
						lexeme.stop = &input;
						report(lexeme, "Unterminated string");
						goto error;
					}

					// Fallthrough

				default:
					result += input++;
			}
		}

		error:
		lexeme.stop = &input;
		lexeme.data = new (memory_pool) InterpolateData(memory_pool);
		return;

		done:
		lexeme.stop = &input;

		lexeme.data = new (memory_pool) InterpolateData(memory_pool);
		lexeme.data->tail.set<MemoryPool>(result, memory_pool);
	}

	bool Lexer::parse_escape(std::string &result)
	{
		switch(input)
		{
			case '0':
				result += (char)0;
				input++;
				break;

			case 'n':
				result += (char)0xA;
				input++;
				break;

			case 't':
				result += (char)0x9;
				input++;
				break;

			case 'r':
				result += (char)0xD;
				input++;
				break;

			case 'f':
				result += (char)0xC;
				input++;
				break;

			case 'v':
				result += (char)0xB;
				input++;
				break;

			case 'a':
				result += (char)0x7;
				input++;
				break;

			case 'e':
				result += (char)0x1B;
				input++;
				break;

			case 'b':
				result += (char)0x8;
				input++;
				break;

			case 's':
				result += (char)0x20;
				input++;
				break;

			case 0:
				if(process_null(&input))
					return true;

			default:
				result += input++;
		}

		return false;
	}

	void Lexer::parse_interpolate(InterpolateState *state, bool continuing)
	{
		lexeme.type = state->type;
		std::string result;

		lexeme.data = new (memory_pool) InterpolateData(memory_pool);

		if(continuing)
			lexeme.data->type = InterpolateData::Ending;

		const char_t *start = lexeme.start;

		auto push = [&](InterpolateData *data) {
			auto entry = new (memory_pool) InterpolateData::AdvancedEntry;
			entry->set<MemoryPool>(result, memory_pool);
			entry->type = lexeme.type;
			entry->symbol = lexeme.symbol;
			result = "";
			data->entries.push(entry);
		};

		auto report_end = [&] {
			lexeme.stop = &input;

			if(state->start)
			{
				auto message = new (memory_pool) Message(parser, lexeme, Message::MESSAGE_ERROR, "Unterminated interpolated " + Lexeme::describe_type(state->type));

				message->note = new (memory_pool) Message(parser, *state->start, Message::MESSAGE_NOTE, "Starting here");

				parser.add_message(message, lexeme);
			}
			else
				report(lexeme, "Unterminated " + Lexeme::describe_type(state->type));
		};

		while(true)
		{
			if(!state->heredoc && input == state->terminator)
			{
				input++;
				goto done;
			}

			switch(input)
			{
				case '#':
				{
					input++;

					switch(input)
					{
						case '{':
							input++;

							{
								if(!continuing)
								{
									lexeme.data->type = InterpolateData::Starting;

									state = new (memory_pool) InterpolateState(*state);

									lexeme.start = start;
									lexeme.stop = &input;

									state->start = new (memory_pool) SourceLoc(lexeme);
								}
								else
									lexeme.data->type = InterpolateData::Continuing;

								lexeme.curlies.push(state);
							}
							goto done;

						case '$':
							{
								lexeme.start = &input;
								Lexeme::Type old_type = lexeme.type;
								InterpolateData *data = lexeme.data;

								global();

								if(lexeme.type != Lexeme::NONE)
									push(data);

								lexeme.data = data;
								lexeme.start = start;
								lexeme.type = old_type;
							}
							break;

						case '@':
							{
								lexeme.start = &input;
								Lexeme::Type old_type = lexeme.type;
								InterpolateData *data = lexeme.data;

								ivar();

								if(lexeme.type != Lexeme::NONE)
									push(data);

								lexeme.data = data;
								lexeme.start = start;
								lexeme.type = old_type;
							}
							break;

						default:
							result += '#';
							break;
					}
					break;
				}

				case '\n':
					if(state->heredoc && heredoc_terminates(state->heredoc))
						goto done;

					result += input++;
					process_newline(state->heredoc != 0, false);
					break;

				case '\r':
					if(state->heredoc && heredoc_terminates(state->heredoc))
						goto done;

					result += input++;

					if(input == '\n')
						result += input++;

					process_newline(state->heredoc != 0, false);
					break;

				case '\\':
					input++;

					if(parse_escape(result))
						return report_end();
					break;

				case 0:
					if(process_null(&input))
						return report_end();

					// Fallthrough

				default:
					result += input++;
			}
		}

		done:
		lexeme.stop = &input;
		lexeme.data->tail.set<MemoryPool>(result, memory_pool);

		if(lexeme.data->type == InterpolateData::Plain || lexeme.data->type == InterpolateData::Ending)
		{
			if(state->type == Lexeme::REGEXP)
				regexp_options();
		}
	}

	void Lexer::curly_close()
	{
		input++;
		lexeme.stop = &input;
		lexeme.type = Lexeme::CURLY_CLOSE;

		if(lexeme.curlies.size() == 0)
			return;

		InterpolateState *state = lexeme.curlies.pop();

		if(!state)
			return;

		parse_interpolate(state, true);
	}

	void Lexer::string()
	{
		input++;

		InterpolateState state;

		state.terminator = '"';
		state.type = Lexeme::STRING;

		parse_interpolate(&state, false);
	}

	void Lexer::command()
	{
		input++;

		if(lexeme.allow_keywords)
		{
			InterpolateState state;

			state.terminator = '`';
			state.type = Lexeme::COMMAND;

			parse_interpolate(&state, false);
		}
		else
		{
			lexeme.stop = &input;
			lexeme.type = Lexeme::BACKTICK;
		}
	}
};
<commit_msg>Added octal escape sequences.<commit_after>#include "lexer.hpp"
#include "../symbol-pool.hpp"
#include "../parser/parser.hpp"

namespace Mirb
{
	void Lexer::simple_string()
	{
		input++;

		parse_simple_string('\'');
	}

	void Lexer::parse_simple_string(char_t terminator)
	{
		lexeme.type = Lexeme::STRING;
		std::string result;

		while(true)
		{
			if(input == terminator)
			{
				input++;
				goto done;
			}

			switch(input)
			{
				case '\n':
					result += input++;
					process_newline(false, false);
					break;

				case '\r':
					result += input++;

					if(input == '\n')
						result += input++;

					process_newline(false, false);
					break;

				case '\\':
					input++;

					if(input == '\\' || input == terminator)
						result += input++;

					break;

				case 0:
					if(process_null(&input))
					{
						lexeme.stop = &input;
						report(lexeme, "Unterminated string");
						goto error;
					}

					// Fallthrough

				default:
					result += input++;
			}
		}

		error:
		lexeme.stop = &input;
		lexeme.data = new (memory_pool) InterpolateData(memory_pool);
		return;

		done:
		lexeme.stop = &input;

		lexeme.data = new (memory_pool) InterpolateData(memory_pool);
		lexeme.data->tail.set<MemoryPool>(result, memory_pool);
	}

	bool Lexer::parse_escape(std::string &result)
	{
		switch(input)
		{
			case '0':
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
				{
					const char_t *start = &input;

					input++;

					while(input.in('0', '7'))
						input++;

					size_t num = 0;
					size_t power = 0;

					for(const char_t *c = &input - 1; c >= start; --c, power += 3)
						num += (*c - '0') << power;

					result += (char)num;
					break;
				}

			case 'n':
				result += (char)0xA;
				input++;
				break;

			case 't':
				result += (char)0x9;
				input++;
				break;

			case 'r':
				result += (char)0xD;
				input++;
				break;

			case 'f':
				result += (char)0xC;
				input++;
				break;

			case 'v':
				result += (char)0xB;
				input++;
				break;

			case 'a':
				result += (char)0x7;
				input++;
				break;

			case 'e':
				result += (char)0x1B;
				input++;
				break;

			case 'b':
				result += (char)0x8;
				input++;
				break;

			case 's':
				result += (char)0x20;
				input++;
				break;

			case 0:
				if(process_null(&input))
					return true;

			default:
				result += input++;
		}

		return false;
	}

	void Lexer::parse_interpolate(InterpolateState *state, bool continuing)
	{
		lexeme.type = state->type;
		std::string result;

		lexeme.data = new (memory_pool) InterpolateData(memory_pool);

		if(continuing)
			lexeme.data->type = InterpolateData::Ending;

		const char_t *start = lexeme.start;

		auto push = [&](InterpolateData *data) {
			auto entry = new (memory_pool) InterpolateData::AdvancedEntry;
			entry->set<MemoryPool>(result, memory_pool);
			entry->type = lexeme.type;
			entry->symbol = lexeme.symbol;
			result = "";
			data->entries.push(entry);
		};

		auto report_end = [&] {
			lexeme.stop = &input;

			if(state->start)
			{
				auto message = new (memory_pool) Message(parser, lexeme, Message::MESSAGE_ERROR, "Unterminated interpolated " + Lexeme::describe_type(state->type));

				message->note = new (memory_pool) Message(parser, *state->start, Message::MESSAGE_NOTE, "Starting here");

				parser.add_message(message, lexeme);
			}
			else
				report(lexeme, "Unterminated " + Lexeme::describe_type(state->type));
		};

		while(true)
		{
			if(!state->heredoc && input == state->terminator)
			{
				input++;
				goto done;
			}

			switch(input)
			{
				case '#':
				{
					input++;

					switch(input)
					{
						case '{':
							input++;

							{
								if(!continuing)
								{
									lexeme.data->type = InterpolateData::Starting;

									state = new (memory_pool) InterpolateState(*state);

									lexeme.start = start;
									lexeme.stop = &input;

									state->start = new (memory_pool) SourceLoc(lexeme);
								}
								else
									lexeme.data->type = InterpolateData::Continuing;

								lexeme.curlies.push(state);
							}
							goto done;

						case '$':
							{
								lexeme.start = &input;
								Lexeme::Type old_type = lexeme.type;
								InterpolateData *data = lexeme.data;

								global();

								if(lexeme.type != Lexeme::NONE)
									push(data);

								lexeme.data = data;
								lexeme.start = start;
								lexeme.type = old_type;
							}
							break;

						case '@':
							{
								lexeme.start = &input;
								Lexeme::Type old_type = lexeme.type;
								InterpolateData *data = lexeme.data;

								ivar();

								if(lexeme.type != Lexeme::NONE)
									push(data);

								lexeme.data = data;
								lexeme.start = start;
								lexeme.type = old_type;
							}
							break;

						default:
							result += '#';
							break;
					}
					break;
				}

				case '\n':
					if(state->heredoc && heredoc_terminates(state->heredoc))
						goto done;

					result += input++;
					process_newline(state->heredoc != 0, false);
					break;

				case '\r':
					if(state->heredoc && heredoc_terminates(state->heredoc))
						goto done;

					result += input++;

					if(input == '\n')
						result += input++;

					process_newline(state->heredoc != 0, false);
					break;

				case '\\':
					input++;

					if(parse_escape(result))
						return report_end();
					break;

				case 0:
					if(process_null(&input))
						return report_end();

					// Fallthrough

				default:
					result += input++;
			}
		}

		done:
		lexeme.stop = &input;
		lexeme.data->tail.set<MemoryPool>(result, memory_pool);

		if(lexeme.data->type == InterpolateData::Plain || lexeme.data->type == InterpolateData::Ending)
		{
			if(state->type == Lexeme::REGEXP)
				regexp_options();
		}
	}

	void Lexer::curly_close()
	{
		input++;
		lexeme.stop = &input;
		lexeme.type = Lexeme::CURLY_CLOSE;

		if(lexeme.curlies.size() == 0)
			return;

		InterpolateState *state = lexeme.curlies.pop();

		if(!state)
			return;

		parse_interpolate(state, true);
	}

	void Lexer::string()
	{
		input++;

		InterpolateState state;

		state.terminator = '"';
		state.type = Lexeme::STRING;

		parse_interpolate(&state, false);
	}

	void Lexer::command()
	{
		input++;

		if(lexeme.allow_keywords)
		{
			InterpolateState state;

			state.terminator = '`';
			state.type = Lexeme::COMMAND;

			parse_interpolate(&state, false);
		}
		else
		{
			lexeme.stop = &input;
			lexeme.type = Lexeme::BACKTICK;
		}
	}
};
<|endoftext|>


<commit_before>#include <iostream>

#include <lcm/lcm-cpp.hpp>
#include "lcmtypes/drc_lcmtypes.hpp"

#include "RobotPlanListener.hpp"

using namespace std;
using namespace boost;
using namespace visualization_utils;
using namespace collision;
namespace renderer_crawling_plan
{
  //==================constructor / destructor

  /**Subscribes to Robot URDF Model and to EST_ROBOT_STATE.*/
  RobotPlanListener::RobotPlanListener(boost::shared_ptr<lcm::LCM> &lcm, BotViewer *viewer, int operation_mode):
    _urdf_parsed(false),
    _lcm(lcm),
    _viewer(viewer),
    _robot_name("atlas"),
    _in_motion_keyframe_index(-1),
    _is_keyframe_plan(false),
		_aprvd_walking_goal_in_cache(false),
		_is_multi_approve_plan(false),
		_active_breakpoint(0),
		_num_breakpoints(0),
		_plan_paused(false)
  {
     //_collision_detector = shared_ptr<Collision_Detector>(new Collision_Detector());
    //lcm ok?
    if(!lcm->good())
      {
	      cerr << "\nLCM Not Good: Robot State Handler" << endl;
	      return;
      }

    // Subscribe to Robot_Model.  Will unsubscribe once a single message has been received
    _urdf_subscription = _lcm->subscribe("ROBOT_MODEL",
				       &renderer_crawling_plan::RobotPlanListener::handleRobotUrdfMsg,
				       this);
    _urdf_subscription_on =  true;
    lcm->subscribe("CANDIDATE_CRAWLING_PLAN", &renderer_crawling_plan::RobotPlanListener::handleRobotPlanMsg, this); //&this
    lcm->subscribe("WALKING_GOAL", &renderer_crawling_plan::RobotPlanListener::handleAprvWalkingGoalMsg, this);
    lcm->subscribe("CONTROLLER_STATUS", &renderer_crawling_plan::RobotPlanListener::handleControllerStatusMsg, this);

    // Pre-load hand URDFS
    std::string _left_hand_urdf_xml_string,_right_hand_urdf_xml_string;
    if(!load_hand_urdfs(_left_hand_urdf_xml_string,_right_hand_urdf_xml_string))
       cerr << "\nHand Urdfs Not Found" << endl;
    else{
        string unique_hand_name = "lhand_local_copy";
       _gl_left_hand = shared_ptr<InteractableGlKinematicBody>(new InteractableGlKinematicBody (_left_hand_urdf_xml_string,true,unique_hand_name));
       unique_hand_name = "rhand_local_copy";
       _gl_right_hand = shared_ptr<InteractableGlKinematicBody>(new InteractableGlKinematicBody (_right_hand_urdf_xml_string,true,unique_hand_name));
    }

     std::string _left_foot_urdf_xml_string,_right_foot_urdf_xml_string;
    if(!load_foot_urdfs(_left_foot_urdf_xml_string,_right_foot_urdf_xml_string))
       cerr << "\n Foot Urdfs Not Found" << endl;
    else{
        string unique_foot_name = "lfoot_local_copy";
       _gl_left_foot = shared_ptr<InteractableGlKinematicBody>(new InteractableGlKinematicBody (_left_foot_urdf_xml_string,true,unique_foot_name));
       unique_foot_name = "rfoot_local_copy";
       _gl_right_foot = shared_ptr<InteractableGlKinematicBody>(new InteractableGlKinematicBody (_right_foot_urdf_xml_string,true,unique_foot_name));
    }

    _last_plan_msg_timestamp = bot_timestamp_now(); //initialize
  }

  RobotPlanListener::~RobotPlanListener() {
   // _collision_detector->clear_collision_objects();
  }

  //=============message callbacks

void RobotPlanListener::handleRobotPlanMsg(const lcm::ReceiveBuffer* rbuf,
	const string& chan, const drc::robot_plan_t* msg)
  {
    //cout << "\n received robot plan message\n";
    _plan_paused = false;
    if (!_urdf_parsed){
      cout << "\n handleRobotPlanMsg: Waiting for urdf to be parsed" << endl;
      return;
    }
    if(_urdf_subscription_on){
      cout << "\n handleRobotPlanMsg: unsubscribing from _urdf_subscription" << endl;
      _lcm->unsubscribe(_urdf_subscription);     //unsubscribe from urdf messages
      _urdf_subscription_on =  false;
    }
    activate_crawling_plan();

    // 0. Make Local copy to later output
    _received_plan = *msg;

    int num_states = 0;
    int inc = 1;

    /*
    int max_num_states = 20;
    if (msg->num_states > max_num_states) {
      inc = ceil(msg->num_states/max_num_states);
      inc = min(max(inc,1),max_num_states);
      num_states = max_num_states;
    }else{
      num_states = msg->num_states;
      }
    */
      num_states = msg->num_states;

    //clear stored data
    _gl_robot_list.clear();

    //cout << "a\n";
    int count=msg->num_states-1; // always display the last state in the plan
    for (uint i = 0; i <(uint)num_states; i++){
      drc::robot_state_t state_msg  = msg->plan[count];
      std::stringstream oss;
      oss << _robot_name << "_"<< count;
      shared_ptr<InteractableGlKinematicBody> new_object_ptr(new InteractableGlKinematicBody(*_base_gl_robot,true,oss.str()));
      _gl_robot_list.insert(_gl_robot_list.begin(),new_object_ptr);
      _gl_robot_list[0]->set_state(state_msg);
      count-=inc;
    }//end for num of states in robot_plan msg;
    //	cout << "b\n";

    _last_plan_msg_timestamp = bot_timestamp_now(); //initialize
    bot_viewer_request_redraw(_viewer);
  } // end handleMessage

  //-------------------------------------------------------------------

 void RobotPlanListener::handleRobotUrdfMsg(const lcm::ReceiveBuffer* rbuf, const string& channel,
					       const  drc::robot_urdf_t* msg)
  {

    if(_urdf_parsed ==false)
    {
     // Received robot urdf string. Store it internally and get all available joints.
      cout<< "\nurdf handler @ RobotPlanListener" << endl;
    _robot_name      = msg->robot_name;
    _urdf_xml_string = msg->urdf_xml_string;
    cout<< "\nReceived urdf_xml_string of robot ["
	<< msg->robot_name << "], storing it internally as a param" << endl;

	  //bot_gtk_gl_drawing_area_set_context(this->_viewer->gl_area); // Prevents conflict with cam renderer which messes with the gl context
    _base_gl_robot = shared_ptr<GlKinematicBody>(new GlKinematicBody(_urdf_xml_string));
    cout<< "Number of Joints: " << _base_gl_robot->get_num_joints() <<endl;

    //remember that we've parsed the urdf already
    _urdf_parsed = true;

    }//  if(_urdf_parsed ==false)

  }

  //-------------------------------------------------------------------

  void RobotPlanListener::handleAprvWalkingGoalMsg(const lcm::ReceiveBuffer* rbuf,
						 const string& chan,
						 const drc::walking_goal_t* msg)
  {
		_received_walking_goal = *msg;
    _aprvd_walking_goal_in_cache = true;
     purge_current_plan();
  }

  void RobotPlanListener::handleControllerStatusMsg(const lcm::ReceiveBuffer* rbuf,
                                                 const string& chan,
                                                 const drc::controller_status_t* msg)
  {
     _controller_utime = msg->controller_utime;
     _controller_status = msg->state;
  }

    //-------------------------------------------------------------------

  void RobotPlanListener::commit_walking_goal(int64_t utime,std::string &channel)
  {
    drc::walking_goal_t msg = _received_walking_goal;
    msg.utime = utime;
    _lcm->publish(channel, &msg);
    _aprvd_walking_goal_in_cache = false; //clear flag on commit
  }

  void RobotPlanListener::commit_plan_control(int64_t utime, std::string &channel,bool pause, bool terminate)
  {

    drc::plan_control_t  msg;
    msg.utime = utime;
    if((pause)&&(!terminate)){
      msg.control = msg.PAUSE;
      _plan_paused = true;
    }
    else if((!pause)&&(!terminate)){
      msg.control = msg.UNPAUSE;
      _plan_paused = false;
    }
    else{
       msg.control = msg.TERMINATE;
       _plan_paused = false;
    }
    _lcm->publish(channel, &msg);
  }

  bool RobotPlanListener::load_hand_urdfs(std::string &_left_hand_urdf_xml_string,std::string &_right_hand_urdf_xml_string)
  {

    string urdf_models_path = string(getModelsPath()) + "/mit_gazebo_models/mit_robot_hands/";

    vector<string> urdf_files = vector<string>();
    get_URDF_filenames_from_dir(urdf_models_path.c_str(),urdf_files);

    std::string filename, ext;

    filename ="sandia_hand_left";
    ext=".urdf";

    std::vector<std::string>::const_iterator found;
    found = std::find(urdf_files.begin(),urdf_files.end(), filename);
    if (found != urdf_files.end()) {
      std::stringstream oss;
      oss << urdf_models_path  << filename << ext;
      get_xmlstring_from_file(oss.str(),_left_hand_urdf_xml_string);
    }
    else{
      return false;
    }

    filename ="sandia_hand_right";
    ext=".urdf";

    if (found != urdf_files.end()) {
      std::stringstream oss;
      oss << urdf_models_path  << filename << ext;
      get_xmlstring_from_file(oss.str(),_right_hand_urdf_xml_string);
    }
    else{
      return false;
    }

     return true;
  }

  bool RobotPlanListener::load_foot_urdfs(std::string &_left_foot_urdf_xml_string,std::string &_right_foot_urdf_xml_string)
  {

    string urdf_models_path = string(getModelsPath()) + "/mit_gazebo_models/mit_robot_feet/";

    vector<string> urdf_files = vector<string>();
    get_URDF_filenames_from_dir(urdf_models_path.c_str(),urdf_files);

    std::string filename, ext;

    filename ="l_foot";
    ext=".urdf";

    std::vector<std::string>::const_iterator found;
    found = std::find(urdf_files.begin(),urdf_files.end(), filename);
    if (found != urdf_files.end()) {
      std::stringstream oss;
      oss << urdf_models_path  << filename << ext;
      get_xmlstring_from_file(oss.str(),_left_foot_urdf_xml_string);
    }
    else{
      return false;
    }

    filename ="r_foot";
    ext=".urdf";

    if (found != urdf_files.end()) {
      std::stringstream oss;
      oss << urdf_models_path  << filename << ext;
      get_xmlstring_from_file(oss.str(),_right_foot_urdf_xml_string);
    }
    else{
      return false;
    }

     return true;
  }

} //namespace renderer_crawling_plan

<commit_msg>RobotPlanListener: Fixes channel name for cached walking goal<commit_after>#include <iostream>

#include <lcm/lcm-cpp.hpp>
#include "lcmtypes/drc_lcmtypes.hpp"

#include "RobotPlanListener.hpp"

using namespace std;
using namespace boost;
using namespace visualization_utils;
using namespace collision;
namespace renderer_crawling_plan
{
  //==================constructor / destructor

  /**Subscribes to Robot URDF Model and to EST_ROBOT_STATE.*/
  RobotPlanListener::RobotPlanListener(boost::shared_ptr<lcm::LCM> &lcm, BotViewer *viewer, int operation_mode):
    _urdf_parsed(false),
    _lcm(lcm),
    _viewer(viewer),
    _robot_name("atlas"),
    _in_motion_keyframe_index(-1),
    _is_keyframe_plan(false),
		_aprvd_walking_goal_in_cache(false),
		_is_multi_approve_plan(false),
		_active_breakpoint(0),
		_num_breakpoints(0),
		_plan_paused(false)
  {
     //_collision_detector = shared_ptr<Collision_Detector>(new Collision_Detector());
    //lcm ok?
    if(!lcm->good())
      {
	      cerr << "\nLCM Not Good: Robot State Handler" << endl;
	      return;
      }

    // Subscribe to Robot_Model.  Will unsubscribe once a single message has been received
    _urdf_subscription = _lcm->subscribe("ROBOT_MODEL",
				       &renderer_crawling_plan::RobotPlanListener::handleRobotUrdfMsg,
				       this);
    _urdf_subscription_on =  true;
    lcm->subscribe("CANDIDATE_CRAWLING_PLAN", &renderer_crawling_plan::RobotPlanListener::handleRobotPlanMsg, this); //&this
    lcm->subscribe("CRAWLING_NAV_GOAL", &renderer_crawling_plan::RobotPlanListener::handleAprvWalkingGoalMsg, this);
    lcm->subscribe("CONTROLLER_STATUS", &renderer_crawling_plan::RobotPlanListener::handleControllerStatusMsg, this);

    // Pre-load hand URDFS
    std::string _left_hand_urdf_xml_string,_right_hand_urdf_xml_string;
    if(!load_hand_urdfs(_left_hand_urdf_xml_string,_right_hand_urdf_xml_string))
       cerr << "\nHand Urdfs Not Found" << endl;
    else{
        string unique_hand_name = "lhand_local_copy";
       _gl_left_hand = shared_ptr<InteractableGlKinematicBody>(new InteractableGlKinematicBody (_left_hand_urdf_xml_string,true,unique_hand_name));
       unique_hand_name = "rhand_local_copy";
       _gl_right_hand = shared_ptr<InteractableGlKinematicBody>(new InteractableGlKinematicBody (_right_hand_urdf_xml_string,true,unique_hand_name));
    }

     std::string _left_foot_urdf_xml_string,_right_foot_urdf_xml_string;
    if(!load_foot_urdfs(_left_foot_urdf_xml_string,_right_foot_urdf_xml_string))
       cerr << "\n Foot Urdfs Not Found" << endl;
    else{
        string unique_foot_name = "lfoot_local_copy";
       _gl_left_foot = shared_ptr<InteractableGlKinematicBody>(new InteractableGlKinematicBody (_left_foot_urdf_xml_string,true,unique_foot_name));
       unique_foot_name = "rfoot_local_copy";
       _gl_right_foot = shared_ptr<InteractableGlKinematicBody>(new InteractableGlKinematicBody (_right_foot_urdf_xml_string,true,unique_foot_name));
    }

    _last_plan_msg_timestamp = bot_timestamp_now(); //initialize
  }

  RobotPlanListener::~RobotPlanListener() {
   // _collision_detector->clear_collision_objects();
  }

  //=============message callbacks

void RobotPlanListener::handleRobotPlanMsg(const lcm::ReceiveBuffer* rbuf,
	const string& chan, const drc::robot_plan_t* msg)
  {
    //cout << "\n received robot plan message\n";
    _plan_paused = false;
    if (!_urdf_parsed){
      cout << "\n handleRobotPlanMsg: Waiting for urdf to be parsed" << endl;
      return;
    }
    if(_urdf_subscription_on){
      cout << "\n handleRobotPlanMsg: unsubscribing from _urdf_subscription" << endl;
      _lcm->unsubscribe(_urdf_subscription);     //unsubscribe from urdf messages
      _urdf_subscription_on =  false;
    }
    activate_crawling_plan();

    // 0. Make Local copy to later output
    _received_plan = *msg;

    int num_states = 0;
    int inc = 1;

    /*
    int max_num_states = 20;
    if (msg->num_states > max_num_states) {
      inc = ceil(msg->num_states/max_num_states);
      inc = min(max(inc,1),max_num_states);
      num_states = max_num_states;
    }else{
      num_states = msg->num_states;
      }
    */
      num_states = msg->num_states;

    //clear stored data
    _gl_robot_list.clear();

    //cout << "a\n";
    int count=msg->num_states-1; // always display the last state in the plan
    for (uint i = 0; i <(uint)num_states; i++){
      drc::robot_state_t state_msg  = msg->plan[count];
      std::stringstream oss;
      oss << _robot_name << "_"<< count;
      shared_ptr<InteractableGlKinematicBody> new_object_ptr(new InteractableGlKinematicBody(*_base_gl_robot,true,oss.str()));
      _gl_robot_list.insert(_gl_robot_list.begin(),new_object_ptr);
      _gl_robot_list[0]->set_state(state_msg);
      count-=inc;
    }//end for num of states in robot_plan msg;
    //	cout << "b\n";

    _last_plan_msg_timestamp = bot_timestamp_now(); //initialize
    bot_viewer_request_redraw(_viewer);
  } // end handleMessage

  //-------------------------------------------------------------------

 void RobotPlanListener::handleRobotUrdfMsg(const lcm::ReceiveBuffer* rbuf, const string& channel,
					       const  drc::robot_urdf_t* msg)
  {

    if(_urdf_parsed ==false)
    {
     // Received robot urdf string. Store it internally and get all available joints.
      cout<< "\nurdf handler @ RobotPlanListener" << endl;
    _robot_name      = msg->robot_name;
    _urdf_xml_string = msg->urdf_xml_string;
    cout<< "\nReceived urdf_xml_string of robot ["
	<< msg->robot_name << "], storing it internally as a param" << endl;

	  //bot_gtk_gl_drawing_area_set_context(this->_viewer->gl_area); // Prevents conflict with cam renderer which messes with the gl context
    _base_gl_robot = shared_ptr<GlKinematicBody>(new GlKinematicBody(_urdf_xml_string));
    cout<< "Number of Joints: " << _base_gl_robot->get_num_joints() <<endl;

    //remember that we've parsed the urdf already
    _urdf_parsed = true;

    }//  if(_urdf_parsed ==false)

  }

  //-------------------------------------------------------------------

  void RobotPlanListener::handleAprvWalkingGoalMsg(const lcm::ReceiveBuffer* rbuf,
						 const string& chan,
						 const drc::walking_goal_t* msg)
  {
		_received_walking_goal = *msg;
    _aprvd_walking_goal_in_cache = true;
     purge_current_plan();
  }

  void RobotPlanListener::handleControllerStatusMsg(const lcm::ReceiveBuffer* rbuf,
                                                 const string& chan,
                                                 const drc::controller_status_t* msg)
  {
     _controller_utime = msg->controller_utime;
     _controller_status = msg->state;
  }

    //-------------------------------------------------------------------

  void RobotPlanListener::commit_walking_goal(int64_t utime,std::string &channel)
  {
    drc::walking_goal_t msg = _received_walking_goal;
    msg.utime = utime;
    _lcm->publish(channel, &msg);
    _aprvd_walking_goal_in_cache = false; //clear flag on commit
  }

  void RobotPlanListener::commit_plan_control(int64_t utime, std::string &channel,bool pause, bool terminate)
  {

    drc::plan_control_t  msg;
    msg.utime = utime;
    if((pause)&&(!terminate)){
      msg.control = msg.PAUSE;
      _plan_paused = true;
    }
    else if((!pause)&&(!terminate)){
      msg.control = msg.UNPAUSE;
      _plan_paused = false;
    }
    else{
       msg.control = msg.TERMINATE;
       _plan_paused = false;
    }
    _lcm->publish(channel, &msg);
  }

  bool RobotPlanListener::load_hand_urdfs(std::string &_left_hand_urdf_xml_string,std::string &_right_hand_urdf_xml_string)
  {

    string urdf_models_path = string(getModelsPath()) + "/mit_gazebo_models/mit_robot_hands/";

    vector<string> urdf_files = vector<string>();
    get_URDF_filenames_from_dir(urdf_models_path.c_str(),urdf_files);

    std::string filename, ext;

    filename ="sandia_hand_left";
    ext=".urdf";

    std::vector<std::string>::const_iterator found;
    found = std::find(urdf_files.begin(),urdf_files.end(), filename);
    if (found != urdf_files.end()) {
      std::stringstream oss;
      oss << urdf_models_path  << filename << ext;
      get_xmlstring_from_file(oss.str(),_left_hand_urdf_xml_string);
    }
    else{
      return false;
    }

    filename ="sandia_hand_right";
    ext=".urdf";

    if (found != urdf_files.end()) {
      std::stringstream oss;
      oss << urdf_models_path  << filename << ext;
      get_xmlstring_from_file(oss.str(),_right_hand_urdf_xml_string);
    }
    else{
      return false;
    }

     return true;
  }

  bool RobotPlanListener::load_foot_urdfs(std::string &_left_foot_urdf_xml_string,std::string &_right_foot_urdf_xml_string)
  {

    string urdf_models_path = string(getModelsPath()) + "/mit_gazebo_models/mit_robot_feet/";

    vector<string> urdf_files = vector<string>();
    get_URDF_filenames_from_dir(urdf_models_path.c_str(),urdf_files);

    std::string filename, ext;

    filename ="l_foot";
    ext=".urdf";

    std::vector<std::string>::const_iterator found;
    found = std::find(urdf_files.begin(),urdf_files.end(), filename);
    if (found != urdf_files.end()) {
      std::stringstream oss;
      oss << urdf_models_path  << filename << ext;
      get_xmlstring_from_file(oss.str(),_left_foot_urdf_xml_string);
    }
    else{
      return false;
    }

    filename ="r_foot";
    ext=".urdf";

    if (found != urdf_files.end()) {
      std::stringstream oss;
      oss << urdf_models_path  << filename << ext;
      get_xmlstring_from_file(oss.str(),_right_foot_urdf_xml_string);
    }
    else{
      return false;
    }

     return true;
  }

} //namespace renderer_crawling_plan

<|endoftext|>


<commit_before>//===-- CppModuleConfiguration.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "CppModuleConfiguration.h"

#include "ClangHost.h"
#include "lldb/Host/FileSystem.h"

using namespace lldb_private;

bool CppModuleConfiguration::SetOncePath::TrySet(llvm::StringRef path) {
  // Setting for the first time always works.
  if (m_first) {
    m_path = path.str();
    m_valid = true;
    m_first = false;
    return true;
  }
  // Changing the path to the same value is fine.
  if (m_path == path)
    return true;

  // Changing the path after it was already set is not allowed.
  m_valid = false;
  return false;
}

bool CppModuleConfiguration::analyzeFile(const FileSpec &f) {
  using namespace llvm::sys::path;
  // Convert to slashes to make following operations simpler.
  std::string dir_buffer = convert_to_slash(f.GetDirectory().GetStringRef());
  llvm::StringRef posix_dir(dir_buffer);

  // Check for /c++/vX/ that is used by libc++.
  static llvm::Regex libcpp_regex(R"regex(/c[+][+]/v[0-9]/)regex");
  if (libcpp_regex.match(f.GetPath())) {
    // Strip away libc++'s /experimental directory if there is one.
    posix_dir.consume_back("/experimental");
    return m_std_inc.TrySet(posix_dir);
  }

  // Check for /usr/include. On Linux this might be /usr/include/bits, so
  // we should remove that '/bits' suffix to get the actual include directory.
  if (posix_dir.endswith("/usr/include/bits"))
    posix_dir.consume_back("/bits");
  if (posix_dir.endswith("/usr/include"))
    return m_c_inc.TrySet(posix_dir);

  // File wasn't interesting, continue analyzing.
  return true;
}

bool CppModuleConfiguration::hasValidConfig() {
  // We all these include directories to have a valid usable configuration.
  return m_c_inc.Valid() && m_std_inc.Valid();
}

CppModuleConfiguration::CppModuleConfiguration(
    const FileSpecList &support_files) {
  // Analyze all files we were given to build the configuration.
  bool error = !std::all_of(support_files.begin(), support_files.end(),
                            std::bind(&CppModuleConfiguration::analyzeFile,
                                      this, std::placeholders::_1));
  // If we have a valid configuration at this point, set the
  // include directories and module list that should be used.
  if (!error && hasValidConfig()) {
    // Calculate the resource directory for LLDB.
    llvm::SmallString<256> resource_dir;
    llvm::sys::path::append(resource_dir, GetClangResourceDir().GetPath(),
                            "include");
    m_resource_inc = resource_dir.str();

    // This order matches the way Clang orders these directories.
    m_include_dirs = {m_std_inc.Get(), m_resource_inc, m_c_inc.Get()};
    m_imported_modules = {"std"};
  }
}
<commit_msg>[lldb][NFC] Use llvm::all_of instead of std::all_of in CppModuleConfiguration<commit_after>//===-- CppModuleConfiguration.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "CppModuleConfiguration.h"

#include "ClangHost.h"
#include "lldb/Host/FileSystem.h"

using namespace lldb_private;

bool CppModuleConfiguration::SetOncePath::TrySet(llvm::StringRef path) {
  // Setting for the first time always works.
  if (m_first) {
    m_path = path.str();
    m_valid = true;
    m_first = false;
    return true;
  }
  // Changing the path to the same value is fine.
  if (m_path == path)
    return true;

  // Changing the path after it was already set is not allowed.
  m_valid = false;
  return false;
}

bool CppModuleConfiguration::analyzeFile(const FileSpec &f) {
  using namespace llvm::sys::path;
  // Convert to slashes to make following operations simpler.
  std::string dir_buffer = convert_to_slash(f.GetDirectory().GetStringRef());
  llvm::StringRef posix_dir(dir_buffer);

  // Check for /c++/vX/ that is used by libc++.
  static llvm::Regex libcpp_regex(R"regex(/c[+][+]/v[0-9]/)regex");
  if (libcpp_regex.match(f.GetPath())) {
    // Strip away libc++'s /experimental directory if there is one.
    posix_dir.consume_back("/experimental");
    return m_std_inc.TrySet(posix_dir);
  }

  // Check for /usr/include. On Linux this might be /usr/include/bits, so
  // we should remove that '/bits' suffix to get the actual include directory.
  if (posix_dir.endswith("/usr/include/bits"))
    posix_dir.consume_back("/bits");
  if (posix_dir.endswith("/usr/include"))
    return m_c_inc.TrySet(posix_dir);

  // File wasn't interesting, continue analyzing.
  return true;
}

bool CppModuleConfiguration::hasValidConfig() {
  // We all these include directories to have a valid usable configuration.
  return m_c_inc.Valid() && m_std_inc.Valid();
}

CppModuleConfiguration::CppModuleConfiguration(
    const FileSpecList &support_files) {
  // Analyze all files we were given to build the configuration.
  bool error = !llvm::all_of(support_files,
                             std::bind(&CppModuleConfiguration::analyzeFile,
                                       this, std::placeholders::_1));
  // If we have a valid configuration at this point, set the
  // include directories and module list that should be used.
  if (!error && hasValidConfig()) {
    // Calculate the resource directory for LLDB.
    llvm::SmallString<256> resource_dir;
    llvm::sys::path::append(resource_dir, GetClangResourceDir().GetPath(),
                            "include");
    m_resource_inc = resource_dir.str();

    // This order matches the way Clang orders these directories.
    m_include_dirs = {m_std_inc.Get(), m_resource_inc, m_c_inc.Get()};
    m_imported_modules = {"std"};
  }
}
<|endoftext|>


<commit_before><commit_msg>Completed aligner_dp.<commit_after><|endoftext|>


<commit_before><commit_msg>Added warning<commit_after><|endoftext|>


<commit_before>#include "effectswidgets.h"
#include <QPainter>
#include <QTimer>
#include <QEvent>
#include <QApplication>
using namespace GUtil::QtControls::EffectsWidgets;

FaderWidget::FaderWidget(QWidget *par, bool fade_in, int fade_duration, int start_delay)
    : QWidget(par)
{
    if (par)
        color = par->palette().window().color();
    else
        color = Qt::white;

    _fade_in = fade_in;

    duration = fade_duration;
    delay = start_delay;

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()),
            this, SLOT(update()));

    setAttribute(Qt::WA_DeleteOnClose);

    // We want to intercept resize event so we can adjust our size
    par->installEventFilter(this);

    show();

    if(_fade_in)
    {
        currentAlpha = 255;
        ((QWidget *)parent())->hide();
    }
    else
    {
        currentAlpha = 0;
        ((QWidget *)parent())->show();
    }
}

bool FaderWidget::eventFilter(QObject *obj, QEvent *ev)
{
    bool ret = false;

    if(ev->type() == QEvent::Resize)
    {
        resize(((QWidget *)obj)->size());
        ret = true;
    }

    return ret;
}

QColor FaderWidget::fadeColor() const
{
    return color;
}

void FaderWidget::setFadeColor(const QColor &newColor)
{
    color = newColor;
}

int FaderWidget::fadeDuration() const
{
    return duration;
}

void FaderWidget::setFadeDuration(int milliseconds)
{
    duration = milliseconds;
}

bool FaderWidget::willFadeIn()
{
    return _fade_in;
}

void FaderWidget::setWillFadeIn(bool val)
{
    _fade_in = val;
}

void FaderWidget::startFading()
{
    if(timer->isActive())
    {
        // don't allow to fade while it's in the middle of fading
        return;
    }

    if(_fade_in)
        currentAlpha = 255;
    else
        currentAlpha = 0;

    // Make sure the parent is in the correct state before we fade it
    if(_fade_in)
        ((QWidget *)parent())->hide();
    else
        ((QWidget *)parent())->show();

    update();

    // Fade after a certain delay
    QTimer::singleShot(delay, this, SLOT(_start()));
}

void FaderWidget::_start()
{
    if(_fade_in)
        ((QWidget *)parent())->show();

    timer->start(30);
}

void FaderWidget::paintEvent(QPaintEvent * /* event */)
{
    QPainter painter(this);
    QColor semiTransparentColor = color;
    semiTransparentColor.setAlpha(currentAlpha);

    painter.fillRect(rect(), semiTransparentColor);

    if(timer->isActive())
    {
        if(_fade_in)
        {
            currentAlpha -= (255 * timer->interval()) / duration;
            if (currentAlpha <= 0)
            {
                timer->stop();
                currentAlpha = 0;

                emit doneFading(true);
            }
        }
        else
        {
            currentAlpha += (255 * timer->interval()) / duration;
            if (currentAlpha >= 255)
            {
                timer->stop();
                currentAlpha = 255;

                // Hide the parent once we're faded out
                ((QWidget *)parent())->hide();

                emit doneFading(false);
            }
        }
    }
}

void FaderWidget::fadeIn()
{
    _fade_in = true;
    startFading();
}

void FaderWidget::fadeOut()
{
    _fade_in = false;
    startFading();
}

void FaderWidget::toggleFade()
{
    _fade_in = !_fade_in;
    startFading();
}
<commit_msg>Fixed the fader widget so it hides after fading, relinquishing control back to the parent widget<commit_after>#include "effectswidgets.h"
#include <QPainter>
#include <QTimer>
#include <QEvent>
#include <QApplication>
using namespace GUtil::QtControls::EffectsWidgets;

FaderWidget::FaderWidget(QWidget *par, bool fade_in, int fade_duration, int start_delay)
    : QWidget(par)
{
    if (par)
        color = par->palette().window().color();
    else
        color = Qt::white;

    _fade_in = fade_in;

    duration = fade_duration;
    delay = start_delay;

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()),
            this, SLOT(update()));

    setAttribute(Qt::WA_DeleteOnClose);

    // We want to intercept resize event so we can adjust our size
    par->installEventFilter(this);

    show();

    if(_fade_in)
    {
        currentAlpha = 255;
        ((QWidget *)parent())->hide();
    }
    else
    {
        currentAlpha = 0;
        ((QWidget *)parent())->show();
    }
}

bool FaderWidget::eventFilter(QObject *obj, QEvent *ev)
{
    bool ret = false;

    if(ev->type() == QEvent::Resize)
    {
        resize(((QWidget *)obj)->size());
        ret = true;
    }

    return ret;
}

QColor FaderWidget::fadeColor() const
{
    return color;
}

void FaderWidget::setFadeColor(const QColor &newColor)
{
    color = newColor;
}

int FaderWidget::fadeDuration() const
{
    return duration;
}

void FaderWidget::setFadeDuration(int milliseconds)
{
    duration = milliseconds;
}

bool FaderWidget::willFadeIn()
{
    return _fade_in;
}

void FaderWidget::setWillFadeIn(bool val)
{
    _fade_in = val;
}

void FaderWidget::startFading()
{
    if(timer->isActive())
    {
        // don't allow to fade while it's in the middle of fading
        return;
    }

    if(_fade_in)
        currentAlpha = 255;
    else
        currentAlpha = 0;

    // Make sure the parent is in the correct state before we fade it
    if(_fade_in)
        ((QWidget *)parent())->hide();
    else
        ((QWidget *)parent())->show();

    show();
    update();

    // Fade after a certain delay
    QTimer::singleShot(delay, this, SLOT(_start()));
}

void FaderWidget::_start()
{
    if(_fade_in)
        ((QWidget *)parent())->show();

    timer->start(30);
}

void FaderWidget::paintEvent(QPaintEvent * /* event */)
{
    QPainter painter(this);
    QColor semiTransparentColor = color;
    semiTransparentColor.setAlpha(currentAlpha);

    painter.fillRect(rect(), semiTransparentColor);

    if(timer->isActive())
    {
        if(_fade_in)
        {
            currentAlpha -= (255 * timer->interval()) / duration;
            if (currentAlpha <= 0)
            {
                timer->stop();
                currentAlpha = 0;

                hide();

                emit doneFading(true);
            }
        }
        else
        {
            currentAlpha += (255 * timer->interval()) / duration;
            if (currentAlpha >= 255)
            {
                timer->stop();
                currentAlpha = 255;

                // Hide the parent once we're faded out
                ((QWidget *)parent())->hide();

                hide();

                emit doneFading(false);
            }
        }
    }
}

void FaderWidget::fadeIn()
{
    _fade_in = true;
    startFading();
}

void FaderWidget::fadeOut()
{
    _fade_in = false;
    startFading();
}

void FaderWidget::toggleFade()
{
    _fade_in = !_fade_in;
    startFading();
}
<|endoftext|>


<commit_before>/* This is free and unencumbered software released into the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "mode.h"

#include <sys/types.h> /* for mode_t */

using namespace posix;

static_assert(sizeof(mode_t) == sizeof(mode), "sizeof(mode_t) != sizeof(mode)");
<commit_msg>Fixed a sizeof(posix::mode) static assertion failure on Darwin.<commit_after>/* This is free and unencumbered software released into the public domain. */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "mode.h"

#include <sys/types.h> /* for mode_t */

using namespace posix;

/*
 * x86-64 Linux 3.x:   uint32_t.
 * x86-64 Darwin 11.x: uint16_t.
 */
static_assert(sizeof(mode_t) <= sizeof(mode), "sizeof(mode_t) > sizeof(mode)");
<|endoftext|>