Merge clang-format from core

This commit is contained in:
Jesse Beder
2014-03-22 13:03:18 -05:00
72 changed files with 20508 additions and 20365 deletions

View File

@@ -1,14 +1,15 @@
#ifndef ANCHOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef ANCHOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define ANCHOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define ANCHOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <cstddef> #include <cstddef>
namespace YAML namespace YAML {
{
typedef std::size_t anchor_t; typedef std::size_t anchor_t;
const anchor_t NullAnchor = 0; const anchor_t NullAnchor = 0;
} }

View File

@@ -1,26 +1,30 @@
#ifndef BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define BASE64_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <string> #include <string>
#include <vector> #include <vector>
namespace YAML namespace YAML {
{
std::string EncodeBase64(const unsigned char *data, std::size_t size); std::string EncodeBase64(const unsigned char *data, std::size_t size);
std::vector<unsigned char> DecodeBase64(const std::string &input); std::vector<unsigned char> DecodeBase64(const std::string &input);
class Binary { class Binary {
public: public:
Binary() : m_unownedData(0), m_unownedSize(0) {} Binary() : m_unownedData(0), m_unownedSize(0) {}
Binary(const unsigned char *data_, std::size_t size_): m_unownedData(data_), m_unownedSize(size_) {} Binary(const unsigned char *data_, std::size_t size_)
: m_unownedData(data_), m_unownedSize(size_) {}
bool owned() const { return !m_unownedData; } bool owned() const { return !m_unownedData; }
std::size_t size() const { return owned() ? m_data.size() : m_unownedSize; } std::size_t size() const { return owned() ? m_data.size() : m_unownedSize; }
const unsigned char *data() const { return owned() ? &m_data[0] : m_unownedData; } const unsigned char *data() const {
return owned() ? &m_data[0] : m_unownedData;
}
void swap(std::vector<unsigned char> &rhs) { void swap(std::vector<unsigned char> &rhs) {
if (m_unownedData) { if (m_unownedData) {
@@ -48,9 +52,7 @@ namespace YAML
return true; return true;
} }
bool operator != (const Binary& rhs) const { bool operator!=(const Binary &rhs) const { return !(*this == rhs); }
return !(*this == rhs);
}
private: private:
std::vector<unsigned char> m_data; std::vector<unsigned char> m_data;

View File

@@ -1,7 +1,9 @@
#ifndef ANCHORDICT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef ANCHORDICT_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define ANCHORDICT_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define ANCHORDICT_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
@@ -9,30 +11,23 @@
#include "../anchor.h" #include "../anchor.h"
namespace YAML namespace YAML {
{
/// AnchorDict /// AnchorDict
/// . An object that stores and retrieves values correlating to anchor_t /// . An object that stores and retrieves values correlating to anchor_t
/// values. /// values.
/// . Efficient implementation that can make assumptions about how anchor_t /// . Efficient implementation that can make assumptions about how anchor_t
/// values are assigned by the Parser class. /// values are assigned by the Parser class.
template <class T> template <class T>
class AnchorDict class AnchorDict {
{
public: public:
void Register(anchor_t anchor, T value) void Register(anchor_t anchor, T value) {
{ if (anchor > m_data.size()) {
if (anchor > m_data.size())
{
m_data.resize(anchor); m_data.resize(anchor);
} }
m_data[anchor - 1] = value; m_data[anchor - 1] = value;
} }
T Get(anchor_t anchor) const T Get(anchor_t anchor) const { return m_data[anchor - 1]; }
{
return m_data[anchor - 1];
}
private: private:
std::vector<T> m_data; std::vector<T> m_data;

View File

@@ -1,49 +1,59 @@
#ifndef GRAPHBUILDER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef GRAPHBUILDER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define GRAPHBUILDER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define GRAPHBUILDER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/mark.h" #include "yaml-cpp/mark.h"
#include <string> #include <string>
namespace YAML namespace YAML {
{
class Parser; class Parser;
// GraphBuilderInterface // GraphBuilderInterface
// . Abstraction of node creation // . Abstraction of node creation
// . pParentNode is always NULL or the return value of one of the NewXXX() // . pParentNode is always NULL or the return value of one of the NewXXX()
// functions. // functions.
class GraphBuilderInterface class GraphBuilderInterface {
{
public: public:
// Create and return a new node with a null value. // Create and return a new node with a null value.
virtual void *NewNull(const Mark &mark, void *pParentNode) = 0; virtual void *NewNull(const Mark &mark, void *pParentNode) = 0;
// Create and return a new node with the given tag and value. // Create and return a new node with the given tag and value.
virtual void *NewScalar(const Mark& mark, const std::string& tag, void *pParentNode, const std::string& value) = 0; virtual void *NewScalar(const Mark &mark, const std::string &tag,
void *pParentNode, const std::string &value) = 0;
// Create and return a new sequence node // Create and return a new sequence node
virtual void *NewSequence(const Mark& mark, const std::string& tag, void *pParentNode) = 0; virtual void *NewSequence(const Mark &mark, const std::string &tag,
void *pParentNode) = 0;
// Add pNode to pSequence. pNode was created with one of the NewXxx() // Add pNode to pSequence. pNode was created with one of the NewXxx()
// functions and pSequence with NewSequence(). // functions and pSequence with NewSequence().
virtual void AppendToSequence(void *pSequence, void *pNode) = 0; virtual void AppendToSequence(void *pSequence, void *pNode) = 0;
// Note that no moew entries will be added to pSequence // Note that no moew entries will be added to pSequence
virtual void SequenceComplete(void *pSequence) { (void)pSequence; } virtual void SequenceComplete(void *pSequence) { (void)pSequence; }
// Create and return a new map node // Create and return a new map node
virtual void *NewMap(const Mark& mark, const std::string& tag, void *pParentNode) = 0; virtual void *NewMap(const Mark &mark, const std::string &tag,
void *pParentNode) = 0;
// Add the pKeyNode => pValueNode mapping to pMap. pKeyNode and pValueNode // Add the pKeyNode => pValueNode mapping to pMap. pKeyNode and pValueNode
// were created with one of the NewXxx() methods and pMap with NewMap(). // were created with one of the NewXxx() methods and pMap with NewMap().
virtual void AssignInMap(void *pMap, void *pKeyNode, void *pValueNode) = 0; virtual void AssignInMap(void *pMap, void *pKeyNode, void *pValueNode) = 0;
// Note that no more assignments will be made in pMap // Note that no more assignments will be made in pMap
virtual void MapComplete(void *pMap) { (void)pMap; } virtual void MapComplete(void *pMap) { (void)pMap; }
// Return the node that should be used in place of an alias referencing // Return the node that should be used in place of an alias referencing
// pNode (pNode by default) // pNode (pNode by default)
virtual void *AnchorReference(const Mark& mark, void *pNode) {(void)mark; return pNode;} virtual void *AnchorReference(const Mark &mark, void *pNode) {
(void)mark;
return pNode;
}
}; };
// Typesafe wrapper for GraphBuilderInterface. Assumes that Impl defines // Typesafe wrapper for GraphBuilderInterface. Assumes that Impl defines
@@ -54,15 +64,13 @@ namespace YAML
// prototypes changed to accept an explicit Node*, Sequence*, or Map* where // prototypes changed to accept an explicit Node*, Sequence*, or Map* where
// appropriate. // appropriate.
template <class Impl> template <class Impl>
class GraphBuilder : public GraphBuilderInterface class GraphBuilder : public GraphBuilderInterface {
{
public: public:
typedef typename Impl::Node Node; typedef typename Impl::Node Node;
typedef typename Impl::Sequence Sequence; typedef typename Impl::Sequence Sequence;
typedef typename Impl::Map Map; typedef typename Impl::Map Map;
GraphBuilder(Impl& impl) : m_impl(impl) GraphBuilder(Impl &impl) : m_impl(impl) {
{
Map *pMap = NULL; Map *pMap = NULL;
Sequence *pSeq = NULL; Sequence *pSeq = NULL;
Node *pNode = NULL; Node *pNode = NULL;
@@ -78,12 +86,16 @@ namespace YAML
return CheckType<Node>(m_impl.NewNull(mark, AsNode(pParentNode))); return CheckType<Node>(m_impl.NewNull(mark, AsNode(pParentNode)));
} }
virtual void *NewScalar(const Mark& mark, const std::string& tag, void *pParentNode, const std::string& value) { virtual void *NewScalar(const Mark &mark, const std::string &tag,
return CheckType<Node>(m_impl.NewScalar(mark, tag, AsNode(pParentNode), value)); void *pParentNode, const std::string &value) {
return CheckType<Node>(
m_impl.NewScalar(mark, tag, AsNode(pParentNode), value));
} }
virtual void *NewSequence(const Mark& mark, const std::string& tag, void *pParentNode) { virtual void *NewSequence(const Mark &mark, const std::string &tag,
return CheckType<Sequence>(m_impl.NewSequence(mark, tag, AsNode(pParentNode))); void *pParentNode) {
return CheckType<Sequence>(
m_impl.NewSequence(mark, tag, AsNode(pParentNode)));
} }
virtual void AppendToSequence(void *pSequence, void *pNode) { virtual void AppendToSequence(void *pSequence, void *pNode) {
m_impl.AppendToSequence(AsSequence(pSequence), AsNode(pNode)); m_impl.AppendToSequence(AsSequence(pSequence), AsNode(pNode));
@@ -92,15 +104,14 @@ namespace YAML
m_impl.SequenceComplete(AsSequence(pSequence)); m_impl.SequenceComplete(AsSequence(pSequence));
} }
virtual void *NewMap(const Mark& mark, const std::string& tag, void *pParentNode) { virtual void *NewMap(const Mark &mark, const std::string &tag,
void *pParentNode) {
return CheckType<Map>(m_impl.NewMap(mark, tag, AsNode(pParentNode))); return CheckType<Map>(m_impl.NewMap(mark, tag, AsNode(pParentNode)));
} }
virtual void AssignInMap(void *pMap, void *pKeyNode, void *pValueNode) { virtual void AssignInMap(void *pMap, void *pKeyNode, void *pValueNode) {
m_impl.AssignInMap(AsMap(pMap), AsNode(pKeyNode), AsNode(pValueNode)); m_impl.AssignInMap(AsMap(pMap), AsNode(pKeyNode), AsNode(pValueNode));
} }
virtual void MapComplete(void *pMap) { virtual void MapComplete(void *pMap) { m_impl.MapComplete(AsMap(pMap)); }
m_impl.MapComplete(AsMap(pMap));
}
virtual void *AnchorReference(const Mark &mark, void *pNode) { virtual void *AnchorReference(const Mark &mark, void *pNode) {
return CheckType<Node>(m_impl.AnchorReference(mark, AsNode(pNode))); return CheckType<Node>(m_impl.AnchorReference(mark, AsNode(pNode)));
@@ -111,22 +122,25 @@ namespace YAML
// Static check for pointer to T // Static check for pointer to T
template <class T, class U> template <class T, class U>
static T* CheckType(U* p) {return p;} static T *CheckType(U *p) {
return p;
}
static Node *AsNode(void *pNode) { return static_cast<Node *>(pNode); } static Node *AsNode(void *pNode) { return static_cast<Node *>(pNode); }
static Sequence *AsSequence(void *pSeq) {return static_cast<Sequence*>(pSeq);} static Sequence *AsSequence(void *pSeq) {
return static_cast<Sequence *>(pSeq);
}
static Map *AsMap(void *pMap) { return static_cast<Map *>(pMap); } static Map *AsMap(void *pMap) { return static_cast<Map *>(pMap); }
}; };
void *BuildGraphOfNextDocument(Parser& parser, GraphBuilderInterface& graphBuilder); void *BuildGraphOfNextDocument(Parser &parser,
GraphBuilderInterface &graphBuilder);
template <class Impl> template <class Impl>
typename Impl::Node *BuildGraphOfNextDocument(Parser& parser, Impl& impl) typename Impl::Node *BuildGraphOfNextDocument(Parser &parser, Impl &impl) {
{
GraphBuilder<Impl> graphBuilder(impl); GraphBuilder<Impl> graphBuilder(impl);
return static_cast<typename Impl::Node *>(BuildGraphOfNextDocument( return static_cast<typename Impl::Node *>(
parser, graphBuilder BuildGraphOfNextDocument(parser, graphBuilder));
));
} }
} }

View File

@@ -1,20 +1,29 @@
#ifndef DLL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef DLL_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define DLL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define DLL_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
// The following ifdef block is the standard way of creating macros which make exporting // The following ifdef block is the standard way of creating macros which make
// from a DLL simpler. All files within this DLL are compiled with the yaml_cpp_EXPORTS // exporting
// symbol defined on the command line. this symbol should not be defined on any project // from a DLL simpler. All files within this DLL are compiled with the
// that uses this DLL. This way any other project whose source files include this file see // yaml_cpp_EXPORTS
// YAML_CPP_API functions as being imported from a DLL, whereas this DLL sees symbols // symbol defined on the command line. this symbol should not be defined on any
// project
// that uses this DLL. This way any other project whose source files include
// this file see
// YAML_CPP_API functions as being imported from a DLL, whereas this DLL sees
// symbols
// defined with this macro as being exported. // defined with this macro as being exported.
#undef YAML_CPP_API #undef YAML_CPP_API
#ifdef YAML_CPP_DLL // Using or Building YAML-CPP DLL (definition defined manually) #ifdef YAML_CPP_DLL // Using or Building YAML-CPP DLL (definition defined
#ifdef yaml_cpp_EXPORTS // Building YAML-CPP DLL (definition created by CMake or defined manually) // manually)
#ifdef yaml_cpp_EXPORTS // Building YAML-CPP DLL (definition created by CMake
// or defined manually)
// #pragma message( "Defining YAML_CPP_API for DLL export" ) // #pragma message( "Defining YAML_CPP_API for DLL export" )
#define YAML_CPP_API __declspec(dllexport) #define YAML_CPP_API __declspec(dllexport)
#else // yaml_cpp_EXPORTS #else // yaml_cpp_EXPORTS

View File

@@ -1,19 +1,19 @@
#ifndef EMITFROMEVENTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef EMITFROMEVENTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define EMITFROMEVENTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define EMITFROMEVENTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/eventhandler.h" #include "yaml-cpp/eventhandler.h"
#include <stack> #include <stack>
namespace YAML namespace YAML {
{
class Emitter; class Emitter;
class EmitFromEvents: public EventHandler class EmitFromEvents : public EventHandler {
{
public: public:
EmitFromEvents(Emitter& emitter); EmitFromEvents(Emitter& emitter);
@@ -22,12 +22,15 @@ namespace YAML
virtual void OnNull(const Mark& mark, anchor_t anchor); virtual void OnNull(const Mark& mark, anchor_t anchor);
virtual void OnAlias(const Mark& mark, anchor_t anchor); virtual void OnAlias(const Mark& mark, anchor_t anchor);
virtual void OnScalar(const Mark& mark, const std::string& tag, anchor_t anchor, const std::string& value); virtual void OnScalar(const Mark& mark, const std::string& tag,
anchor_t anchor, const std::string& value);
virtual void OnSequenceStart(const Mark& mark, const std::string& tag, anchor_t anchor); virtual void OnSequenceStart(const Mark& mark, const std::string& tag,
anchor_t anchor);
virtual void OnSequenceEnd(); virtual void OnSequenceEnd();
virtual void OnMapStart(const Mark& mark, const std::string& tag, anchor_t anchor); virtual void OnMapStart(const Mark& mark, const std::string& tag,
anchor_t anchor);
virtual void OnMapEnd(); virtual void OnMapEnd();
private: private:
@@ -37,7 +40,13 @@ namespace YAML
private: private:
Emitter& m_emitter; Emitter& m_emitter;
struct State { enum value { WaitingForSequenceEntry, WaitingForKey, WaitingForValue }; }; struct State {
enum value {
WaitingForSequenceEntry,
WaitingForKey,
WaitingForValue
};
};
std::stack<State::value> m_stateStack; std::stack<State::value> m_stateStack;
}; };
} }

View File

@@ -1,11 +1,12 @@
#ifndef EMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef EMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define EMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define EMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/dll.h" #include "yaml-cpp/dll.h"
#include "yaml-cpp/binary.h" #include "yaml-cpp/binary.h"
#include "yaml-cpp/emitterdef.h" #include "yaml-cpp/emitterdef.h"
@@ -17,12 +18,10 @@
#include <string> #include <string>
#include <sstream> #include <sstream>
namespace YAML namespace YAML {
{
class EmitterState; class EmitterState;
class YAML_CPP_API Emitter: private noncopyable class YAML_CPP_API Emitter : private noncopyable {
{
public: public:
Emitter(); Emitter();
explicit Emitter(std::ostream& stream); explicit Emitter(std::ostream& stream);
@@ -72,7 +71,8 @@ namespace YAML
Emitter& WriteStreamable(T value); Emitter& WriteStreamable(T value);
private: private:
template<typename T> void SetStreamablePrecision(std::stringstream&) {} template <typename T>
void SetStreamablePrecision(std::stringstream&) {}
unsigned GetFloatPrecision() const; unsigned GetFloatPrecision() const;
unsigned GetDoublePrecision() const; unsigned GetDoublePrecision() const;
@@ -120,8 +120,7 @@ namespace YAML
}; };
template <typename T> template <typename T>
inline Emitter& Emitter::WriteIntegralType(T value) inline Emitter& Emitter::WriteIntegralType(T value) {
{
if (!good()) if (!good())
return *this; return *this;
@@ -138,8 +137,7 @@ namespace YAML
} }
template <typename T> template <typename T>
inline Emitter& Emitter::WriteStreamable(T value) inline Emitter& Emitter::WriteStreamable(T value) {
{
if (!good()) if (!good())
return *this; return *this;
@@ -156,42 +154,82 @@ namespace YAML
} }
template <> template <>
inline void Emitter::SetStreamablePrecision<float>(std::stringstream& stream) inline void Emitter::SetStreamablePrecision<float>(std::stringstream& stream) {
{
stream.precision(GetFloatPrecision()); stream.precision(GetFloatPrecision());
} }
template <> template <>
inline void Emitter::SetStreamablePrecision<double>(std::stringstream& stream) inline void Emitter::SetStreamablePrecision<double>(std::stringstream& stream) {
{
stream.precision(GetDoublePrecision()); stream.precision(GetDoublePrecision());
} }
// overloads of insertion // overloads of insertion
inline Emitter& operator << (Emitter& emitter, const std::string& v) { return emitter.Write(v); } inline Emitter& operator<<(Emitter& emitter, const std::string& v) {
inline Emitter& operator << (Emitter& emitter, bool v) { return emitter.Write(v); } return emitter.Write(v);
inline Emitter& operator << (Emitter& emitter, char v) { return emitter.Write(v); } }
inline Emitter& operator << (Emitter& emitter, unsigned char v) { return emitter.Write(static_cast<char>(v)); } inline Emitter& operator<<(Emitter& emitter, bool v) {
inline Emitter& operator << (Emitter& emitter, const _Alias& v) { return emitter.Write(v); } return emitter.Write(v);
inline Emitter& operator << (Emitter& emitter, const _Anchor& v) { return emitter.Write(v); } }
inline Emitter& operator << (Emitter& emitter, const _Tag& v) { return emitter.Write(v); } inline Emitter& operator<<(Emitter& emitter, char v) {
inline Emitter& operator << (Emitter& emitter, const _Comment& v) { return emitter.Write(v); } return emitter.Write(v);
inline Emitter& operator << (Emitter& emitter, const _Null& v) { return emitter.Write(v); } }
inline Emitter& operator << (Emitter& emitter, const Binary& b) { return emitter.Write(b); } inline Emitter& operator<<(Emitter& emitter, unsigned char v) {
return emitter.Write(static_cast<char>(v));
}
inline Emitter& operator<<(Emitter& emitter, const _Alias& v) {
return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, const _Anchor& v) {
return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, const _Tag& v) {
return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, const _Comment& v) {
return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, const _Null& v) {
return emitter.Write(v);
}
inline Emitter& operator<<(Emitter& emitter, const Binary& b) {
return emitter.Write(b);
}
inline Emitter& operator << (Emitter& emitter, const char *v) { return emitter.Write(std::string(v)); } inline Emitter& operator<<(Emitter& emitter, const char* v) {
return emitter.Write(std::string(v));
}
inline Emitter& operator << (Emitter& emitter, int v) { return emitter.WriteIntegralType(v); } inline Emitter& operator<<(Emitter& emitter, int v) {
inline Emitter& operator << (Emitter& emitter, unsigned int v) { return emitter.WriteIntegralType(v); } return emitter.WriteIntegralType(v);
inline Emitter& operator << (Emitter& emitter, short v) { return emitter.WriteIntegralType(v); } }
inline Emitter& operator << (Emitter& emitter, unsigned short v) { return emitter.WriteIntegralType(v); } inline Emitter& operator<<(Emitter& emitter, unsigned int v) {
inline Emitter& operator << (Emitter& emitter, long v) { return emitter.WriteIntegralType(v); } return emitter.WriteIntegralType(v);
inline Emitter& operator << (Emitter& emitter, unsigned long v) { return emitter.WriteIntegralType(v); } }
inline Emitter& operator << (Emitter& emitter, long long v) { return emitter.WriteIntegralType(v); } inline Emitter& operator<<(Emitter& emitter, short v) {
inline Emitter& operator << (Emitter& emitter, unsigned long long v) { return emitter.WriteIntegralType(v); } return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, unsigned short v) {
return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, long v) {
return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, unsigned long v) {
return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, long long v) {
return emitter.WriteIntegralType(v);
}
inline Emitter& operator<<(Emitter& emitter, unsigned long long v) {
return emitter.WriteIntegralType(v);
}
inline Emitter& operator << (Emitter& emitter, float v) { return emitter.WriteStreamable(v); } inline Emitter& operator<<(Emitter& emitter, float v) {
inline Emitter& operator << (Emitter& emitter, double v) { return emitter.WriteStreamable(v); } return emitter.WriteStreamable(v);
}
inline Emitter& operator<<(Emitter& emitter, double v) {
return emitter.WriteStreamable(v);
}
inline Emitter& operator<<(Emitter& emitter, EMITTER_MANIP value) { inline Emitter& operator<<(Emitter& emitter, EMITTER_MANIP value) {
return emitter.SetLocalValue(value); return emitter.SetLocalValue(value);

View File

@@ -1,13 +1,24 @@
#ifndef EMITTERDEF_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef EMITTERDEF_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define EMITTERDEF_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define EMITTERDEF_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
namespace YAML namespace YAML {
{ struct EmitterNodeType {
struct EmitterNodeType { enum value { None, Property, Scalar, FlowSeq, BlockSeq, FlowMap, BlockMap }; }; enum value {
None,
Property,
Scalar,
FlowSeq,
BlockSeq,
FlowMap,
BlockMap
};
};
} }
#endif // EMITTERDEF_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // EMITTERDEF_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -1,15 +1,15 @@
#ifndef EMITTERMANIP_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef EMITTERMANIP_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define EMITTERMANIP_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define EMITTERMANIP_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <string> #include <string>
namespace YAML namespace YAML {
{
enum EMITTER_MANIP { enum EMITTER_MANIP {
// general manipulators // general manipulators
Auto, Auto,
@@ -67,35 +67,34 @@ namespace YAML
int value; int value;
}; };
inline _Indent Indent(int value) { inline _Indent Indent(int value) { return _Indent(value); }
return _Indent(value);
}
struct _Alias { struct _Alias {
_Alias(const std::string& content_) : content(content_) {} _Alias(const std::string& content_) : content(content_) {}
std::string content; std::string content;
}; };
inline _Alias Alias(const std::string content) { inline _Alias Alias(const std::string content) { return _Alias(content); }
return _Alias(content);
}
struct _Anchor { struct _Anchor {
_Anchor(const std::string& content_) : content(content_) {} _Anchor(const std::string& content_) : content(content_) {}
std::string content; std::string content;
}; };
inline _Anchor Anchor(const std::string content) { inline _Anchor Anchor(const std::string content) { return _Anchor(content); }
return _Anchor(content);
}
struct _Tag { struct _Tag {
struct Type { enum value { Verbatim, PrimaryHandle, NamedHandle }; }; struct Type {
enum value {
Verbatim,
PrimaryHandle,
NamedHandle
};
};
explicit _Tag(const std::string& prefix_, const std::string& content_, Type::value type_) explicit _Tag(const std::string& prefix_, const std::string& content_,
: prefix(prefix_), content(content_), type(type_) Type::value type_)
{ : prefix(prefix_), content(content_), type(type_) {}
}
std::string prefix; std::string prefix;
std::string content; std::string content;
Type::value type; Type::value type;
@@ -122,28 +121,21 @@ namespace YAML
std::string content; std::string content;
}; };
inline _Comment Comment(const std::string content) { inline _Comment Comment(const std::string content) { return _Comment(content); }
return _Comment(content);
}
struct _Precision { struct _Precision {
_Precision(int floatPrecision_, int doublePrecision_): floatPrecision(floatPrecision_), doublePrecision(doublePrecision_) {} _Precision(int floatPrecision_, int doublePrecision_)
: floatPrecision(floatPrecision_), doublePrecision(doublePrecision_) {}
int floatPrecision; int floatPrecision;
int doublePrecision; int doublePrecision;
}; };
inline _Precision FloatPrecision(int n) { inline _Precision FloatPrecision(int n) { return _Precision(n, -1); }
return _Precision(n, -1);
}
inline _Precision DoublePrecision(int n) { inline _Precision DoublePrecision(int n) { return _Precision(-1, n); }
return _Precision(-1, n);
}
inline _Precision Precision(int n) { inline _Precision Precision(int n) { return _Precision(n, n); }
return _Precision(n, n);
}
} }
#endif // EMITTERMANIP_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // EMITTERMANIP_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -1,19 +1,19 @@
#ifndef EVENTHANDLER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef EVENTHANDLER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define EVENTHANDLER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define EVENTHANDLER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/anchor.h" #include "yaml-cpp/anchor.h"
#include <string> #include <string>
namespace YAML namespace YAML {
{
struct Mark; struct Mark;
class EventHandler class EventHandler {
{
public: public:
virtual ~EventHandler() {} virtual ~EventHandler() {}
@@ -22,15 +22,17 @@ namespace YAML
virtual void OnNull(const Mark& mark, anchor_t anchor) = 0; virtual void OnNull(const Mark& mark, anchor_t anchor) = 0;
virtual void OnAlias(const Mark& mark, anchor_t anchor) = 0; virtual void OnAlias(const Mark& mark, anchor_t anchor) = 0;
virtual void OnScalar(const Mark& mark, const std::string& tag, anchor_t anchor, const std::string& value) = 0; virtual void OnScalar(const Mark& mark, const std::string& tag,
anchor_t anchor, const std::string& value) = 0;
virtual void OnSequenceStart(const Mark& mark, const std::string& tag, anchor_t anchor) = 0; virtual void OnSequenceStart(const Mark& mark, const std::string& tag,
anchor_t anchor) = 0;
virtual void OnSequenceEnd() = 0; virtual void OnSequenceEnd() = 0;
virtual void OnMapStart(const Mark& mark, const std::string& tag, anchor_t anchor) = 0; virtual void OnMapStart(const Mark& mark, const std::string& tag,
anchor_t anchor) = 0;
virtual void OnMapEnd() = 0; virtual void OnMapEnd() = 0;
}; };
} }
#endif // EVENTHANDLER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // EVENTHANDLER_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -1,15 +1,15 @@
#ifndef MARK_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef MARK_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define MARK_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define MARK_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/dll.h" #include "yaml-cpp/dll.h"
namespace YAML namespace YAML {
{
struct YAML_CPP_API Mark { struct YAML_CPP_API Mark {
Mark() : pos(0), line(0), column(0) {} Mark() : pos(0), line(0), column(0) {}
@@ -19,7 +19,8 @@ namespace YAML
int line, column; int line, column;
private: private:
Mark(int pos_, int line_, int column_): pos(pos_), line(line_), column(column_) {} Mark(int pos_, int line_, int column_)
: pos(pos_), line(line_), column(column_) {}
}; };
} }

View File

@@ -1,17 +1,17 @@
#ifndef NONCOPYABLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef NONCOPYABLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define NONCOPYABLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define NONCOPYABLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/dll.h" #include "yaml-cpp/dll.h"
namespace YAML namespace YAML {
{
// this is basically boost::noncopyable // this is basically boost::noncopyable
class YAML_CPP_API noncopyable class YAML_CPP_API noncopyable {
{
protected: protected:
noncopyable() {} noncopyable() {}
~noncopyable() {} ~noncopyable() {}

View File

@@ -1,15 +1,15 @@
#ifndef NULL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef NULL_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define NULL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define NULL_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/dll.h" #include "yaml-cpp/dll.h"
namespace YAML namespace YAML {
{
class Node; class Node;
struct YAML_CPP_API _Null {}; struct YAML_CPP_API _Null {};
@@ -22,4 +22,3 @@ namespace YAML
} }
#endif // NULL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // NULL_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -1,18 +1,17 @@
#ifndef OSTREAM_WRAPPER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef OSTREAM_WRAPPER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define OSTREAM_WRAPPER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define OSTREAM_WRAPPER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <string> #include <string>
#include <vector> #include <vector>
namespace YAML namespace YAML {
{ class ostream_wrapper {
class ostream_wrapper
{
public: public:
ostream_wrapper(); ostream_wrapper();
explicit ostream_wrapper(std::ostream& stream); explicit ostream_wrapper(std::ostream& stream);
@@ -50,12 +49,14 @@ namespace YAML
}; };
template <std::size_t N> template <std::size_t N>
inline ostream_wrapper& operator << (ostream_wrapper& stream, const char (&str)[N]) { inline ostream_wrapper& operator<<(ostream_wrapper& stream,
const char (&str)[N]) {
stream.write(str, N - 1); stream.write(str, N - 1);
return stream; return stream;
} }
inline ostream_wrapper& operator << (ostream_wrapper& stream, const std::string& str) { inline ostream_wrapper& operator<<(ostream_wrapper& stream,
const std::string& str) {
stream.write(str); stream.write(str);
return stream; return stream;
} }

View File

@@ -1,18 +1,18 @@
#ifndef STLEMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef STLEMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define STLEMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define STLEMITTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <vector> #include <vector>
#include <list> #include <list>
#include <set> #include <set>
#include <map> #include <map>
namespace YAML namespace YAML {
{
template <typename Seq> template <typename Seq>
inline Emitter& EmitSeq(Emitter& emitter, const Seq& seq) { inline Emitter& EmitSeq(Emitter& emitter, const Seq& seq) {
emitter << BeginSeq; emitter << BeginSeq;

View File

@@ -1,34 +1,113 @@
#ifndef TRAITS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef TRAITS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define TRAITS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define TRAITS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
namespace YAML {
namespace YAML
{
template <typename> template <typename>
struct is_numeric { enum { value = false }; }; struct is_numeric {
enum {
value = false
};
};
template <> struct is_numeric <char> { enum { value = true }; }; template <>
template <> struct is_numeric <unsigned char> { enum { value = true }; }; struct is_numeric<char> {
template <> struct is_numeric <int> { enum { value = true }; }; enum {
template <> struct is_numeric <unsigned int> { enum { value = true }; }; value = true
template <> struct is_numeric <long int> { enum { value = true }; }; };
template <> struct is_numeric <unsigned long int> { enum { value = true }; }; };
template <> struct is_numeric <short int> { enum { value = true }; }; template <>
template <> struct is_numeric <unsigned short int> { enum { value = true }; }; struct is_numeric<unsigned char> {
enum {
value = true
};
};
template <>
struct is_numeric<int> {
enum {
value = true
};
};
template <>
struct is_numeric<unsigned int> {
enum {
value = true
};
};
template <>
struct is_numeric<long int> {
enum {
value = true
};
};
template <>
struct is_numeric<unsigned long int> {
enum {
value = true
};
};
template <>
struct is_numeric<short int> {
enum {
value = true
};
};
template <>
struct is_numeric<unsigned short int> {
enum {
value = true
};
};
#if defined(_MSC_VER) && (_MSC_VER < 1310) #if defined(_MSC_VER) && (_MSC_VER < 1310)
template <> struct is_numeric <__int64> { enum { value = true }; }; template <>
template <> struct is_numeric <unsigned __int64> { enum { value = true }; }; struct is_numeric<__int64> {
enum {
value = true
};
};
template <>
struct is_numeric<unsigned __int64> {
enum {
value = true
};
};
#else #else
template <> struct is_numeric <long long> { enum { value = true }; }; template <>
template <> struct is_numeric <unsigned long long> { enum { value = true }; }; struct is_numeric<long long> {
enum {
value = true
};
};
template <>
struct is_numeric<unsigned long long> {
enum {
value = true
};
};
#endif #endif
template <> struct is_numeric <float> { enum { value = true }; }; template <>
template <> struct is_numeric <double> { enum { value = true }; }; struct is_numeric<float> {
template <> struct is_numeric <long double> { enum { value = true }; }; enum {
value = true
};
};
template <>
struct is_numeric<double> {
enum {
value = true
};
};
template <>
struct is_numeric<long double> {
enum {
value = true
};
};
template <bool, class T = void> template <bool, class T = void>
struct enable_if_c { struct enable_if_c {
@@ -54,4 +133,3 @@ namespace YAML
} }
#endif // TRAITS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // TRAITS_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -1,11 +1,10 @@
#include "yaml-cpp/binary.h" #include "yaml-cpp/binary.h"
namespace YAML namespace YAML {
{ static const char encoding[] =
static const char encoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string EncodeBase64(const unsigned char *data, std::size_t size) std::string EncodeBase64(const unsigned char *data, std::size_t size) {
{
const char PAD = '='; const char PAD = '=';
std::string ret; std::string ret;
@@ -44,26 +43,26 @@ namespace YAML
} }
static const unsigned char decoding[] = { static const unsigned char decoding[] = {
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255, 0,255,255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 255, 0, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
}; 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, };
std::vector<unsigned char> DecodeBase64(const std::string& input) std::vector<unsigned char> DecodeBase64(const std::string &input) {
{
typedef std::vector<unsigned char> ret_type; typedef std::vector<unsigned char> ret_type;
if (input.empty()) if (input.empty())
return ret_type(); return ret_type();

View File

@@ -1,22 +1,28 @@
#ifndef COLLECTIONSTACK_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef COLLECTIONSTACK_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define COLLECTIONSTACK_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define COLLECTIONSTACK_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <stack> #include <stack>
#include <cassert> #include <cassert>
namespace YAML namespace YAML {
{
struct CollectionType { struct CollectionType {
enum value { None, BlockMap, BlockSeq, FlowMap, FlowSeq, CompactMap }; enum value {
None,
BlockMap,
BlockSeq,
FlowMap,
FlowSeq,
CompactMap
};
}; };
class CollectionStack class CollectionStack {
{
public: public:
CollectionType::value GetCurCollectionType() const { CollectionType::value GetCurCollectionType() const {
if (collectionStack.empty()) if (collectionStack.empty())
@@ -24,8 +30,13 @@ namespace YAML
return collectionStack.top(); return collectionStack.top();
} }
void PushCollectionType(CollectionType::value type) { collectionStack.push(type); } void PushCollectionType(CollectionType::value type) {
void PopCollectionType(CollectionType::value type) { assert(type == GetCurCollectionType()); collectionStack.pop(); } collectionStack.push(type);
}
void PopCollectionType(CollectionType::value type) {
assert(type == GetCurCollectionType());
collectionStack.pop();
}
private: private:
std::stack<CollectionType::value> collectionStack; std::stack<CollectionType::value> collectionStack;

View File

@@ -2,10 +2,9 @@
#include "yaml-cpp/contrib/graphbuilder.h" #include "yaml-cpp/contrib/graphbuilder.h"
#include "graphbuilderadapter.h" #include "graphbuilderadapter.h"
namespace YAML namespace YAML {
{ void* BuildGraphOfNextDocument(Parser& parser,
void *BuildGraphOfNextDocument(Parser& parser, GraphBuilderInterface& graphBuilder) GraphBuilderInterface& graphBuilder) {
{
GraphBuilderAdapter eventHandler(graphBuilder); GraphBuilderAdapter eventHandler(graphBuilder);
if (parser.HandleNextDocument(eventHandler)) { if (parser.HandleNextDocument(eventHandler)) {
return eventHandler.RootNode(); return eventHandler.RootNode();

View File

@@ -1,11 +1,9 @@
#include "graphbuilderadapter.h" #include "graphbuilderadapter.h"
namespace YAML namespace YAML {
{
int GraphBuilderAdapter::ContainerFrame::sequenceMarker; int GraphBuilderAdapter::ContainerFrame::sequenceMarker;
void GraphBuilderAdapter::OnNull(const Mark& mark, anchor_t anchor) void GraphBuilderAdapter::OnNull(const Mark &mark, anchor_t anchor) {
{
void *pParent = GetCurrentParent(); void *pParent = GetCurrentParent();
void *pNode = m_builder.NewNull(mark, pParent); void *pNode = m_builder.NewNull(mark, pParent);
RegisterAnchor(anchor, pNode); RegisterAnchor(anchor, pNode);
@@ -13,14 +11,13 @@ namespace YAML
DispositionNode(pNode); DispositionNode(pNode);
} }
void GraphBuilderAdapter::OnAlias(const Mark& mark, anchor_t anchor) void GraphBuilderAdapter::OnAlias(const Mark &mark, anchor_t anchor) {
{
void *pReffedNode = m_anchors.Get(anchor); void *pReffedNode = m_anchors.Get(anchor);
DispositionNode(m_builder.AnchorReference(mark, pReffedNode)); DispositionNode(m_builder.AnchorReference(mark, pReffedNode));
} }
void GraphBuilderAdapter::OnScalar(const Mark& mark, const std::string& tag, anchor_t anchor, const std::string& value) void GraphBuilderAdapter::OnScalar(const Mark &mark, const std::string &tag,
{ anchor_t anchor, const std::string &value) {
void *pParent = GetCurrentParent(); void *pParent = GetCurrentParent();
void *pNode = m_builder.NewScalar(mark, tag, pParent, value); void *pNode = m_builder.NewScalar(mark, tag, pParent, value);
RegisterAnchor(anchor, pNode); RegisterAnchor(anchor, pNode);
@@ -28,54 +25,50 @@ namespace YAML
DispositionNode(pNode); DispositionNode(pNode);
} }
void GraphBuilderAdapter::OnSequenceStart(const Mark& mark, const std::string& tag, anchor_t anchor) void GraphBuilderAdapter::OnSequenceStart(const Mark &mark,
{ const std::string &tag,
anchor_t anchor) {
void *pNode = m_builder.NewSequence(mark, tag, GetCurrentParent()); void *pNode = m_builder.NewSequence(mark, tag, GetCurrentParent());
m_containers.push(ContainerFrame(pNode)); m_containers.push(ContainerFrame(pNode));
RegisterAnchor(anchor, pNode); RegisterAnchor(anchor, pNode);
} }
void GraphBuilderAdapter::OnSequenceEnd() void GraphBuilderAdapter::OnSequenceEnd() {
{
void *pSequence = m_containers.top().pContainer; void *pSequence = m_containers.top().pContainer;
m_containers.pop(); m_containers.pop();
DispositionNode(pSequence); DispositionNode(pSequence);
} }
void GraphBuilderAdapter::OnMapStart(const Mark& mark, const std::string& tag, anchor_t anchor) void GraphBuilderAdapter::OnMapStart(const Mark &mark, const std::string &tag,
{ anchor_t anchor) {
void *pNode = m_builder.NewMap(mark, tag, GetCurrentParent()); void *pNode = m_builder.NewMap(mark, tag, GetCurrentParent());
m_containers.push(ContainerFrame(pNode, m_pKeyNode)); m_containers.push(ContainerFrame(pNode, m_pKeyNode));
m_pKeyNode = NULL; m_pKeyNode = NULL;
RegisterAnchor(anchor, pNode); RegisterAnchor(anchor, pNode);
} }
void GraphBuilderAdapter::OnMapEnd() void GraphBuilderAdapter::OnMapEnd() {
{
void *pMap = m_containers.top().pContainer; void *pMap = m_containers.top().pContainer;
m_pKeyNode = m_containers.top().pPrevKeyNode; m_pKeyNode = m_containers.top().pPrevKeyNode;
m_containers.pop(); m_containers.pop();
DispositionNode(pMap); DispositionNode(pMap);
} }
void *GraphBuilderAdapter::GetCurrentParent() const void *GraphBuilderAdapter::GetCurrentParent() const {
{
if (m_containers.empty()) { if (m_containers.empty()) {
return NULL; return NULL;
} }
return m_containers.top().pContainer; return m_containers.top().pContainer;
} }
void GraphBuilderAdapter::RegisterAnchor(anchor_t anchor, void *pNode) void GraphBuilderAdapter::RegisterAnchor(anchor_t anchor, void *pNode) {
{
if (anchor) { if (anchor) {
m_anchors.Register(anchor, pNode); m_anchors.Register(anchor, pNode);
} }
} }
void GraphBuilderAdapter::DispositionNode(void *pNode) void GraphBuilderAdapter::DispositionNode(void *pNode) {
{
if (m_containers.empty()) { if (m_containers.empty()) {
m_pRootNode = pNode; m_pRootNode = pNode;
return; return;

View File

@@ -1,7 +1,9 @@
#ifndef GRAPHBUILDERADAPTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef GRAPHBUILDERADAPTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define GRAPHBUILDERADAPTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define GRAPHBUILDERADAPTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
@@ -12,40 +14,36 @@
#include "yaml-cpp/contrib/anchordict.h" #include "yaml-cpp/contrib/anchordict.h"
#include "yaml-cpp/contrib/graphbuilder.h" #include "yaml-cpp/contrib/graphbuilder.h"
namespace YAML namespace YAML {
{ class GraphBuilderAdapter : public EventHandler {
class GraphBuilderAdapter : public EventHandler
{
public: public:
GraphBuilderAdapter(GraphBuilderInterface& builder) GraphBuilderAdapter(GraphBuilderInterface& builder)
: m_builder(builder), m_pRootNode(NULL), m_pKeyNode(NULL) : m_builder(builder), m_pRootNode(NULL), m_pKeyNode(NULL) {}
{
}
virtual void OnDocumentStart(const Mark& mark) { (void)mark; } virtual void OnDocumentStart(const Mark& mark) { (void)mark; }
virtual void OnDocumentEnd() {} virtual void OnDocumentEnd() {}
virtual void OnNull(const Mark& mark, anchor_t anchor); virtual void OnNull(const Mark& mark, anchor_t anchor);
virtual void OnAlias(const Mark& mark, anchor_t anchor); virtual void OnAlias(const Mark& mark, anchor_t anchor);
virtual void OnScalar(const Mark& mark, const std::string& tag, anchor_t anchor, const std::string& value); virtual void OnScalar(const Mark& mark, const std::string& tag,
anchor_t anchor, const std::string& value);
virtual void OnSequenceStart(const Mark& mark, const std::string& tag, anchor_t anchor); virtual void OnSequenceStart(const Mark& mark, const std::string& tag,
anchor_t anchor);
virtual void OnSequenceEnd(); virtual void OnSequenceEnd();
virtual void OnMapStart(const Mark& mark, const std::string& tag, anchor_t anchor); virtual void OnMapStart(const Mark& mark, const std::string& tag,
anchor_t anchor);
virtual void OnMapEnd(); virtual void OnMapEnd();
void* RootNode() const { return m_pRootNode; } void* RootNode() const { return m_pRootNode; }
private: private:
struct ContainerFrame struct ContainerFrame {
{
ContainerFrame(void* pSequence) ContainerFrame(void* pSequence)
: pContainer(pSequence), pPrevKeyNode(&sequenceMarker) : pContainer(pSequence), pPrevKeyNode(&sequenceMarker) {}
{}
ContainerFrame(void* pMap, void* pPrevKeyNode) ContainerFrame(void* pMap, void* pPrevKeyNode)
: pContainer(pMap), pPrevKeyNode(pPrevKeyNode) : pContainer(pMap), pPrevKeyNode(pPrevKeyNode) {}
{}
void* pContainer; void* pContainer;
void* pPrevKeyNode; void* pPrevKeyNode;

View File

@@ -1,17 +1,15 @@
#include "directives.h" #include "directives.h"
namespace YAML namespace YAML {
{ Directives::Directives() {
Directives::Directives()
{
// version // version
version.isDefault = true; version.isDefault = true;
version.major = 1; version.major = 1;
version.minor = 2; version.minor = 2;
} }
const std::string Directives::TranslateTagHandle(const std::string& handle) const const std::string Directives::TranslateTagHandle(const std::string& handle)
{ const {
std::map<std::string, std::string>::const_iterator it = tags.find(handle); std::map<std::string, std::string>::const_iterator it = tags.find(handle);
if (it == tags.end()) { if (it == tags.end()) {
if (handle == "!!") if (handle == "!!")

View File

@@ -1,16 +1,16 @@
#ifndef DIRECTIVES_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef DIRECTIVES_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define DIRECTIVES_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define DIRECTIVES_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <string> #include <string>
#include <map> #include <map>
namespace YAML namespace YAML {
{
struct Version { struct Version {
bool isDefault; bool isDefault;
int major, minor; int major, minor;

View File

@@ -12,72 +12,60 @@ namespace {
} }
} }
namespace YAML namespace YAML {
{ EmitFromEvents::EmitFromEvents(Emitter& emitter) : m_emitter(emitter) {}
EmitFromEvents::EmitFromEvents(Emitter& emitter): m_emitter(emitter)
{
}
void EmitFromEvents::OnDocumentStart(const Mark&) void EmitFromEvents::OnDocumentStart(const Mark&) {}
{
}
void EmitFromEvents::OnDocumentEnd() void EmitFromEvents::OnDocumentEnd() {}
{
}
void EmitFromEvents::OnNull(const Mark&, anchor_t anchor) void EmitFromEvents::OnNull(const Mark&, anchor_t anchor) {
{
BeginNode(); BeginNode();
EmitProps("", anchor); EmitProps("", anchor);
m_emitter << Null; m_emitter << Null;
} }
void EmitFromEvents::OnAlias(const Mark&, anchor_t anchor) void EmitFromEvents::OnAlias(const Mark&, anchor_t anchor) {
{
BeginNode(); BeginNode();
m_emitter << Alias(ToString(anchor)); m_emitter << Alias(ToString(anchor));
} }
void EmitFromEvents::OnScalar(const Mark&, const std::string& tag, anchor_t anchor, const std::string& value) void EmitFromEvents::OnScalar(const Mark&, const std::string& tag,
{ anchor_t anchor, const std::string& value) {
BeginNode(); BeginNode();
EmitProps(tag, anchor); EmitProps(tag, anchor);
m_emitter << value; m_emitter << value;
} }
void EmitFromEvents::OnSequenceStart(const Mark&, const std::string& tag, anchor_t anchor) void EmitFromEvents::OnSequenceStart(const Mark&, const std::string& tag,
{ anchor_t anchor) {
BeginNode(); BeginNode();
EmitProps(tag, anchor); EmitProps(tag, anchor);
m_emitter << BeginSeq; m_emitter << BeginSeq;
m_stateStack.push(State::WaitingForSequenceEntry); m_stateStack.push(State::WaitingForSequenceEntry);
} }
void EmitFromEvents::OnSequenceEnd() void EmitFromEvents::OnSequenceEnd() {
{
m_emitter << EndSeq; m_emitter << EndSeq;
assert(m_stateStack.top() == State::WaitingForSequenceEntry); assert(m_stateStack.top() == State::WaitingForSequenceEntry);
m_stateStack.pop(); m_stateStack.pop();
} }
void EmitFromEvents::OnMapStart(const Mark&, const std::string& tag, anchor_t anchor) void EmitFromEvents::OnMapStart(const Mark&, const std::string& tag,
{ anchor_t anchor) {
BeginNode(); BeginNode();
EmitProps(tag, anchor); EmitProps(tag, anchor);
m_emitter << BeginMap; m_emitter << BeginMap;
m_stateStack.push(State::WaitingForKey); m_stateStack.push(State::WaitingForKey);
} }
void EmitFromEvents::OnMapEnd() void EmitFromEvents::OnMapEnd() {
{
m_emitter << EndMap; m_emitter << EndMap;
assert(m_stateStack.top() == State::WaitingForKey); assert(m_stateStack.top() == State::WaitingForKey);
m_stateStack.pop(); m_stateStack.pop();
} }
void EmitFromEvents::BeginNode() void EmitFromEvents::BeginNode() {
{
if (m_stateStack.empty()) if (m_stateStack.empty())
return; return;
@@ -95,8 +83,7 @@ namespace YAML
} }
} }
void EmitFromEvents::EmitProps(const std::string& tag, anchor_t anchor) void EmitFromEvents::EmitProps(const std::string& tag, anchor_t anchor) {
{
if (!tag.empty() && tag != "?") if (!tag.empty() && tag != "?")
m_emitter << VerbatimTag(tag); m_emitter << VerbatimTag(tag);
if (anchor) if (anchor)

View File

@@ -5,54 +5,35 @@
#include "yaml-cpp/exceptions.h" #include "yaml-cpp/exceptions.h"
#include <sstream> #include <sstream>
namespace YAML namespace YAML {
{ Emitter::Emitter() : m_pState(new EmitterState) {}
Emitter::Emitter(): m_pState(new EmitterState)
{
}
Emitter::Emitter(std::ostream& stream): m_pState(new EmitterState), m_stream(stream) Emitter::Emitter(std::ostream& stream)
{ : m_pState(new EmitterState), m_stream(stream) {}
}
Emitter::~Emitter() Emitter::~Emitter() {}
{
}
const char *Emitter::c_str() const const char* Emitter::c_str() const { return m_stream.str(); }
{
return m_stream.str();
}
std::size_t Emitter::size() const std::size_t Emitter::size() const { return m_stream.pos(); }
{
return m_stream.pos();
}
// state checking // state checking
bool Emitter::good() const bool Emitter::good() const { return m_pState->good(); }
{
return m_pState->good();
}
const std::string Emitter::GetLastError() const const std::string Emitter::GetLastError() const {
{
return m_pState->GetLastError(); return m_pState->GetLastError();
} }
// global setters // global setters
bool Emitter::SetOutputCharset(EMITTER_MANIP value) bool Emitter::SetOutputCharset(EMITTER_MANIP value) {
{
return m_pState->SetOutputCharset(value, FmtScope::Global); return m_pState->SetOutputCharset(value, FmtScope::Global);
} }
bool Emitter::SetStringFormat(EMITTER_MANIP value) bool Emitter::SetStringFormat(EMITTER_MANIP value) {
{
return m_pState->SetStringFormat(value, FmtScope::Global); return m_pState->SetStringFormat(value, FmtScope::Global);
} }
bool Emitter::SetBoolFormat(EMITTER_MANIP value) bool Emitter::SetBoolFormat(EMITTER_MANIP value) {
{
bool ok = false; bool ok = false;
if (m_pState->SetBoolFormat(value, FmtScope::Global)) if (m_pState->SetBoolFormat(value, FmtScope::Global))
ok = true; ok = true;
@@ -63,18 +44,15 @@ namespace YAML
return ok; return ok;
} }
bool Emitter::SetIntBase(EMITTER_MANIP value) bool Emitter::SetIntBase(EMITTER_MANIP value) {
{
return m_pState->SetIntFormat(value, FmtScope::Global); return m_pState->SetIntFormat(value, FmtScope::Global);
} }
bool Emitter::SetSeqFormat(EMITTER_MANIP value) bool Emitter::SetSeqFormat(EMITTER_MANIP value) {
{
return m_pState->SetFlowType(GroupType::Seq, value, FmtScope::Global); return m_pState->SetFlowType(GroupType::Seq, value, FmtScope::Global);
} }
bool Emitter::SetMapFormat(EMITTER_MANIP value) bool Emitter::SetMapFormat(EMITTER_MANIP value) {
{
bool ok = false; bool ok = false;
if (m_pState->SetFlowType(GroupType::Map, value, FmtScope::Global)) if (m_pState->SetFlowType(GroupType::Map, value, FmtScope::Global))
ok = true; ok = true;
@@ -83,35 +61,29 @@ namespace YAML
return ok; return ok;
} }
bool Emitter::SetIndent(unsigned n) bool Emitter::SetIndent(unsigned n) {
{
return m_pState->SetIndent(n, FmtScope::Global); return m_pState->SetIndent(n, FmtScope::Global);
} }
bool Emitter::SetPreCommentIndent(unsigned n) bool Emitter::SetPreCommentIndent(unsigned n) {
{
return m_pState->SetPreCommentIndent(n, FmtScope::Global); return m_pState->SetPreCommentIndent(n, FmtScope::Global);
} }
bool Emitter::SetPostCommentIndent(unsigned n) bool Emitter::SetPostCommentIndent(unsigned n) {
{
return m_pState->SetPostCommentIndent(n, FmtScope::Global); return m_pState->SetPostCommentIndent(n, FmtScope::Global);
} }
bool Emitter::SetFloatPrecision(unsigned n) bool Emitter::SetFloatPrecision(unsigned n) {
{
return m_pState->SetFloatPrecision(n, FmtScope::Global); return m_pState->SetFloatPrecision(n, FmtScope::Global);
} }
bool Emitter::SetDoublePrecision(unsigned n) bool Emitter::SetDoublePrecision(unsigned n) {
{
return m_pState->SetDoublePrecision(n, FmtScope::Global); return m_pState->SetDoublePrecision(n, FmtScope::Global);
} }
// SetLocalValue // SetLocalValue
// . Either start/end a group, or set a modifier locally // . Either start/end a group, or set a modifier locally
Emitter& Emitter::SetLocalValue(EMITTER_MANIP value) Emitter& Emitter::SetLocalValue(EMITTER_MANIP value) {
{
if (!good()) if (!good())
return *this; return *this;
@@ -151,14 +123,12 @@ namespace YAML
return *this; return *this;
} }
Emitter& Emitter::SetLocalIndent(const _Indent& indent) Emitter& Emitter::SetLocalIndent(const _Indent& indent) {
{
m_pState->SetIndent(indent.value, FmtScope::Local); m_pState->SetIndent(indent.value, FmtScope::Local);
return *this; return *this;
} }
Emitter& Emitter::SetLocalPrecision(const _Precision& precision) Emitter& Emitter::SetLocalPrecision(const _Precision& precision) {
{
if (precision.floatPrecision >= 0) if (precision.floatPrecision >= 0)
m_pState->SetFloatPrecision(precision.floatPrecision, FmtScope::Local); m_pState->SetFloatPrecision(precision.floatPrecision, FmtScope::Local);
if (precision.doublePrecision >= 0) if (precision.doublePrecision >= 0)
@@ -167,8 +137,7 @@ namespace YAML
} }
// EmitBeginDoc // EmitBeginDoc
void Emitter::EmitBeginDoc() void Emitter::EmitBeginDoc() {
{
if (!good()) if (!good())
return; return;
@@ -190,8 +159,7 @@ namespace YAML
} }
// EmitEndDoc // EmitEndDoc
void Emitter::EmitEndDoc() void Emitter::EmitEndDoc() {
{
if (!good()) if (!good())
return; return;
@@ -211,8 +179,7 @@ namespace YAML
} }
// EmitBeginSeq // EmitBeginSeq
void Emitter::EmitBeginSeq() void Emitter::EmitBeginSeq() {
{
if (!good()) if (!good())
return; return;
@@ -222,8 +189,7 @@ namespace YAML
} }
// EmitEndSeq // EmitEndSeq
void Emitter::EmitEndSeq() void Emitter::EmitEndSeq() {
{
if (!good()) if (!good())
return; return;
@@ -243,8 +209,7 @@ namespace YAML
} }
// EmitBeginMap // EmitBeginMap
void Emitter::EmitBeginMap() void Emitter::EmitBeginMap() {
{
if (!good()) if (!good())
return; return;
@@ -254,8 +219,7 @@ namespace YAML
} }
// EmitEndMap // EmitEndMap
void Emitter::EmitEndMap() void Emitter::EmitEndMap() {
{
if (!good()) if (!good())
return; return;
@@ -275,8 +239,7 @@ namespace YAML
} }
// EmitNewline // EmitNewline
void Emitter::EmitNewline() void Emitter::EmitNewline() {
{
if (!good()) if (!good())
return; return;
@@ -285,15 +248,11 @@ namespace YAML
m_pState->SetNonContent(); m_pState->SetNonContent();
} }
bool Emitter::CanEmitNewline() const bool Emitter::CanEmitNewline() const { return true; }
{
return true;
}
// Put the stream in a state so we can simply write the next node // Put the stream in a state so we can simply write the next node
// E.g., if we're in a sequence, write the "- " // E.g., if we're in a sequence, write the "- "
void Emitter::PrepareNode(EmitterNodeType::value child) void Emitter::PrepareNode(EmitterNodeType::value child) {
{
switch (m_pState->CurGroupNodeType()) { switch (m_pState->CurGroupNodeType()) {
case EmitterNodeType::None: case EmitterNodeType::None:
PrepareTopNode(child); PrepareTopNode(child);
@@ -317,8 +276,7 @@ namespace YAML
} }
} }
void Emitter::PrepareTopNode(EmitterNodeType::value child) void Emitter::PrepareTopNode(EmitterNodeType::value child) {
{
if (child == EmitterNodeType::None) if (child == EmitterNodeType::None)
return; return;
@@ -346,8 +304,7 @@ namespace YAML
} }
} }
void Emitter::FlowSeqPrepareNode(EmitterNodeType::value child) void Emitter::FlowSeqPrepareNode(EmitterNodeType::value child) {
{
const unsigned lastIndent = m_pState->LastIndent(); const unsigned lastIndent = m_pState->LastIndent();
if (!m_pState->HasBegunNode()) { if (!m_pState->HasBegunNode()) {
@@ -367,7 +324,9 @@ namespace YAML
case EmitterNodeType::Scalar: case EmitterNodeType::Scalar:
case EmitterNodeType::FlowSeq: case EmitterNodeType::FlowSeq:
case EmitterNodeType::FlowMap: case EmitterNodeType::FlowMap:
SpaceOrIndentTo(m_pState->HasBegunContent() || m_pState->CurGroupChildCount() > 0, lastIndent); SpaceOrIndentTo(
m_pState->HasBegunContent() || m_pState->CurGroupChildCount() > 0,
lastIndent);
break; break;
case EmitterNodeType::BlockSeq: case EmitterNodeType::BlockSeq:
case EmitterNodeType::BlockMap: case EmitterNodeType::BlockMap:
@@ -376,8 +335,7 @@ namespace YAML
} }
} }
void Emitter::BlockSeqPrepareNode(EmitterNodeType::value child) void Emitter::BlockSeqPrepareNode(EmitterNodeType::value child) {
{
const unsigned curIndent = m_pState->CurIndent(); const unsigned curIndent = m_pState->CurIndent();
const unsigned nextIndent = curIndent + m_pState->CurGroupIndent(); const unsigned nextIndent = curIndent + m_pState->CurGroupIndent();
@@ -411,8 +369,7 @@ namespace YAML
} }
} }
void Emitter::FlowMapPrepareNode(EmitterNodeType::value child) void Emitter::FlowMapPrepareNode(EmitterNodeType::value child) {
{
if (m_pState->CurGroupChildCount() % 2 == 0) { if (m_pState->CurGroupChildCount() % 2 == 0) {
if (m_pState->GetMapKeyFormat() == LongKey) if (m_pState->GetMapKeyFormat() == LongKey)
m_pState->SetLongKey(); m_pState->SetLongKey();
@@ -429,8 +386,7 @@ namespace YAML
} }
} }
void Emitter::FlowMapPrepareLongKey(EmitterNodeType::value child) void Emitter::FlowMapPrepareLongKey(EmitterNodeType::value child) {
{
const unsigned lastIndent = m_pState->LastIndent(); const unsigned lastIndent = m_pState->LastIndent();
if (!m_pState->HasBegunNode()) { if (!m_pState->HasBegunNode()) {
@@ -450,7 +406,9 @@ namespace YAML
case EmitterNodeType::Scalar: case EmitterNodeType::Scalar:
case EmitterNodeType::FlowSeq: case EmitterNodeType::FlowSeq:
case EmitterNodeType::FlowMap: case EmitterNodeType::FlowMap:
SpaceOrIndentTo(m_pState->HasBegunContent() || m_pState->CurGroupChildCount() > 0, lastIndent); SpaceOrIndentTo(
m_pState->HasBegunContent() || m_pState->CurGroupChildCount() > 0,
lastIndent);
break; break;
case EmitterNodeType::BlockSeq: case EmitterNodeType::BlockSeq:
case EmitterNodeType::BlockMap: case EmitterNodeType::BlockMap:
@@ -459,8 +417,7 @@ namespace YAML
} }
} }
void Emitter::FlowMapPrepareLongKeyValue(EmitterNodeType::value child) void Emitter::FlowMapPrepareLongKeyValue(EmitterNodeType::value child) {
{
const unsigned lastIndent = m_pState->LastIndent(); const unsigned lastIndent = m_pState->LastIndent();
if (!m_pState->HasBegunNode()) { if (!m_pState->HasBegunNode()) {
@@ -477,7 +434,9 @@ namespace YAML
case EmitterNodeType::Scalar: case EmitterNodeType::Scalar:
case EmitterNodeType::FlowSeq: case EmitterNodeType::FlowSeq:
case EmitterNodeType::FlowMap: case EmitterNodeType::FlowMap:
SpaceOrIndentTo(m_pState->HasBegunContent() || m_pState->CurGroupChildCount() > 0, lastIndent); SpaceOrIndentTo(
m_pState->HasBegunContent() || m_pState->CurGroupChildCount() > 0,
lastIndent);
break; break;
case EmitterNodeType::BlockSeq: case EmitterNodeType::BlockSeq:
case EmitterNodeType::BlockMap: case EmitterNodeType::BlockMap:
@@ -486,8 +445,7 @@ namespace YAML
} }
} }
void Emitter::FlowMapPrepareSimpleKey(EmitterNodeType::value child) void Emitter::FlowMapPrepareSimpleKey(EmitterNodeType::value child) {
{
const unsigned lastIndent = m_pState->LastIndent(); const unsigned lastIndent = m_pState->LastIndent();
if (!m_pState->HasBegunNode()) { if (!m_pState->HasBegunNode()) {
@@ -507,7 +465,9 @@ namespace YAML
case EmitterNodeType::Scalar: case EmitterNodeType::Scalar:
case EmitterNodeType::FlowSeq: case EmitterNodeType::FlowSeq:
case EmitterNodeType::FlowMap: case EmitterNodeType::FlowMap:
SpaceOrIndentTo(m_pState->HasBegunContent() || m_pState->CurGroupChildCount() > 0, lastIndent); SpaceOrIndentTo(
m_pState->HasBegunContent() || m_pState->CurGroupChildCount() > 0,
lastIndent);
break; break;
case EmitterNodeType::BlockSeq: case EmitterNodeType::BlockSeq:
case EmitterNodeType::BlockMap: case EmitterNodeType::BlockMap:
@@ -516,8 +476,7 @@ namespace YAML
} }
} }
void Emitter::FlowMapPrepareSimpleKeyValue(EmitterNodeType::value child) void Emitter::FlowMapPrepareSimpleKeyValue(EmitterNodeType::value child) {
{
const unsigned lastIndent = m_pState->LastIndent(); const unsigned lastIndent = m_pState->LastIndent();
if (!m_pState->HasBegunNode()) { if (!m_pState->HasBegunNode()) {
@@ -534,7 +493,9 @@ namespace YAML
case EmitterNodeType::Scalar: case EmitterNodeType::Scalar:
case EmitterNodeType::FlowSeq: case EmitterNodeType::FlowSeq:
case EmitterNodeType::FlowMap: case EmitterNodeType::FlowMap:
SpaceOrIndentTo(m_pState->HasBegunContent() || m_pState->CurGroupChildCount() > 0, lastIndent); SpaceOrIndentTo(
m_pState->HasBegunContent() || m_pState->CurGroupChildCount() > 0,
lastIndent);
break; break;
case EmitterNodeType::BlockSeq: case EmitterNodeType::BlockSeq:
case EmitterNodeType::BlockMap: case EmitterNodeType::BlockMap:
@@ -543,12 +504,12 @@ namespace YAML
} }
} }
void Emitter::BlockMapPrepareNode(EmitterNodeType::value child) void Emitter::BlockMapPrepareNode(EmitterNodeType::value child) {
{
if (m_pState->CurGroupChildCount() % 2 == 0) { if (m_pState->CurGroupChildCount() % 2 == 0) {
if (m_pState->GetMapKeyFormat() == LongKey) if (m_pState->GetMapKeyFormat() == LongKey)
m_pState->SetLongKey(); m_pState->SetLongKey();
if(child == EmitterNodeType::BlockSeq || child == EmitterNodeType::BlockMap) if (child == EmitterNodeType::BlockSeq ||
child == EmitterNodeType::BlockMap)
m_pState->SetLongKey(); m_pState->SetLongKey();
if (m_pState->CurGroupLongKey()) if (m_pState->CurGroupLongKey())
@@ -563,8 +524,7 @@ namespace YAML
} }
} }
void Emitter::BlockMapPrepareLongKey(EmitterNodeType::value child) void Emitter::BlockMapPrepareLongKey(EmitterNodeType::value child) {
{
const unsigned curIndent = m_pState->CurIndent(); const unsigned curIndent = m_pState->CurIndent();
const std::size_t childCount = m_pState->CurGroupChildCount(); const std::size_t childCount = m_pState->CurGroupChildCount();
@@ -597,8 +557,7 @@ namespace YAML
} }
} }
void Emitter::BlockMapPrepareLongKeyValue(EmitterNodeType::value child) void Emitter::BlockMapPrepareLongKeyValue(EmitterNodeType::value child) {
{
const unsigned curIndent = m_pState->CurIndent(); const unsigned curIndent = m_pState->CurIndent();
if (child == EmitterNodeType::None) if (child == EmitterNodeType::None)
@@ -624,8 +583,7 @@ namespace YAML
} }
} }
void Emitter::BlockMapPrepareSimpleKey(EmitterNodeType::value child) void Emitter::BlockMapPrepareSimpleKey(EmitterNodeType::value child) {
{
const unsigned curIndent = m_pState->CurIndent(); const unsigned curIndent = m_pState->CurIndent();
const std::size_t childCount = m_pState->CurGroupChildCount(); const std::size_t childCount = m_pState->CurGroupChildCount();
@@ -653,8 +611,7 @@ namespace YAML
} }
} }
void Emitter::BlockMapPrepareSimpleKeyValue(EmitterNodeType::value child) void Emitter::BlockMapPrepareSimpleKeyValue(EmitterNodeType::value child) {
{
const unsigned curIndent = m_pState->CurIndent(); const unsigned curIndent = m_pState->CurIndent();
const unsigned nextIndent = curIndent + m_pState->CurGroupIndent(); const unsigned nextIndent = curIndent + m_pState->CurGroupIndent();
@@ -680,8 +637,7 @@ namespace YAML
// SpaceOrIndentTo // SpaceOrIndentTo
// . Prepares for some more content by proper spacing // . Prepares for some more content by proper spacing
void Emitter::SpaceOrIndentTo(bool requireSpace, unsigned indent) void Emitter::SpaceOrIndentTo(bool requireSpace, unsigned indent) {
{
if (m_stream.comment()) if (m_stream.comment())
m_stream << "\n"; m_stream << "\n";
if (m_stream.col() > 0 && requireSpace) if (m_stream.col() > 0 && requireSpace)
@@ -689,8 +645,7 @@ namespace YAML
m_stream << IndentTo(indent); m_stream << IndentTo(indent);
} }
void Emitter::PrepareIntegralStream(std::stringstream& stream) const void Emitter::PrepareIntegralStream(std::stringstream& stream) const {
{
switch (m_pState->GetIntFormat()) { switch (m_pState->GetIntFormat()) {
case Dec: case Dec:
@@ -709,21 +664,19 @@ namespace YAML
} }
} }
void Emitter::StartedScalar() void Emitter::StartedScalar() { m_pState->StartedScalar(); }
{
m_pState->StartedScalar();
}
// ******************************************************************************************* // *******************************************************************************************
// overloads of Write // overloads of Write
Emitter& Emitter::Write(const std::string& str) Emitter& Emitter::Write(const std::string& str) {
{
if (!good()) if (!good())
return *this; return *this;
const bool escapeNonAscii = m_pState->GetOutputCharset() == EscapeNonAscii; const bool escapeNonAscii = m_pState->GetOutputCharset() == EscapeNonAscii;
const StringFormat::value strFormat = Utils::ComputeStringFormat(str, m_pState->GetStringFormat(), m_pState->CurGroupFlowType(), escapeNonAscii); const StringFormat::value strFormat =
Utils::ComputeStringFormat(str, m_pState->GetStringFormat(),
m_pState->CurGroupFlowType(), escapeNonAscii);
if (strFormat == StringFormat::Literal) if (strFormat == StringFormat::Literal)
m_pState->SetMapKeyFormat(YAML::LongKey, FmtScope::Local); m_pState->SetMapKeyFormat(YAML::LongKey, FmtScope::Local);
@@ -741,7 +694,8 @@ namespace YAML
Utils::WriteDoubleQuotedString(m_stream, str, escapeNonAscii); Utils::WriteDoubleQuotedString(m_stream, str, escapeNonAscii);
break; break;
case StringFormat::Literal: case StringFormat::Literal:
Utils::WriteLiteralString(m_stream, str, m_pState->CurIndent() + m_pState->GetIndent()); Utils::WriteLiteralString(m_stream, str,
m_pState->CurIndent() + m_pState->GetIndent());
break; break;
} }
@@ -750,53 +704,64 @@ namespace YAML
return *this; return *this;
} }
unsigned Emitter::GetFloatPrecision() const unsigned Emitter::GetFloatPrecision() const {
{
return m_pState->GetFloatPrecision(); return m_pState->GetFloatPrecision();
} }
unsigned Emitter::GetDoublePrecision() const unsigned Emitter::GetDoublePrecision() const {
{
return m_pState->GetDoublePrecision(); return m_pState->GetDoublePrecision();
} }
const char *Emitter::ComputeFullBoolName(bool b) const const char* Emitter::ComputeFullBoolName(bool b) const {
{ const EMITTER_MANIP mainFmt = (m_pState->GetBoolLengthFormat() == ShortBool
const EMITTER_MANIP mainFmt = (m_pState->GetBoolLengthFormat() == ShortBool ? YesNoBool : m_pState->GetBoolFormat()); ? YesNoBool
: m_pState->GetBoolFormat());
const EMITTER_MANIP caseFmt = m_pState->GetBoolCaseFormat(); const EMITTER_MANIP caseFmt = m_pState->GetBoolCaseFormat();
switch (mainFmt) { switch (mainFmt) {
case YesNoBool: case YesNoBool:
switch (caseFmt) { switch (caseFmt) {
case UpperCase: return b ? "YES" : "NO"; case UpperCase:
case CamelCase: return b ? "Yes" : "No"; return b ? "YES" : "NO";
case LowerCase: return b ? "yes" : "no"; case CamelCase:
default: break; return b ? "Yes" : "No";
case LowerCase:
return b ? "yes" : "no";
default:
break;
} }
break; break;
case OnOffBool: case OnOffBool:
switch (caseFmt) { switch (caseFmt) {
case UpperCase: return b ? "ON" : "OFF"; case UpperCase:
case CamelCase: return b ? "On" : "Off"; return b ? "ON" : "OFF";
case LowerCase: return b ? "on" : "off"; case CamelCase:
default: break; return b ? "On" : "Off";
case LowerCase:
return b ? "on" : "off";
default:
break;
} }
break; break;
case TrueFalseBool: case TrueFalseBool:
switch (caseFmt) { switch (caseFmt) {
case UpperCase: return b ? "TRUE" : "FALSE"; case UpperCase:
case CamelCase: return b ? "True" : "False"; return b ? "TRUE" : "FALSE";
case LowerCase: return b ? "true" : "false"; case CamelCase:
default: break; return b ? "True" : "False";
case LowerCase:
return b ? "true" : "false";
default:
break;
} }
break; break;
default: default:
break; break;
} }
return b ? "y" : "n"; // should never get here, but it can't hurt to give these answers return b ? "y" : "n"; // should never get here, but it can't hurt to give
// these answers
} }
Emitter& Emitter::Write(bool b) Emitter& Emitter::Write(bool b) {
{
if (!good()) if (!good())
return *this; return *this;
@@ -813,8 +778,7 @@ namespace YAML
return *this; return *this;
} }
Emitter& Emitter::Write(char ch) Emitter& Emitter::Write(char ch) {
{
if (!good()) if (!good())
return *this; return *this;
@@ -825,8 +789,7 @@ namespace YAML
return *this; return *this;
} }
Emitter& Emitter::Write(const _Alias& alias) Emitter& Emitter::Write(const _Alias& alias) {
{
if (!good()) if (!good())
return *this; return *this;
@@ -847,8 +810,7 @@ namespace YAML
return *this; return *this;
} }
Emitter& Emitter::Write(const _Anchor& anchor) Emitter& Emitter::Write(const _Anchor& anchor) {
{
if (!good()) if (!good())
return *this; return *this;
@@ -869,8 +831,7 @@ namespace YAML
return *this; return *this;
} }
Emitter& Emitter::Write(const _Tag& tag) Emitter& Emitter::Write(const _Tag& tag) {
{
if (!good()) if (!good())
return *this; return *this;
@@ -899,13 +860,9 @@ namespace YAML
return *this; return *this;
} }
void Emitter::EmitKindTag() void Emitter::EmitKindTag() { Write(LocalTag("")); }
{
Write(LocalTag(""));
}
Emitter& Emitter::Write(const _Comment& comment) Emitter& Emitter::Write(const _Comment& comment) {
{
if (!good()) if (!good())
return *this; return *this;
@@ -913,15 +870,15 @@ namespace YAML
if (m_stream.col() > 0) if (m_stream.col() > 0)
m_stream << Indentation(m_pState->GetPreCommentIndent()); m_stream << Indentation(m_pState->GetPreCommentIndent());
Utils::WriteComment(m_stream, comment.content, m_pState->GetPostCommentIndent()); Utils::WriteComment(m_stream, comment.content,
m_pState->GetPostCommentIndent());
m_pState->SetNonContent(); m_pState->SetNonContent();
return *this; return *this;
} }
Emitter& Emitter::Write(const _Null& /*null*/) Emitter& Emitter::Write(const _Null& /*null*/) {
{
if (!good()) if (!good())
return *this; return *this;
@@ -934,8 +891,7 @@ namespace YAML
return *this; return *this;
} }
Emitter& Emitter::Write(const Binary& binary) Emitter& Emitter::Write(const Binary& binary) {
{
Write(SecondaryTag("binary")); Write(SecondaryTag("binary"));
if (!good()) if (!good())
@@ -948,4 +904,3 @@ namespace YAML
return *this; return *this;
} }
} }

View File

@@ -2,10 +2,14 @@
#include "yaml-cpp/exceptions.h" #include "yaml-cpp/exceptions.h"
#include <limits> #include <limits>
namespace YAML namespace YAML {
{ EmitterState::EmitterState()
EmitterState::EmitterState(): m_isGood(true), m_curIndent(0), m_hasAnchor(false), m_hasTag(false), m_hasNonContent(false), m_docCount(0) : m_isGood(true),
{ m_curIndent(0),
m_hasAnchor(false),
m_hasTag(false),
m_hasNonContent(false),
m_docCount(0) {
// set default global manipulators // set default global manipulators
m_charset.set(EmitNonAscii); m_charset.set(EmitNonAscii);
m_strFmt.set(Auto); m_strFmt.set(Auto);
@@ -23,15 +27,12 @@ namespace YAML
m_doublePrecision.set(std::numeric_limits<double>::digits10 + 1); m_doublePrecision.set(std::numeric_limits<double>::digits10 + 1);
} }
EmitterState::~EmitterState() EmitterState::~EmitterState() {}
{
}
// SetLocalValue // SetLocalValue
// . We blindly tries to set all possible formatters to this value // . We blindly tries to set all possible formatters to this value
// . Only the ones that make sense will be accepted // . Only the ones that make sense will be accepted
void EmitterState::SetLocalValue(EMITTER_MANIP value) void EmitterState::SetLocalValue(EMITTER_MANIP value) {
{
SetOutputCharset(value, FmtScope::Local); SetOutputCharset(value, FmtScope::Local);
SetStringFormat(value, FmtScope::Local); SetStringFormat(value, FmtScope::Local);
SetBoolFormat(value, FmtScope::Local); SetBoolFormat(value, FmtScope::Local);
@@ -43,23 +44,13 @@ namespace YAML
SetMapKeyFormat(value, FmtScope::Local); SetMapKeyFormat(value, FmtScope::Local);
} }
void EmitterState::SetAnchor() void EmitterState::SetAnchor() { m_hasAnchor = true; }
{
m_hasAnchor = true;
}
void EmitterState::SetTag() void EmitterState::SetTag() { m_hasTag = true; }
{
m_hasTag = true;
}
void EmitterState::SetNonContent() void EmitterState::SetNonContent() { m_hasNonContent = true; }
{
m_hasNonContent = true;
}
void EmitterState::SetLongKey() void EmitterState::SetLongKey() {
{
assert(!m_groups.empty()); assert(!m_groups.empty());
if (m_groups.empty()) if (m_groups.empty())
return; return;
@@ -68,8 +59,7 @@ namespace YAML
m_groups.top().longKey = true; m_groups.top().longKey = true;
} }
void EmitterState::ForceFlow() void EmitterState::ForceFlow() {
{
assert(!m_groups.empty()); assert(!m_groups.empty());
if (m_groups.empty()) if (m_groups.empty())
return; return;
@@ -77,8 +67,7 @@ namespace YAML
m_groups.top().flowType = FlowType::Flow; m_groups.top().flowType = FlowType::Flow;
} }
void EmitterState::StartedNode() void EmitterState::StartedNode() {
{
if (m_groups.empty()) { if (m_groups.empty()) {
m_docCount++; m_docCount++;
} else { } else {
@@ -92,8 +81,8 @@ namespace YAML
m_hasNonContent = false; m_hasNonContent = false;
} }
EmitterNodeType::value EmitterState::NextGroupType(GroupType::value type) const EmitterNodeType::value EmitterState::NextGroupType(GroupType::value type)
{ const {
if (type == GroupType::Seq) { if (type == GroupType::Seq) {
if (GetFlowType(type) == Block) if (GetFlowType(type) == Block)
return EmitterNodeType::BlockSeq; return EmitterNodeType::BlockSeq;
@@ -111,28 +100,24 @@ namespace YAML
return EmitterNodeType::None; return EmitterNodeType::None;
} }
void EmitterState::StartedDoc() void EmitterState::StartedDoc() {
{
m_hasAnchor = false; m_hasAnchor = false;
m_hasTag = false; m_hasTag = false;
m_hasNonContent = false; m_hasNonContent = false;
} }
void EmitterState::EndedDoc() void EmitterState::EndedDoc() {
{
m_hasAnchor = false; m_hasAnchor = false;
m_hasTag = false; m_hasTag = false;
m_hasNonContent = false; m_hasNonContent = false;
} }
void EmitterState::StartedScalar() void EmitterState::StartedScalar() {
{
StartedNode(); StartedNode();
ClearModifiedSettings(); ClearModifiedSettings();
} }
void EmitterState::StartedGroup(GroupType::value type) void EmitterState::StartedGroup(GroupType::value type) {
{
StartedNode(); StartedNode();
const int lastGroupIndent = (m_groups.empty() ? 0 : m_groups.top().indent); const int lastGroupIndent = (m_groups.empty() ? 0 : m_groups.top().indent);
@@ -153,8 +138,7 @@ namespace YAML
m_groups.push(pGroup); m_groups.push(pGroup);
} }
void EmitterState::EndedGroup(GroupType::value type) void EmitterState::EndedGroup(GroupType::value type) {
{
if (m_groups.empty()) { if (m_groups.empty()) {
if (type == GroupType::Seq) if (type == GroupType::Seq)
return SetError(ErrorMsg::UNEXPECTED_END_SEQ); return SetError(ErrorMsg::UNEXPECTED_END_SEQ);
@@ -181,54 +165,44 @@ namespace YAML
ClearModifiedSettings(); ClearModifiedSettings();
} }
EmitterNodeType::value EmitterState::CurGroupNodeType() const EmitterNodeType::value EmitterState::CurGroupNodeType() const {
{
if (m_groups.empty()) if (m_groups.empty())
return EmitterNodeType::None; return EmitterNodeType::None;
return m_groups.top().NodeType(); return m_groups.top().NodeType();
} }
GroupType::value EmitterState::CurGroupType() const GroupType::value EmitterState::CurGroupType() const {
{
return m_groups.empty() ? GroupType::None : m_groups.top().type; return m_groups.empty() ? GroupType::None : m_groups.top().type;
} }
FlowType::value EmitterState::CurGroupFlowType() const FlowType::value EmitterState::CurGroupFlowType() const {
{
return m_groups.empty() ? FlowType::None : m_groups.top().flowType; return m_groups.empty() ? FlowType::None : m_groups.top().flowType;
} }
int EmitterState::CurGroupIndent() const int EmitterState::CurGroupIndent() const {
{
return m_groups.empty() ? 0 : m_groups.top().indent; return m_groups.empty() ? 0 : m_groups.top().indent;
} }
std::size_t EmitterState::CurGroupChildCount() const std::size_t EmitterState::CurGroupChildCount() const {
{
return m_groups.empty() ? m_docCount : m_groups.top().childCount; return m_groups.empty() ? m_docCount : m_groups.top().childCount;
} }
bool EmitterState::CurGroupLongKey() const bool EmitterState::CurGroupLongKey() const {
{
return m_groups.empty() ? false : m_groups.top().longKey; return m_groups.empty() ? false : m_groups.top().longKey;
} }
int EmitterState::LastIndent() const int EmitterState::LastIndent() const {
{
if (m_groups.size() <= 1) if (m_groups.size() <= 1)
return 0; return 0;
return m_curIndent - m_groups.top(-1).indent; return m_curIndent - m_groups.top(-1).indent;
} }
void EmitterState::ClearModifiedSettings() void EmitterState::ClearModifiedSettings() { m_modifiedSettings.clear(); }
{
m_modifiedSettings.clear();
}
bool EmitterState::SetOutputCharset(EMITTER_MANIP value, FmtScope::value scope) bool EmitterState::SetOutputCharset(EMITTER_MANIP value,
{ FmtScope::value scope) {
switch (value) { switch (value) {
case EmitNonAscii: case EmitNonAscii:
case EscapeNonAscii: case EscapeNonAscii:
@@ -239,8 +213,7 @@ namespace YAML
} }
} }
bool EmitterState::SetStringFormat(EMITTER_MANIP value, FmtScope::value scope) bool EmitterState::SetStringFormat(EMITTER_MANIP value, FmtScope::value scope) {
{
switch (value) { switch (value) {
case Auto: case Auto:
case SingleQuoted: case SingleQuoted:
@@ -253,8 +226,7 @@ namespace YAML
} }
} }
bool EmitterState::SetBoolFormat(EMITTER_MANIP value, FmtScope::value scope) bool EmitterState::SetBoolFormat(EMITTER_MANIP value, FmtScope::value scope) {
{
switch (value) { switch (value) {
case OnOffBool: case OnOffBool:
case TrueFalseBool: case TrueFalseBool:
@@ -266,8 +238,8 @@ namespace YAML
} }
} }
bool EmitterState::SetBoolLengthFormat(EMITTER_MANIP value, FmtScope::value scope) bool EmitterState::SetBoolLengthFormat(EMITTER_MANIP value,
{ FmtScope::value scope) {
switch (value) { switch (value) {
case LongBool: case LongBool:
case ShortBool: case ShortBool:
@@ -278,8 +250,8 @@ namespace YAML
} }
} }
bool EmitterState::SetBoolCaseFormat(EMITTER_MANIP value, FmtScope::value scope) bool EmitterState::SetBoolCaseFormat(EMITTER_MANIP value,
{ FmtScope::value scope) {
switch (value) { switch (value) {
case UpperCase: case UpperCase:
case LowerCase: case LowerCase:
@@ -291,8 +263,7 @@ namespace YAML
} }
} }
bool EmitterState::SetIntFormat(EMITTER_MANIP value, FmtScope::value scope) bool EmitterState::SetIntFormat(EMITTER_MANIP value, FmtScope::value scope) {
{
switch (value) { switch (value) {
case Dec: case Dec:
case Hex: case Hex:
@@ -304,8 +275,7 @@ namespace YAML
} }
} }
bool EmitterState::SetIndent(unsigned value, FmtScope::value scope) bool EmitterState::SetIndent(unsigned value, FmtScope::value scope) {
{
if (value <= 1) if (value <= 1)
return false; return false;
@@ -313,8 +283,7 @@ namespace YAML
return true; return true;
} }
bool EmitterState::SetPreCommentIndent(unsigned value, FmtScope::value scope) bool EmitterState::SetPreCommentIndent(unsigned value, FmtScope::value scope) {
{
if (value == 0) if (value == 0)
return false; return false;
@@ -322,8 +291,7 @@ namespace YAML
return true; return true;
} }
bool EmitterState::SetPostCommentIndent(unsigned value, FmtScope::value scope) bool EmitterState::SetPostCommentIndent(unsigned value, FmtScope::value scope) {
{
if (value == 0) if (value == 0)
return false; return false;
@@ -331,8 +299,8 @@ namespace YAML
return true; return true;
} }
bool EmitterState::SetFlowType(GroupType::value groupType, EMITTER_MANIP value, FmtScope::value scope) bool EmitterState::SetFlowType(GroupType::value groupType, EMITTER_MANIP value,
{ FmtScope::value scope) {
switch (value) { switch (value) {
case Block: case Block:
case Flow: case Flow:
@@ -343,8 +311,7 @@ namespace YAML
} }
} }
EMITTER_MANIP EmitterState::GetFlowType(GroupType::value groupType) const EMITTER_MANIP EmitterState::GetFlowType(GroupType::value groupType) const {
{
// force flow style if we're currently in a flow // force flow style if we're currently in a flow
if (CurGroupFlowType() == FlowType::Flow) if (CurGroupFlowType() == FlowType::Flow)
return Flow; return Flow;
@@ -353,8 +320,7 @@ namespace YAML
return (groupType == GroupType::Seq ? m_seqFmt.get() : m_mapFmt.get()); return (groupType == GroupType::Seq ? m_seqFmt.get() : m_mapFmt.get());
} }
bool EmitterState::SetMapKeyFormat(EMITTER_MANIP value, FmtScope::value scope) bool EmitterState::SetMapKeyFormat(EMITTER_MANIP value, FmtScope::value scope) {
{
switch (value) { switch (value) {
case Auto: case Auto:
case LongKey: case LongKey:
@@ -365,20 +331,17 @@ namespace YAML
} }
} }
bool EmitterState::SetFloatPrecision(int value, FmtScope::value scope) bool EmitterState::SetFloatPrecision(int value, FmtScope::value scope) {
{
if (value < 0 || value > std::numeric_limits<float>::digits10 + 1) if (value < 0 || value > std::numeric_limits<float>::digits10 + 1)
return false; return false;
_Set(m_floatPrecision, value, scope); _Set(m_floatPrecision, value, scope);
return true; return true;
} }
bool EmitterState::SetDoublePrecision(int value, FmtScope::value scope) bool EmitterState::SetDoublePrecision(int value, FmtScope::value scope) {
{
if (value < 0 || value > std::numeric_limits<double>::digits10 + 1) if (value < 0 || value > std::numeric_limits<double>::digits10 + 1)
return false; return false;
_Set(m_doublePrecision, value, scope); _Set(m_doublePrecision, value, scope);
return true; return true;
} }
} }

View File

@@ -1,11 +1,12 @@
#ifndef EMITTERSTATE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef EMITTERSTATE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define EMITTERSTATE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define EMITTERSTATE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "ptr_stack.h" #include "ptr_stack.h"
#include "setting.h" #include "setting.h"
#include "yaml-cpp/emitterdef.h" #include "yaml-cpp/emitterdef.h"
@@ -16,14 +17,29 @@
#include <memory> #include <memory>
#include <stdexcept> #include <stdexcept>
namespace YAML namespace YAML {
{ struct FmtScope {
struct FmtScope { enum value { Local, Global }; }; enum value {
struct GroupType { enum value { None, Seq, Map }; }; Local,
struct FlowType { enum value { None, Flow, Block }; }; Global
};
};
struct GroupType {
enum value {
None,
Seq,
Map
};
};
struct FlowType {
enum value {
None,
Flow,
Block
};
};
class EmitterState class EmitterState {
{
public: public:
EmitterState(); EmitterState();
~EmitterState(); ~EmitterState();
@@ -31,7 +47,10 @@ namespace YAML
// basic state checking // basic state checking
bool good() const { return m_isGood; } bool good() const { return m_isGood; }
const std::string GetLastError() const { return m_lastError; } const std::string GetLastError() const { return m_lastError; }
void SetError(const std::string& error) { m_isGood = false; m_lastError = error; } void SetError(const std::string& error) {
m_isGood = false;
m_lastError = error;
}
// node handling // node handling
void SetAnchor(); void SetAnchor();
@@ -58,7 +77,9 @@ namespace YAML
int CurIndent() const { return m_curIndent; } int CurIndent() const { return m_curIndent; }
bool HasAnchor() const { return m_hasAnchor; } bool HasAnchor() const { return m_hasAnchor; }
bool HasTag() const { return m_hasTag; } bool HasTag() const { return m_hasTag; }
bool HasBegunNode() const { return m_hasAnchor || m_hasTag || m_hasNonContent; } bool HasBegunNode() const {
return m_hasAnchor || m_hasTag || m_hasNonContent;
}
bool HasBegunContent() const { return m_hasAnchor || m_hasTag; } bool HasBegunContent() const { return m_hasAnchor || m_hasTag; }
void ClearModifiedSettings(); void ClearModifiedSettings();
@@ -92,7 +113,8 @@ namespace YAML
bool SetPostCommentIndent(unsigned value, FmtScope::value scope); bool SetPostCommentIndent(unsigned value, FmtScope::value scope);
int GetPostCommentIndent() const { return m_postCommentIndent.get(); } int GetPostCommentIndent() const { return m_postCommentIndent.get(); }
bool SetFlowType(GroupType::value groupType, EMITTER_MANIP value, FmtScope::value scope); bool SetFlowType(GroupType::value groupType, EMITTER_MANIP value,
FmtScope::value scope);
EMITTER_MANIP GetFlowType(GroupType::value groupType) const; EMITTER_MANIP GetFlowType(GroupType::value groupType) const;
bool SetMapKeyFormat(EMITTER_MANIP value, FmtScope::value scope); bool SetMapKeyFormat(EMITTER_MANIP value, FmtScope::value scope);
@@ -133,7 +155,8 @@ namespace YAML
SettingChanges m_globalModifiedSettings; SettingChanges m_globalModifiedSettings;
struct Group { struct Group {
explicit Group(GroupType::value type_): type(type_), indent(0), childCount(0), longKey(false) {} explicit Group(GroupType::value type_)
: type(type_), indent(0), childCount(0), longKey(false) {}
GroupType::value type; GroupType::value type;
FlowType::value flowType; FlowType::value flowType;
@@ -178,7 +201,8 @@ namespace YAML
break; break;
case FmtScope::Global: case FmtScope::Global:
fmt.set(value); fmt.set(value);
m_globalModifiedSettings.push(fmt.set(value)); // this pushes an identity set, so when we restore, m_globalModifiedSettings.push(
fmt.set(value)); // this pushes an identity set, so when we restore,
// it restores to the value here, and not the previous one // it restores to the value here, and not the previous one
break; break;
default: default:

View File

@@ -7,19 +7,25 @@
#include <sstream> #include <sstream>
#include <iomanip> #include <iomanip>
namespace YAML namespace YAML {
{ namespace Utils {
namespace Utils
{
namespace { namespace {
enum {REPLACEMENT_CHARACTER = 0xFFFD}; enum {
REPLACEMENT_CHARACTER = 0xFFFD
};
bool IsAnchorChar(int ch) { // test for ns-anchor-char bool IsAnchorChar(int ch) { // test for ns-anchor-char
switch (ch) { switch (ch) {
case ',': case '[': case ']': case '{': case '}': // c-flow-indicator case ',':
case ' ': case '\t': // s-white case '[':
case ']':
case '{':
case '}': // c-flow-indicator
case ' ':
case '\t': // s-white
case 0xFEFF: // c-byte-order-mark case 0xFEFF: // c-byte-order-mark
case 0xA: case 0xD: // b-char case 0xA:
case 0xD: // b-char
return false; return false;
case 0x85: case 0x85:
return true; return true;
@@ -48,9 +54,17 @@ namespace YAML
int Utf8BytesIndicated(char ch) { int Utf8BytesIndicated(char ch) {
int byteVal = static_cast<unsigned char>(ch); int byteVal = static_cast<unsigned char>(ch);
switch (byteVal >> 4) { switch (byteVal >> 4) {
case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return 1; return 1;
case 12: case 13: case 12:
case 13:
return 2; return 2;
case 14: case 14:
return 3; return 3;
@@ -61,11 +75,11 @@ namespace YAML
} }
} }
bool IsTrailingByte(char ch) { bool IsTrailingByte(char ch) { return (ch & 0xC0) == 0x80; }
return (ch & 0xC0) == 0x80;
}
bool GetNextCodePointAndAdvance(int& codePoint, std::string::const_iterator& first, std::string::const_iterator last) { bool GetNextCodePointAndAdvance(int& codePoint,
std::string::const_iterator& first,
std::string::const_iterator last) {
if (first == last) if (first == last)
return false; return false;
@@ -128,26 +142,28 @@ namespace YAML
} }
} }
bool IsValidPlainScalar(const std::string& str, FlowType::value flowType, bool allowOnlyAscii) { bool IsValidPlainScalar(const std::string& str, FlowType::value flowType,
bool allowOnlyAscii) {
if (str.empty()) if (str.empty())
return false; return false;
// first check the start // first check the start
const RegEx& start = (flowType == FlowType::Flow ? Exp::PlainScalarInFlow() : Exp::PlainScalar()); const RegEx& start = (flowType == FlowType::Flow ? Exp::PlainScalarInFlow()
: Exp::PlainScalar());
if (!start.Matches(str)) if (!start.Matches(str))
return false; return false;
// and check the end for plain whitespace (which can't be faithfully kept in a plain scalar) // and check the end for plain whitespace (which can't be faithfully kept in a
// plain scalar)
if (!str.empty() && *str.rbegin() == ' ') if (!str.empty() && *str.rbegin() == ' ')
return false; return false;
// then check until something is disallowed // then check until something is disallowed
const RegEx& disallowed = (flowType == FlowType::Flow ? Exp::EndScalarInFlow() : Exp::EndScalar()) const RegEx& disallowed = (flowType == FlowType::Flow ? Exp::EndScalarInFlow()
|| (Exp::BlankOrBreak() + Exp::Comment()) : Exp::EndScalar()) ||
|| Exp::NotPrintable() (Exp::BlankOrBreak() + Exp::Comment()) ||
|| Exp::Utf8_ByteOrderMark() Exp::NotPrintable() || Exp::Utf8_ByteOrderMark() ||
|| Exp::Break() Exp::Break() || Exp::Tab();
|| Exp::Tab();
StringCharSource buffer(str.c_str(), str.size()); StringCharSource buffer(str.c_str(), str.size());
while (buffer) { while (buffer) {
if (disallowed.Matches(buffer)) if (disallowed.Matches(buffer))
@@ -160,8 +176,7 @@ namespace YAML
return true; return true;
} }
bool IsValidSingleQuotedScalar(const std::string& str, bool escapeNonAscii) bool IsValidSingleQuotedScalar(const std::string& str, bool escapeNonAscii) {
{
// TODO: check for non-printable characters? // TODO: check for non-printable characters?
for (std::size_t i = 0; i < str.size(); i++) { for (std::size_t i = 0; i < str.size(); i++) {
if (escapeNonAscii && (0x80 <= static_cast<unsigned char>(str[i]))) if (escapeNonAscii && (0x80 <= static_cast<unsigned char>(str[i])))
@@ -172,8 +187,8 @@ namespace YAML
return true; return true;
} }
bool IsValidLiteralScalar(const std::string& str, FlowType::value flowType, bool escapeNonAscii) bool IsValidLiteralScalar(const std::string& str, FlowType::value flowType,
{ bool escapeNonAscii) {
if (flowType == FlowType::Flow) if (flowType == FlowType::Flow)
return false; return false;
@@ -209,9 +224,7 @@ namespace YAML
bool WriteAliasName(ostream_wrapper& out, const std::string& str) { bool WriteAliasName(ostream_wrapper& out, const std::string& str) {
int codePoint; int codePoint;
for (std::string::const_iterator i = str.begin(); for (std::string::const_iterator i = str.begin();
GetNextCodePointAndAdvance(codePoint, i, str.end()); GetNextCodePointAndAdvance(codePoint, i, str.end());) {
)
{
if (!IsAnchorChar(codePoint)) if (!IsAnchorChar(codePoint))
return false; return false;
@@ -221,8 +234,10 @@ namespace YAML
} }
} }
StringFormat::value ComputeStringFormat(const std::string& str, EMITTER_MANIP strFormat, FlowType::value flowType, bool escapeNonAscii) StringFormat::value ComputeStringFormat(const std::string& str,
{ EMITTER_MANIP strFormat,
FlowType::value flowType,
bool escapeNonAscii) {
switch (strFormat) { switch (strFormat) {
case Auto: case Auto:
if (IsValidPlainScalar(str, flowType, escapeNonAscii)) if (IsValidPlainScalar(str, flowType, escapeNonAscii))
@@ -245,16 +260,14 @@ namespace YAML
return StringFormat::DoubleQuoted; return StringFormat::DoubleQuoted;
} }
bool WriteSingleQuotedString(ostream_wrapper& out, const std::string& str) bool WriteSingleQuotedString(ostream_wrapper& out, const std::string& str) {
{
out << "'"; out << "'";
int codePoint; int codePoint;
for (std::string::const_iterator i = str.begin(); for (std::string::const_iterator i = str.begin();
GetNextCodePointAndAdvance(codePoint, i, str.end()); GetNextCodePointAndAdvance(codePoint, i, str.end());) {
)
{
if (codePoint == '\n') if (codePoint == '\n')
return false; // We can't handle a new line and the attendant indentation yet return false; // We can't handle a new line and the attendant indentation
// yet
if (codePoint == '\'') if (codePoint == '\'')
out << "''"; out << "''";
@@ -265,25 +278,38 @@ namespace YAML
return true; return true;
} }
bool WriteDoubleQuotedString(ostream_wrapper& out, const std::string& str, bool escapeNonAscii) bool WriteDoubleQuotedString(ostream_wrapper& out, const std::string& str,
{ bool escapeNonAscii) {
out << "\""; out << "\"";
int codePoint; int codePoint;
for (std::string::const_iterator i = str.begin(); for (std::string::const_iterator i = str.begin();
GetNextCodePointAndAdvance(codePoint, i, str.end()); GetNextCodePointAndAdvance(codePoint, i, str.end());) {
)
{
switch (codePoint) { switch (codePoint) {
case '\"': out << "\\\""; break; case '\"':
case '\\': out << "\\\\"; break; out << "\\\"";
case '\n': out << "\\n"; break; break;
case '\t': out << "\\t"; break; case '\\':
case '\r': out << "\\r"; break; out << "\\\\";
case '\b': out << "\\b"; break; break;
case '\n':
out << "\\n";
break;
case '\t':
out << "\\t";
break;
case '\r':
out << "\\r";
break;
case '\b':
out << "\\b";
break;
default: default:
if(codePoint < 0x20 || (codePoint >= 0x80 && codePoint <= 0xA0)) // Control characters and non-breaking space if (codePoint < 0x20 ||
(codePoint >= 0x80 &&
codePoint <= 0xA0)) // Control characters and non-breaking space
WriteDoubleQuoteEscapeSequence(out, codePoint); WriteDoubleQuoteEscapeSequence(out, codePoint);
else if (codePoint == 0xFEFF) // Byte order marks (ZWNS) should be escaped (YAML 1.2, sec. 5.2) else if (codePoint == 0xFEFF) // Byte order marks (ZWNS) should be
// escaped (YAML 1.2, sec. 5.2)
WriteDoubleQuoteEscapeSequence(out, codePoint); WriteDoubleQuoteEscapeSequence(out, codePoint);
else if (escapeNonAscii && codePoint > 0x7E) else if (escapeNonAscii && codePoint > 0x7E)
WriteDoubleQuoteEscapeSequence(out, codePoint); WriteDoubleQuoteEscapeSequence(out, codePoint);
@@ -295,15 +321,13 @@ namespace YAML
return true; return true;
} }
bool WriteLiteralString(ostream_wrapper& out, const std::string& str, int indent) bool WriteLiteralString(ostream_wrapper& out, const std::string& str,
{ int indent) {
out << "|\n"; out << "|\n";
out << IndentTo(indent); out << IndentTo(indent);
int codePoint; int codePoint;
for (std::string::const_iterator i = str.begin(); for (std::string::const_iterator i = str.begin();
GetNextCodePointAndAdvance(codePoint, i, str.end()); GetNextCodePointAndAdvance(codePoint, i, str.end());) {
)
{
if (codePoint == '\n') if (codePoint == '\n')
out << "\n" << IndentTo(indent); out << "\n" << IndentTo(indent);
else else
@@ -312,8 +336,7 @@ namespace YAML
return true; return true;
} }
bool WriteChar(ostream_wrapper& out, char ch) bool WriteChar(ostream_wrapper& out, char ch) {
{
if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z')) if (('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z'))
out << ch; out << ch;
else if ((0x20 <= ch && ch <= 0x7e) || ch == ' ') else if ((0x20 <= ch && ch <= 0x7e) || ch == ' ')
@@ -332,18 +355,17 @@ namespace YAML
return true; return true;
} }
bool WriteComment(ostream_wrapper& out, const std::string& str, int postCommentIndent) bool WriteComment(ostream_wrapper& out, const std::string& str,
{ int postCommentIndent) {
const unsigned curIndent = out.col(); const unsigned curIndent = out.col();
out << "#" << Indentation(postCommentIndent); out << "#" << Indentation(postCommentIndent);
out.set_comment(); out.set_comment();
int codePoint; int codePoint;
for (std::string::const_iterator i = str.begin(); for (std::string::const_iterator i = str.begin();
GetNextCodePointAndAdvance(codePoint, i, str.end()); GetNextCodePointAndAdvance(codePoint, i, str.end());) {
)
{
if (codePoint == '\n') { if (codePoint == '\n') {
out << "\n" << IndentTo(curIndent) << "#" << Indentation(postCommentIndent); out << "\n" << IndentTo(curIndent) << "#"
<< Indentation(postCommentIndent);
out.set_comment(); out.set_comment();
} else { } else {
WriteCodePoint(out, codePoint); WriteCodePoint(out, codePoint);
@@ -352,20 +374,17 @@ namespace YAML
return true; return true;
} }
bool WriteAlias(ostream_wrapper& out, const std::string& str) bool WriteAlias(ostream_wrapper& out, const std::string& str) {
{
out << "*"; out << "*";
return WriteAliasName(out, str); return WriteAliasName(out, str);
} }
bool WriteAnchor(ostream_wrapper& out, const std::string& str) bool WriteAnchor(ostream_wrapper& out, const std::string& str) {
{
out << "&"; out << "&";
return WriteAliasName(out, str); return WriteAliasName(out, str);
} }
bool WriteTag(ostream_wrapper& out, const std::string& str, bool verbatim) bool WriteTag(ostream_wrapper& out, const std::string& str, bool verbatim) {
{
out << (verbatim ? "!<" : "!"); out << (verbatim ? "!<" : "!");
StringCharSource buffer(str.c_str(), str.size()); StringCharSource buffer(str.c_str(), str.size());
const RegEx& reValid = verbatim ? Exp::URI() : Exp::Tag(); const RegEx& reValid = verbatim ? Exp::URI() : Exp::Tag();
@@ -384,8 +403,8 @@ namespace YAML
return true; return true;
} }
bool WriteTagWithPrefix(ostream_wrapper& out, const std::string& prefix, const std::string& tag) bool WriteTagWithPrefix(ostream_wrapper& out, const std::string& prefix,
{ const std::string& tag) {
out << "!"; out << "!";
StringCharSource prefixBuffer(prefix.c_str(), prefix.size()); StringCharSource prefixBuffer(prefix.c_str(), prefix.size());
while (prefixBuffer) { while (prefixBuffer) {
@@ -414,11 +433,10 @@ namespace YAML
return true; return true;
} }
bool WriteBinary(ostream_wrapper& out, const Binary& binary) bool WriteBinary(ostream_wrapper& out, const Binary& binary) {
{ WriteDoubleQuotedString(out, EncodeBase64(binary.data(), binary.size()),
WriteDoubleQuotedString(out, EncodeBase64(binary.data(), binary.size()), false); false);
return true; return true;
} }
} }
} }

View File

@@ -1,34 +1,47 @@
#ifndef EMITTERUTILS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef EMITTERUTILS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define EMITTERUTILS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define EMITTERUTILS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "emitterstate.h" #include "emitterstate.h"
#include "yaml-cpp/ostream_wrapper.h" #include "yaml-cpp/ostream_wrapper.h"
#include <string> #include <string>
namespace YAML namespace YAML {
{
class Binary; class Binary;
struct StringFormat { enum value { Plain, SingleQuoted, DoubleQuoted, Literal }; }; struct StringFormat {
enum value {
Plain,
SingleQuoted,
DoubleQuoted,
Literal
};
};
namespace Utils namespace Utils {
{ StringFormat::value ComputeStringFormat(const std::string& str,
StringFormat::value ComputeStringFormat(const std::string& str, EMITTER_MANIP strFormat, FlowType::value flowType, bool escapeNonAscii); EMITTER_MANIP strFormat,
FlowType::value flowType,
bool escapeNonAscii);
bool WriteSingleQuotedString(ostream_wrapper& out, const std::string& str); bool WriteSingleQuotedString(ostream_wrapper& out, const std::string& str);
bool WriteDoubleQuotedString(ostream_wrapper& out, const std::string& str, bool escapeNonAscii); bool WriteDoubleQuotedString(ostream_wrapper& out, const std::string& str,
bool WriteLiteralString(ostream_wrapper& out, const std::string& str, int indent); bool escapeNonAscii);
bool WriteLiteralString(ostream_wrapper& out, const std::string& str,
int indent);
bool WriteChar(ostream_wrapper& out, char ch); bool WriteChar(ostream_wrapper& out, char ch);
bool WriteComment(ostream_wrapper& out, const std::string& str, int postCommentIndent); bool WriteComment(ostream_wrapper& out, const std::string& str,
int postCommentIndent);
bool WriteAlias(ostream_wrapper& out, const std::string& str); bool WriteAlias(ostream_wrapper& out, const std::string& str);
bool WriteAnchor(ostream_wrapper& out, const std::string& str); bool WriteAnchor(ostream_wrapper& out, const std::string& str);
bool WriteTag(ostream_wrapper& out, const std::string& str, bool verbatim); bool WriteTag(ostream_wrapper& out, const std::string& str, bool verbatim);
bool WriteTagWithPrefix(ostream_wrapper& out, const std::string& prefix, const std::string& tag); bool WriteTagWithPrefix(ostream_wrapper& out, const std::string& prefix,
const std::string& tag);
bool WriteBinary(ostream_wrapper& out, const Binary& binary); bool WriteBinary(ostream_wrapper& out, const Binary& binary);
} }
} }

View File

@@ -2,12 +2,9 @@
#include "yaml-cpp/exceptions.h" #include "yaml-cpp/exceptions.h"
#include <sstream> #include <sstream>
namespace YAML namespace YAML {
{ namespace Exp {
namespace Exp unsigned ParseHex(const std::string& str, const Mark& mark) {
{
unsigned ParseHex(const std::string& str, const Mark& mark)
{
unsigned value = 0; unsigned value = 0;
for (std::size_t i = 0; i < str.size(); i++) { for (std::size_t i = 0; i < str.size(); i++) {
char ch = str[i]; char ch = str[i];
@@ -27,16 +24,13 @@ namespace YAML
return value; return value;
} }
std::string Str(unsigned ch) std::string Str(unsigned ch) { return std::string(1, static_cast<char>(ch)); }
{
return std::string(1, static_cast<char>(ch));
}
// Escape // Escape
// . Translates the next 'codeLength' characters into a hex number and returns the result. // . Translates the next 'codeLength' characters into a hex number and returns
// the result.
// . Throws if it's not actually hex. // . Throws if it's not actually hex.
std::string Escape(Stream& in, int codeLength) std::string Escape(Stream& in, int codeLength) {
{
// grab string // grab string
std::string str; std::string str;
for (int i = 0; i < codeLength; i++) for (int i = 0; i < codeLength; i++)
@@ -58,18 +52,19 @@ namespace YAML
else if (value <= 0x7FF) else if (value <= 0x7FF)
return Str(0xC0 + (value >> 6)) + Str(0x80 + (value & 0x3F)); return Str(0xC0 + (value >> 6)) + Str(0x80 + (value & 0x3F));
else if (value <= 0xFFFF) else if (value <= 0xFFFF)
return Str(0xE0 + (value >> 12)) + Str(0x80 + ((value >> 6) & 0x3F)) + Str(0x80 + (value & 0x3F)); return Str(0xE0 + (value >> 12)) + Str(0x80 + ((value >> 6) & 0x3F)) +
Str(0x80 + (value & 0x3F));
else else
return Str(0xF0 + (value >> 18)) + Str(0x80 + ((value >> 12) & 0x3F)) + return Str(0xF0 + (value >> 18)) + Str(0x80 + ((value >> 12) & 0x3F)) +
Str(0x80 + ((value >> 6) & 0x3F)) + Str(0x80 + (value & 0x3F)); Str(0x80 + ((value >> 6) & 0x3F)) + Str(0x80 + (value & 0x3F));
} }
// Escape // Escape
// . Escapes the sequence starting 'in' (it must begin with a '\' or single quote) // . Escapes the sequence starting 'in' (it must begin with a '\' or single
// quote)
// and returns the result. // and returns the result.
// . Throws if it's an unknown escape character. // . Throws if it's an unknown escape character.
std::string Escape(Stream& in) std::string Escape(Stream& in) {
{
// eat slash // eat slash
char escape = in.get(); char escape = in.get();
@@ -80,30 +75,52 @@ namespace YAML
if (escape == '\'' && ch == '\'') if (escape == '\'' && ch == '\'')
return "\'"; return "\'";
// now do the slash (we're not gonna check if it's a slash - you better pass one!) // now do the slash (we're not gonna check if it's a slash - you better pass
// one!)
switch (ch) { switch (ch) {
case '0': return std::string(1, '\x00'); case '0':
case 'a': return "\x07"; return std::string(1, '\x00');
case 'b': return "\x08"; case 'a':
return "\x07";
case 'b':
return "\x08";
case 't': case 't':
case '\t': return "\x09"; case '\t':
case 'n': return "\x0A"; return "\x09";
case 'v': return "\x0B"; case 'n':
case 'f': return "\x0C"; return "\x0A";
case 'r': return "\x0D"; case 'v':
case 'e': return "\x1B"; return "\x0B";
case ' ': return "\x20"; case 'f':
case '\"': return "\""; return "\x0C";
case '\'': return "\'"; case 'r':
case '\\': return "\\"; return "\x0D";
case '/': return "/"; case 'e':
case 'N': return "\x85"; return "\x1B";
case '_': return "\xA0"; case ' ':
case 'L': return "\xE2\x80\xA8"; // LS (#x2028) return "\x20";
case 'P': return "\xE2\x80\xA9"; // PS (#x2029) case '\"':
case 'x': return Escape(in, 2); return "\"";
case 'u': return Escape(in, 4); case '\'':
case 'U': return Escape(in, 8); return "\'";
case '\\':
return "\\";
case '/':
return "/";
case 'N':
return "\x85";
case '_':
return "\xA0";
case 'L':
return "\xE2\x80\xA8"; // LS (#x2028)
case 'P':
return "\xE2\x80\xA9"; // PS (#x2029)
case 'x':
return Escape(in, 2);
case 'u':
return Escape(in, 4);
case 'U':
return Escape(in, 8);
} }
std::stringstream msg; std::stringstream msg;

View File

@@ -1,23 +1,23 @@
#ifndef EXP_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef EXP_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define EXP_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define EXP_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "regex.h" #include "regex.h"
#include <string> #include <string>
#include <ios> #include <ios>
#include "stream.h" #include "stream.h"
namespace YAML namespace YAML {
{
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// Here we store a bunch of expressions for matching different parts of the file. // Here we store a bunch of expressions for matching different parts of the
// file.
namespace Exp namespace Exp {
{
// misc // misc
inline const RegEx& Space() { inline const RegEx& Space() {
static const RegEx e = RegEx(' '); static const RegEx e = RegEx(' ');
@@ -59,9 +59,11 @@ namespace YAML
static const RegEx e = Digit() || RegEx('A', 'F') || RegEx('a', 'f'); static const RegEx e = Digit() || RegEx('A', 'F') || RegEx('a', 'f');
return e; return e;
} }
// Valid Unicode code points that are not part of c-printable (YAML 1.2, sec. 5.1) // Valid Unicode code points that are not part of c-printable (YAML 1.2, sec.
// 5.1)
inline const RegEx& NotPrintable() { inline const RegEx& NotPrintable() {
static const RegEx e = RegEx(0) || static const RegEx e =
RegEx(0) ||
RegEx("\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x7F", REGEX_OR) || RegEx("\x01\x02\x03\x04\x05\x06\x07\x08\x0B\x0C\x7F", REGEX_OR) ||
RegEx(0x0E, 0x1F) || RegEx(0x0E, 0x1F) ||
(RegEx('\xC2') + (RegEx('\x80', '\x84') || RegEx('\x86', '\x9F'))); (RegEx('\xC2') + (RegEx('\x80', '\x84') || RegEx('\x86', '\x9F')));
@@ -123,11 +125,13 @@ namespace YAML
return e; return e;
} }
inline const RegEx& URI() { inline const RegEx& URI() {
static const RegEx e = Word() || RegEx("#;/?:@&=+$,_.!~*'()[]", REGEX_OR) || (RegEx('%') + Hex() + Hex()); static const RegEx e = Word() || RegEx("#;/?:@&=+$,_.!~*'()[]", REGEX_OR) ||
(RegEx('%') + Hex() + Hex());
return e; return e;
} }
inline const RegEx& Tag() { inline const RegEx& Tag() {
static const RegEx e = Word() || RegEx("#;/?:@&=+$_.~*'", REGEX_OR) || (RegEx('%') + Hex() + Hex()); static const RegEx e = Word() || RegEx("#;/?:@&=+$_.~*'", REGEX_OR) ||
(RegEx('%') + Hex() + Hex());
return e; return e;
} }
@@ -135,13 +139,18 @@ namespace YAML
// . Cannot start with a blank. // . Cannot start with a blank.
// . Can never start with any of , [ ] { } # & * ! | > \' \" % @ ` // . Can never start with any of , [ ] { } # & * ! | > \' \" % @ `
// . In the block context - ? : must be not be followed with a space. // . In the block context - ? : must be not be followed with a space.
// . In the flow context ? is illegal and : and - must not be followed with a space. // . In the flow context ? is illegal and : and - must not be followed with a
// space.
inline const RegEx& PlainScalar() { inline const RegEx& PlainScalar() {
static const RegEx e = !(BlankOrBreak() || RegEx(",[]{}#&*!|>\'\"%@`", REGEX_OR) || (RegEx("-?:", REGEX_OR) + (BlankOrBreak() || RegEx()))); static const RegEx e =
!(BlankOrBreak() || RegEx(",[]{}#&*!|>\'\"%@`", REGEX_OR) ||
(RegEx("-?:", REGEX_OR) + (BlankOrBreak() || RegEx())));
return e; return e;
} }
inline const RegEx& PlainScalarInFlow() { inline const RegEx& PlainScalarInFlow() {
static const RegEx e = !(BlankOrBreak() || RegEx("?,[]{}#&*!|>\'\"%@`", REGEX_OR) || (RegEx("-:", REGEX_OR) + Blank())); static const RegEx e =
!(BlankOrBreak() || RegEx("?,[]{}#&*!|>\'\"%@`", REGEX_OR) ||
(RegEx("-:", REGEX_OR) + Blank()));
return e; return e;
} }
inline const RegEx& EndScalar() { inline const RegEx& EndScalar() {
@@ -149,7 +158,9 @@ namespace YAML
return e; return e;
} }
inline const RegEx& EndScalarInFlow() { inline const RegEx& EndScalarInFlow() {
static const RegEx e = (RegEx(':') + (BlankOrBreak() || RegEx() || RegEx(",]}", REGEX_OR))) || RegEx(",?[]{}", REGEX_OR); static const RegEx e =
(RegEx(':') + (BlankOrBreak() || RegEx() || RegEx(",]}", REGEX_OR))) ||
RegEx(",?[]{}", REGEX_OR);
return e; return e;
} }
@@ -167,7 +178,9 @@ namespace YAML
return e; return e;
} }
inline const RegEx& Chomp() { inline const RegEx& Chomp() {
static const RegEx e = (ChompIndicator() + Digit()) || (Digit() + ChompIndicator()) || ChompIndicator() || Digit(); static const RegEx e = (ChompIndicator() + Digit()) ||
(Digit() + ChompIndicator()) || ChompIndicator() ||
Digit();
return e; return e;
} }
@@ -175,8 +188,7 @@ namespace YAML
std::string Escape(Stream& in); std::string Escape(Stream& in);
} }
namespace Keys namespace Keys {
{
const char Directive = '%'; const char Directive = '%';
const char FlowSeqStart = '['; const char FlowSeqStart = '[';
const char FlowSeqEnd = ']'; const char FlowSeqEnd = ']';

View File

@@ -1,22 +1,23 @@
#ifndef INDENTATION_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef INDENTATION_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define INDENTATION_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define INDENTATION_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/ostream_wrapper.h" #include "yaml-cpp/ostream_wrapper.h"
#include <iostream> #include <iostream>
namespace YAML namespace YAML {
{
struct Indentation { struct Indentation {
Indentation(unsigned n_) : n(n_) {} Indentation(unsigned n_) : n(n_) {}
unsigned n; unsigned n;
}; };
inline ostream_wrapper& operator << (ostream_wrapper& out, const Indentation& indent) { inline ostream_wrapper& operator<<(ostream_wrapper& out,
const Indentation& indent) {
for (unsigned i = 0; i < indent.n; i++) for (unsigned i = 0; i < indent.n; i++)
out << ' '; out << ' ';
return out; return out;
@@ -27,12 +28,12 @@ namespace YAML
unsigned n; unsigned n;
}; };
inline ostream_wrapper& operator << (ostream_wrapper& out, const IndentTo& indent) { inline ostream_wrapper& operator<<(ostream_wrapper& out,
const IndentTo& indent) {
while (out.col() < indent.n) while (out.col() < indent.n)
out << ' '; out << ' ';
return out; return out;
} }
} }
#endif // INDENTATION_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // INDENTATION_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -1,6 +1,5 @@
#include "yaml-cpp/null.h" #include "yaml-cpp/null.h"
namespace YAML namespace YAML {
{
_Null Null; _Null Null;
} }

View File

@@ -9,28 +9,18 @@
#include <sstream> #include <sstream>
#include <cstdio> #include <cstdio>
namespace YAML namespace YAML {
{ Parser::Parser() {}
Parser::Parser()
{
}
Parser::Parser(std::istream& in) Parser::Parser(std::istream& in) { Load(in); }
{
Load(in);
}
Parser::~Parser() Parser::~Parser() {}
{
}
Parser::operator bool() const Parser::operator bool() const {
{
return m_pScanner.get() && !m_pScanner->empty(); return m_pScanner.get() && !m_pScanner->empty();
} }
void Parser::Load(std::istream& in) void Parser::Load(std::istream& in) {
{
m_pScanner.reset(new Scanner(in)); m_pScanner.reset(new Scanner(in));
m_pDirectives.reset(new Directives); m_pDirectives.reset(new Directives);
} }
@@ -39,8 +29,7 @@ namespace YAML
// . Handles the next document // . Handles the next document
// . Throws a ParserException on error. // . Throws a ParserException on error.
// . Returns false if there are no more documents // . Returns false if there are no more documents
bool Parser::HandleNextDocument(EventHandler& eventHandler) bool Parser::HandleNextDocument(EventHandler& eventHandler) {
{
if (!m_pScanner.get()) if (!m_pScanner.get())
return false; return false;
@@ -55,8 +44,7 @@ namespace YAML
// ParseDirectives // ParseDirectives
// . Reads any directives that are next in the queue. // . Reads any directives that are next in the queue.
void Parser::ParseDirectives() void Parser::ParseDirectives() {
{
bool readDirective = false; bool readDirective = false;
while (1) { while (1) {
@@ -78,8 +66,7 @@ namespace YAML
} }
} }
void Parser::HandleDirective(const Token& token) void Parser::HandleDirective(const Token& token) {
{
if (token.value == "YAML") if (token.value == "YAML")
HandleYamlDirective(token); HandleYamlDirective(token);
else if (token.value == "TAG") else if (token.value == "TAG")
@@ -88,8 +75,7 @@ namespace YAML
// HandleYamlDirective // HandleYamlDirective
// . Should be of the form 'major.minor' (like a version number) // . Should be of the form 'major.minor' (like a version number)
void Parser::HandleYamlDirective(const Token& token) void Parser::HandleYamlDirective(const Token& token) {
{
if (token.params.size() != 1) if (token.params.size() != 1)
throw ParserException(token.mark, ErrorMsg::YAML_DIRECTIVE_ARGS); throw ParserException(token.mark, ErrorMsg::YAML_DIRECTIVE_ARGS);
@@ -101,7 +87,8 @@ namespace YAML
str.get(); str.get();
str >> m_pDirectives->version.minor; str >> m_pDirectives->version.minor;
if (!str || str.peek() != EOF) if (!str || str.peek() != EOF)
throw ParserException(token.mark, std::string(ErrorMsg::YAML_VERSION) + token.params[0]); throw ParserException(
token.mark, std::string(ErrorMsg::YAML_VERSION) + token.params[0]);
if (m_pDirectives->version.major > 1) if (m_pDirectives->version.major > 1)
throw ParserException(token.mark, ErrorMsg::YAML_MAJOR_VERSION); throw ParserException(token.mark, ErrorMsg::YAML_MAJOR_VERSION);
@@ -111,9 +98,9 @@ namespace YAML
} }
// HandleTagDirective // HandleTagDirective
// . Should be of the form 'handle prefix', where 'handle' is converted to 'prefix' in the file. // . Should be of the form 'handle prefix', where 'handle' is converted to
void Parser::HandleTagDirective(const Token& token) // 'prefix' in the file.
{ void Parser::HandleTagDirective(const Token& token) {
if (token.params.size() != 2) if (token.params.size() != 2)
throw ParserException(token.mark, ErrorMsg::TAG_DIRECTIVE_ARGS); throw ParserException(token.mark, ErrorMsg::TAG_DIRECTIVE_ARGS);
@@ -125,8 +112,7 @@ namespace YAML
m_pDirectives->tags[handle] = prefix; m_pDirectives->tags[handle] = prefix;
} }
void Parser::PrintTokens(std::ostream& out) void Parser::PrintTokens(std::ostream& out) {
{
if (!m_pScanner.get()) if (!m_pScanner.get())
return; return;

View File

@@ -1,7 +1,9 @@
#ifndef PTR_STACK_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef PTR_STACK_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define PTR_STACK_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define PTR_STACK_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
@@ -12,8 +14,7 @@
#include <vector> #include <vector>
template <typename T> template <typename T>
class ptr_stack: private YAML::noncopyable class ptr_stack : private YAML::noncopyable {
{
public: public:
ptr_stack() {} ptr_stack() {}
~ptr_stack() { clear(); } ~ptr_stack() { clear(); }
@@ -40,7 +41,9 @@ public:
const T& top() const { return *m_data.back(); } const T& top() const { return *m_data.back(); }
T& top(std::ptrdiff_t diff) { return **(m_data.end() - 1 + diff); } T& top(std::ptrdiff_t diff) { return **(m_data.end() - 1 + diff); }
const T& top(std::ptrdiff_t diff) const { return **(m_data.end() - 1 + diff); } const T& top(std::ptrdiff_t diff) const {
return **(m_data.end() - 1 + diff);
}
private: private:
std::vector<T*> m_data; std::vector<T*> m_data;

View File

@@ -1,7 +1,9 @@
#ifndef PTR_VECTOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef PTR_VECTOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define PTR_VECTOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define PTR_VECTOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
@@ -14,8 +16,7 @@
namespace YAML { namespace YAML {
template <typename T> template <typename T>
class ptr_vector: private YAML::noncopyable class ptr_vector : private YAML::noncopyable {
{
public: public:
ptr_vector() {} ptr_vector() {}
~ptr_vector() { clear(); } ~ptr_vector() { clear(); }

View File

@@ -1,60 +1,45 @@
#include "regex.h" #include "regex.h"
namespace YAML namespace YAML {
{
// constructors // constructors
RegEx::RegEx(): m_op(REGEX_EMPTY) RegEx::RegEx() : m_op(REGEX_EMPTY) {}
{
}
RegEx::RegEx(REGEX_OP op): m_op(op) RegEx::RegEx(REGEX_OP op) : m_op(op) {}
{
}
RegEx::RegEx(char ch): m_op(REGEX_MATCH), m_a(ch) RegEx::RegEx(char ch) : m_op(REGEX_MATCH), m_a(ch) {}
{
}
RegEx::RegEx(char a, char z): m_op(REGEX_RANGE), m_a(a), m_z(z) RegEx::RegEx(char a, char z) : m_op(REGEX_RANGE), m_a(a), m_z(z) {}
{
}
RegEx::RegEx(const std::string& str, REGEX_OP op): m_op(op) RegEx::RegEx(const std::string& str, REGEX_OP op) : m_op(op) {
{
for (std::size_t i = 0; i < str.size(); i++) for (std::size_t i = 0; i < str.size(); i++)
m_params.push_back(RegEx(str[i])); m_params.push_back(RegEx(str[i]));
} }
// combination constructors // combination constructors
RegEx operator ! (const RegEx& ex) RegEx operator!(const RegEx & ex) {
{
RegEx ret(REGEX_NOT); RegEx ret(REGEX_NOT);
ret.m_params.push_back(ex); ret.m_params.push_back(ex);
return ret; return ret;
} }
RegEx operator || (const RegEx& ex1, const RegEx& ex2) RegEx operator||(const RegEx& ex1, const RegEx& ex2) {
{
RegEx ret(REGEX_OR); RegEx ret(REGEX_OR);
ret.m_params.push_back(ex1); ret.m_params.push_back(ex1);
ret.m_params.push_back(ex2); ret.m_params.push_back(ex2);
return ret; return ret;
} }
RegEx operator && (const RegEx& ex1, const RegEx& ex2) RegEx operator&&(const RegEx& ex1, const RegEx& ex2) {
{
RegEx ret(REGEX_AND); RegEx ret(REGEX_AND);
ret.m_params.push_back(ex1); ret.m_params.push_back(ex1);
ret.m_params.push_back(ex2); ret.m_params.push_back(ex2);
return ret; return ret;
} }
RegEx operator + (const RegEx& ex1, const RegEx& ex2) RegEx operator+(const RegEx& ex1, const RegEx& ex2) {
{
RegEx ret(REGEX_SEQ); RegEx ret(REGEX_SEQ);
ret.m_params.push_back(ex1); ret.m_params.push_back(ex1);
ret.m_params.push_back(ex2); ret.m_params.push_back(ex2);
return ret; return ret;
} }
} }

View File

@@ -1,25 +1,32 @@
#ifndef REGEX_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef REGEX_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define REGEX_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define REGEX_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <vector> #include <vector>
#include <string> #include <string>
namespace YAML namespace YAML {
{
class Stream; class Stream;
enum REGEX_OP { REGEX_EMPTY, REGEX_MATCH, REGEX_RANGE, REGEX_OR, REGEX_AND, REGEX_NOT, REGEX_SEQ }; enum REGEX_OP {
REGEX_EMPTY,
REGEX_MATCH,
REGEX_RANGE,
REGEX_OR,
REGEX_AND,
REGEX_NOT,
REGEX_SEQ
};
// simplified regular expressions // simplified regular expressions
// . Only straightforward matches (no repeated characters) // . Only straightforward matches (no repeated characters)
// . Only matches from start of string // . Only matches from start of string
class RegEx class RegEx {
{
public: public:
RegEx(); RegEx();
RegEx(char ch); RegEx(char ch);
@@ -35,25 +42,36 @@ namespace YAML
bool Matches(char ch) const; bool Matches(char ch) const;
bool Matches(const std::string& str) const; bool Matches(const std::string& str) const;
bool Matches(const Stream& in) const; bool Matches(const Stream& in) const;
template <typename Source> bool Matches(const Source& source) const; template <typename Source>
bool Matches(const Source& source) const;
int Match(const std::string& str) const; int Match(const std::string& str) const;
int Match(const Stream& in) const; int Match(const Stream& in) const;
template <typename Source> int Match(const Source& source) const; template <typename Source>
int Match(const Source& source) const;
private: private:
RegEx(REGEX_OP op); RegEx(REGEX_OP op);
template <typename Source> bool IsValidSource(const Source& source) const; template <typename Source>
template <typename Source> int MatchUnchecked(const Source& source) const; bool IsValidSource(const Source& source) const;
template <typename Source>
int MatchUnchecked(const Source& source) const;
template <typename Source> int MatchOpEmpty(const Source& source) const; template <typename Source>
template <typename Source> int MatchOpMatch(const Source& source) const; int MatchOpEmpty(const Source& source) const;
template <typename Source> int MatchOpRange(const Source& source) const; template <typename Source>
template <typename Source> int MatchOpOr(const Source& source) const; int MatchOpMatch(const Source& source) const;
template <typename Source> int MatchOpAnd(const Source& source) const; template <typename Source>
template <typename Source> int MatchOpNot(const Source& source) const; int MatchOpRange(const Source& source) const;
template <typename Source> int MatchOpSeq(const Source& source) const; template <typename Source>
int MatchOpOr(const Source& source) const;
template <typename Source>
int MatchOpAnd(const Source& source) const;
template <typename Source>
int MatchOpNot(const Source& source) const;
template <typename Source>
int MatchOpSeq(const Source& source) const;
private: private:
REGEX_OP m_op; REGEX_OP m_op;

View File

@@ -1,17 +1,17 @@
#ifndef REGEXIMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef REGEXIMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define REGEXIMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define REGEXIMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "stream.h" #include "stream.h"
#include "stringsource.h" #include "stringsource.h"
#include "streamcharsource.h" #include "streamcharsource.h"
namespace YAML namespace YAML {
{
// query matches // query matches
inline bool RegEx::Matches(char ch) const { inline bool RegEx::Matches(char ch) const {
std::string str; std::string str;
@@ -23,9 +23,7 @@ namespace YAML
return Match(str) >= 0; return Match(str) >= 0;
} }
inline bool RegEx::Matches(const Stream& in) const { inline bool RegEx::Matches(const Stream& in) const { return Match(in) >= 0; }
return Match(in) >= 0;
}
template <typename Source> template <typename Source>
inline bool RegEx::Matches(const Source& source) const { inline bool RegEx::Matches(const Source& source) const {
@@ -39,27 +37,24 @@ namespace YAML
// not returning zero is that we may have an empty regex // not returning zero is that we may have an empty regex
// which is ALWAYS successful at matching zero characters). // which is ALWAYS successful at matching zero characters).
// . REMEMBER that we only match from the start of the buffer! // . REMEMBER that we only match from the start of the buffer!
inline int RegEx::Match(const std::string& str) const inline int RegEx::Match(const std::string& str) const {
{
StringCharSource source(str.c_str(), str.size()); StringCharSource source(str.c_str(), str.size());
return Match(source); return Match(source);
} }
inline int RegEx::Match(const Stream& in) const inline int RegEx::Match(const Stream& in) const {
{
StreamCharSource source(in); StreamCharSource source(in);
return Match(source); return Match(source);
} }
template <typename Source> template <typename Source>
inline bool RegEx::IsValidSource(const Source& source) const inline bool RegEx::IsValidSource(const Source& source) const {
{
return source; return source;
} }
template <> template <>
inline bool RegEx::IsValidSource<StringCharSource>(const StringCharSource&source) const inline bool RegEx::IsValidSource<StringCharSource>(
{ const StringCharSource& source) const {
switch (m_op) { switch (m_op) {
case REGEX_MATCH: case REGEX_MATCH:
case REGEX_RANGE: case REGEX_RANGE:
@@ -70,14 +65,12 @@ namespace YAML
} }
template <typename Source> template <typename Source>
inline int RegEx::Match(const Source& source) const inline int RegEx::Match(const Source& source) const {
{
return IsValidSource(source) ? MatchUnchecked(source) : -1; return IsValidSource(source) ? MatchUnchecked(source) : -1;
} }
template <typename Source> template <typename Source>
inline int RegEx::MatchUnchecked(const Source& source) const inline int RegEx::MatchUnchecked(const Source& source) const {
{
switch (m_op) { switch (m_op) {
case REGEX_EMPTY: case REGEX_EMPTY:
return MatchOpEmpty(source); return MatchOpEmpty(source);
@@ -100,7 +93,8 @@ namespace YAML
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
// Operators // Operators
// Note: the convention MatchOp*<Source> is that we can assume IsSourceValid(source). // Note: the convention MatchOp*<Source> is that we can assume
// IsSourceValid(source).
// So we do all our checks *before* we call these functions // So we do all our checks *before* we call these functions
// EmptyOperator // EmptyOperator
@@ -110,8 +104,11 @@ namespace YAML
} }
template <> template <>
inline int RegEx::MatchOpEmpty<StringCharSource>(const StringCharSource& source) const { inline int RegEx::MatchOpEmpty<StringCharSource>(const StringCharSource& source)
return !source ? 0 : -1; // the empty regex only is successful on the empty string const {
return !source
? 0
: -1; // the empty regex only is successful on the empty string
} }
// MatchOperator // MatchOperator
@@ -173,7 +170,10 @@ namespace YAML
inline int RegEx::MatchOpSeq(const Source& source) const { inline int RegEx::MatchOpSeq(const Source& source) const {
int offset = 0; int offset = 0;
for (std::size_t i = 0; i < m_params.size(); i++) { for (std::size_t i = 0; i < m_params.size(); i++) {
int n = m_params[i].Match(source + offset); // note Match, not MatchUnchecked because we need to check validity after the offset int n = m_params[i].Match(source + offset); // note Match, not
// MatchUnchecked because we
// need to check validity after
// the offset
if (n == -1) if (n == -1)
return -1; return -1;
offset += n; offset += n;

View File

@@ -5,29 +5,26 @@
#include <cassert> #include <cassert>
#include <memory> #include <memory>
namespace YAML namespace YAML {
{
Scanner::Scanner(std::istream& in) Scanner::Scanner(std::istream& in)
: INPUT(in), m_startedStream(false), m_endedStream(false), m_simpleKeyAllowed(false), m_canBeJSONFlow(false) : INPUT(in),
{ m_startedStream(false),
} m_endedStream(false),
m_simpleKeyAllowed(false),
m_canBeJSONFlow(false) {}
Scanner::~Scanner() Scanner::~Scanner() {}
{
}
// empty // empty
// . Returns true if there are no more tokens to be read // . Returns true if there are no more tokens to be read
bool Scanner::empty() bool Scanner::empty() {
{
EnsureTokensInQueue(); EnsureTokensInQueue();
return m_tokens.empty(); return m_tokens.empty();
} }
// pop // pop
// . Simply removes the next token on the queue. // . Simply removes the next token on the queue.
void Scanner::pop() void Scanner::pop() {
{
EnsureTokensInQueue(); EnsureTokensInQueue();
if (!m_tokens.empty()) if (!m_tokens.empty())
m_tokens.pop(); m_tokens.pop();
@@ -35,10 +32,10 @@ namespace YAML
// peek // peek
// . Returns (but does not remove) the next token on the queue. // . Returns (but does not remove) the next token on the queue.
Token& Scanner::peek() Token& Scanner::peek() {
{
EnsureTokensInQueue(); EnsureTokensInQueue();
assert(!m_tokens.empty()); // should we be asserting here? I mean, we really just be checking assert(!m_tokens.empty()); // should we be asserting here? I mean, we really
// just be checking
// if it's empty before peeking. // if it's empty before peeking.
#if 0 #if 0
@@ -53,16 +50,12 @@ namespace YAML
// mark // mark
// . Returns the current mark in the stream // . Returns the current mark in the stream
Mark Scanner::mark() const Mark Scanner::mark() const { return INPUT.mark(); }
{
return INPUT.mark();
}
// EnsureTokensInQueue // EnsureTokensInQueue
// . Scan until there's a valid token at the front of the queue, // . Scan until there's a valid token at the front of the queue,
// or we're sure the queue is empty. // or we're sure the queue is empty.
void Scanner::EnsureTokensInQueue() void Scanner::EnsureTokensInQueue() {
{
while (1) { while (1) {
if (!m_tokens.empty()) { if (!m_tokens.empty()) {
Token& token = m_tokens.front(); Token& token = m_tokens.front();
@@ -92,8 +85,7 @@ namespace YAML
// ScanNextToken // ScanNextToken
// . The main scanning function; here we branch out and // . The main scanning function; here we branch out and
// scan whatever the next token should be. // scan whatever the next token should be.
void Scanner::ScanNextToken() void Scanner::ScanNextToken() {
{
if (m_endedStream) if (m_endedStream)
return; return;
@@ -153,14 +145,16 @@ namespace YAML
return ScanTag(); return ScanTag();
// special scalars // special scalars
if(InBlockContext() && (INPUT.peek() == Keys::LiteralScalar || INPUT.peek() == Keys::FoldedScalar)) if (InBlockContext() && (INPUT.peek() == Keys::LiteralScalar ||
INPUT.peek() == Keys::FoldedScalar))
return ScanBlockScalar(); return ScanBlockScalar();
if (INPUT.peek() == '\'' || INPUT.peek() == '\"') if (INPUT.peek() == '\'' || INPUT.peek() == '\"')
return ScanQuotedScalar(); return ScanQuotedScalar();
// plain scalars // plain scalars
if((InBlockContext() ? Exp::PlainScalar() : Exp::PlainScalarInFlow()).Matches(INPUT)) if ((InBlockContext() ? Exp::PlainScalar() : Exp::PlainScalarInFlow())
.Matches(INPUT))
return ScanPlainScalar(); return ScanPlainScalar();
// don't know what it is! // don't know what it is!
@@ -169,8 +163,7 @@ namespace YAML
// ScanToNextToken // ScanToNextToken
// . Eats input until we reach the next token-like thing. // . Eats input until we reach the next token-like thing.
void Scanner::ScanToNextToken() void Scanner::ScanToNextToken() {
{
while (1) { while (1) {
// first eat whitespace // first eat whitespace
while (INPUT && IsWhitespaceToBeEaten(INPUT.peek())) { while (INPUT && IsWhitespaceToBeEaten(INPUT.peek())) {
@@ -210,12 +203,12 @@ namespace YAML
// . We can eat whitespace if it's a space or tab // . We can eat whitespace if it's a space or tab
// . Note: originally tabs in block context couldn't be eaten // . Note: originally tabs in block context couldn't be eaten
// "where a simple key could be allowed // "where a simple key could be allowed
// (i.e., not at the beginning of a line, or following '-', '?', or ':')" // (i.e., not at the beginning of a line, or following '-', '?', or
// ':')"
// I think this is wrong, since tabs can be non-content whitespace; it's just // I think this is wrong, since tabs can be non-content whitespace; it's just
// that they can't contribute to indentation, so once you've seen a tab in a // that they can't contribute to indentation, so once you've seen a tab in a
// line, you can't start a simple key // line, you can't start a simple key
bool Scanner::IsWhitespaceToBeEaten(char ch) bool Scanner::IsWhitespaceToBeEaten(char ch) {
{
if (ch == ' ') if (ch == ' ')
return true; return true;
@@ -227,8 +220,7 @@ namespace YAML
// GetValueRegex // GetValueRegex
// . Get the appropriate regex to check if it's a value token // . Get the appropriate regex to check if it's a value token
const RegEx& Scanner::GetValueRegex() const const RegEx& Scanner::GetValueRegex() const {
{
if (InBlockContext()) if (InBlockContext())
return Exp::Value(); return Exp::Value();
@@ -237,8 +229,7 @@ namespace YAML
// StartStream // StartStream
// . Set the initial conditions for starting a stream. // . Set the initial conditions for starting a stream.
void Scanner::StartStream() void Scanner::StartStream() {
{
m_startedStream = true; m_startedStream = true;
m_simpleKeyAllowed = true; m_simpleKeyAllowed = true;
std::auto_ptr<IndentMarker> pIndent(new IndentMarker(-1, IndentMarker::NONE)); std::auto_ptr<IndentMarker> pIndent(new IndentMarker(-1, IndentMarker::NONE));
@@ -248,8 +239,7 @@ namespace YAML
// EndStream // EndStream
// . Close out the stream, finish up, etc. // . Close out the stream, finish up, etc.
void Scanner::EndStream() void Scanner::EndStream() {
{
// force newline // force newline
if (INPUT.column() > 0) if (INPUT.column() > 0)
INPUT.ResetColumn(); INPUT.ResetColumn();
@@ -261,18 +251,20 @@ namespace YAML
m_endedStream = true; m_endedStream = true;
} }
Token *Scanner::PushToken(Token::TYPE type) Token* Scanner::PushToken(Token::TYPE type) {
{
m_tokens.push(Token(type, INPUT.mark())); m_tokens.push(Token(type, INPUT.mark()));
return &m_tokens.back(); return &m_tokens.back();
} }
Token::TYPE Scanner::GetStartTokenFor(IndentMarker::INDENT_TYPE type) const Token::TYPE Scanner::GetStartTokenFor(IndentMarker::INDENT_TYPE type) const {
{
switch (type) { switch (type) {
case IndentMarker::SEQ: return Token::BLOCK_SEQ_START; case IndentMarker::SEQ:
case IndentMarker::MAP: return Token::BLOCK_MAP_START; return Token::BLOCK_SEQ_START;
case IndentMarker::NONE: assert(false); break; case IndentMarker::MAP:
return Token::BLOCK_MAP_START;
case IndentMarker::NONE:
assert(false);
break;
} }
assert(false); assert(false);
throw std::runtime_error("yaml-cpp: internal error, invalid indent type"); throw std::runtime_error("yaml-cpp: internal error, invalid indent type");
@@ -282,8 +274,8 @@ namespace YAML
// . Pushes an indentation onto the stack, and enqueues the // . Pushes an indentation onto the stack, and enqueues the
// proper token (sequence start or mapping start). // proper token (sequence start or mapping start).
// . Returns the indent marker it generates (if any). // . Returns the indent marker it generates (if any).
Scanner::IndentMarker *Scanner::PushIndentTo(int column, IndentMarker::INDENT_TYPE type) Scanner::IndentMarker* Scanner::PushIndentTo(int column,
{ IndentMarker::INDENT_TYPE type) {
// are we in flow? // are we in flow?
if (InFlowContext()) if (InFlowContext())
return 0; return 0;
@@ -295,7 +287,9 @@ namespace YAML
// is this actually an indentation? // is this actually an indentation?
if (indent.column < lastIndent.column) if (indent.column < lastIndent.column)
return 0; return 0;
if(indent.column == lastIndent.column && !(indent.type == IndentMarker::SEQ && lastIndent.type == IndentMarker::MAP)) if (indent.column == lastIndent.column &&
!(indent.type == IndentMarker::SEQ &&
lastIndent.type == IndentMarker::MAP))
return 0; return 0;
// push a start token // push a start token
@@ -308,11 +302,11 @@ namespace YAML
} }
// PopIndentToHere // PopIndentToHere
// . Pops indentations off the stack until we reach the current indentation level, // . Pops indentations off the stack until we reach the current indentation
// level,
// and enqueues the proper token each time. // and enqueues the proper token each time.
// . Then pops all invalid indentations off. // . Then pops all invalid indentations off.
void Scanner::PopIndentToHere() void Scanner::PopIndentToHere() {
{
// are we in flow? // are we in flow?
if (InFlowContext()) if (InFlowContext())
return; return;
@@ -322,7 +316,8 @@ namespace YAML
const IndentMarker& indent = *m_indents.top(); const IndentMarker& indent = *m_indents.top();
if (indent.column < INPUT.column()) if (indent.column < INPUT.column())
break; break;
if(indent.column == INPUT.column() && !(indent.type == IndentMarker::SEQ && !Exp::BlockEntry().Matches(INPUT))) if (indent.column == INPUT.column() && !(indent.type == IndentMarker::SEQ &&
!Exp::BlockEntry().Matches(INPUT)))
break; break;
PopIndent(); PopIndent();
@@ -335,8 +330,7 @@ namespace YAML
// PopAllIndents // PopAllIndents
// . Pops all indentations (except for the base empty one) off the stack, // . Pops all indentations (except for the base empty one) off the stack,
// and enqueues the proper token each time. // and enqueues the proper token each time.
void Scanner::PopAllIndents() void Scanner::PopAllIndents() {
{
// are we in flow? // are we in flow?
if (InFlowContext()) if (InFlowContext())
return; return;
@@ -353,8 +347,7 @@ namespace YAML
// PopIndent // PopIndent
// . Pops a single indent, pushing the proper token // . Pops a single indent, pushing the proper token
void Scanner::PopIndent() void Scanner::PopIndent() {
{
const IndentMarker& indent = *m_indents.top(); const IndentMarker& indent = *m_indents.top();
m_indents.pop(); m_indents.pop();
@@ -370,8 +363,7 @@ namespace YAML
} }
// GetTopIndent // GetTopIndent
int Scanner::GetTopIndent() const int Scanner::GetTopIndent() const {
{
if (m_indents.empty()) if (m_indents.empty())
return 0; return 0;
return m_indents.top()->column; return m_indents.top()->column;
@@ -381,8 +373,7 @@ namespace YAML
// . Throws a ParserException with the current token location // . Throws a ParserException with the current token location
// (if available). // (if available).
// . Does not parse any more tokens. // . Does not parse any more tokens.
void Scanner::ThrowParserException(const std::string& msg) const void Scanner::ThrowParserException(const std::string& msg) const {
{
Mark mark = Mark::null_mark(); Mark mark = Mark::null_mark();
if (!m_tokens.empty()) { if (!m_tokens.empty()) {
const Token& token = m_tokens.front(); const Token& token = m_tokens.front();
@@ -391,4 +382,3 @@ namespace YAML
throw ParserException(mark, msg); throw ParserException(mark, msg);
} }
} }

View File

@@ -1,11 +1,12 @@
#ifndef SCANNER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef SCANNER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define SCANNER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define SCANNER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <ios> #include <ios>
#include <string> #include <string>
#include <queue> #include <queue>
@@ -16,13 +17,11 @@
#include "stream.h" #include "stream.h"
#include "token.h" #include "token.h"
namespace YAML namespace YAML {
{
class Node; class Node;
class RegEx; class RegEx;
class Scanner class Scanner {
{
public: public:
Scanner(std::istream &in); Scanner(std::istream &in);
~Scanner(); ~Scanner();
@@ -35,9 +34,18 @@ namespace YAML
private: private:
struct IndentMarker { struct IndentMarker {
enum INDENT_TYPE { MAP, SEQ, NONE }; enum INDENT_TYPE {
enum STATUS { VALID, INVALID, UNKNOWN }; MAP,
IndentMarker(int column_, INDENT_TYPE type_): column(column_), type(type_), status(VALID), pStartToken(0) {} SEQ,
NONE
};
enum STATUS {
VALID,
INVALID,
UNKNOWN
};
IndentMarker(int column_, INDENT_TYPE type_)
: column(column_), type(type_), status(VALID), pStartToken(0) {}
int column; int column;
INDENT_TYPE type; INDENT_TYPE type;
@@ -45,7 +53,10 @@ namespace YAML
Token *pStartToken; Token *pStartToken;
}; };
enum FLOW_MARKER { FLOW_MAP, FLOW_SEQ }; enum FLOW_MARKER {
FLOW_MAP,
FLOW_SEQ
};
private: private:
// scanning // scanning
@@ -130,4 +141,3 @@ namespace YAML
} }
#endif // SCANNER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // SCANNER_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -4,8 +4,7 @@
#include "yaml-cpp/exceptions.h" #include "yaml-cpp/exceptions.h"
#include "token.h" #include "token.h"
namespace YAML namespace YAML {
{
// ScanScalar // ScanScalar
// . This is where the scalar magic happens. // . This is where the scalar magic happens.
// //
@@ -16,8 +15,7 @@ namespace YAML
// //
// . Depending on the parameters given, we store or stop // . Depending on the parameters given, we store or stop
// and different places in the above flow. // and different places in the above flow.
std::string ScanScalar(Stream& INPUT, ScanScalarParams& params) std::string ScanScalar(Stream& INPUT, ScanScalarParams& params) {
{
bool foundNonEmptyLine = false; bool foundNonEmptyLine = false;
bool pastOpeningBreak = (params.fold == FOLD_FLOW); bool pastOpeningBreak = (params.fold == FOLD_FLOW);
bool emptyLine = false, moreIndented = false; bool emptyLine = false, moreIndented = false;
@@ -81,7 +79,8 @@ namespace YAML
} }
// doc indicator? // doc indicator?
if(params.onDocIndicator == BREAK && INPUT.column() == 0 && Exp::DocIndicator().Matches(INPUT)) if (params.onDocIndicator == BREAK && INPUT.column() == 0 &&
Exp::DocIndicator().Matches(INPUT))
break; break;
// are we done via character match? // are we done via character match?
@@ -105,7 +104,8 @@ namespace YAML
// Phase #3: scan initial spaces // Phase #3: scan initial spaces
// first the required indentation // first the required indentation
while(INPUT.peek() == ' ' && (INPUT.column() < params.indent || (params.detectIndent && !foundNonEmptyLine))) while (INPUT.peek() == ' ' && (INPUT.column() < params.indent ||
(params.detectIndent && !foundNonEmptyLine)))
INPUT.eat(1); INPUT.eat(1);
// update indent if we're auto-detecting // update indent if we're auto-detecting
@@ -115,7 +115,8 @@ namespace YAML
// and then the rest of the whitespace // and then the rest of the whitespace
while (Exp::Blank().Matches(INPUT)) { while (Exp::Blank().Matches(INPUT)) {
// we check for tabs that masquerade as indentation // we check for tabs that masquerade as indentation
if(INPUT.peek() == '\t'&& INPUT.column() < params.indent && params.onTabInIndentation == THROW) if (INPUT.peek() == '\t' && INPUT.column() < params.indent &&
params.onTabInIndentation == THROW)
throw ParserException(INPUT.mark(), ErrorMsg::TAB_IN_INDENTATION); throw ParserException(INPUT.mark(), ErrorMsg::TAB_IN_INDENTATION);
if (!params.eatLeadingWhitespace) if (!params.eatLeadingWhitespace)
@@ -130,14 +131,16 @@ namespace YAML
if (params.fold == FOLD_BLOCK && foldedNewlineCount == 0 && nextEmptyLine) if (params.fold == FOLD_BLOCK && foldedNewlineCount == 0 && nextEmptyLine)
foldedNewlineStartedMoreIndented = moreIndented; foldedNewlineStartedMoreIndented = moreIndented;
// for block scalars, we always start with a newline, so we should ignore it (not fold or keep) // for block scalars, we always start with a newline, so we should ignore it
// (not fold or keep)
if (pastOpeningBreak) { if (pastOpeningBreak) {
switch (params.fold) { switch (params.fold) {
case DONT_FOLD: case DONT_FOLD:
scalar += "\n"; scalar += "\n";
break; break;
case FOLD_BLOCK: case FOLD_BLOCK:
if(!emptyLine && !nextEmptyLine && !moreIndented && !nextMoreIndented && INPUT.column() >= params.indent) if (!emptyLine && !nextEmptyLine && !moreIndented &&
!nextMoreIndented && INPUT.column() >= params.indent)
scalar += " "; scalar += " ";
else if (nextEmptyLine) else if (nextEmptyLine)
foldedNewlineCount++; foldedNewlineCount++;
@@ -146,7 +149,8 @@ namespace YAML
if (!nextEmptyLine && foldedNewlineCount > 0) { if (!nextEmptyLine && foldedNewlineCount > 0) {
scalar += std::string(foldedNewlineCount - 1, '\n'); scalar += std::string(foldedNewlineCount - 1, '\n');
if(foldedNewlineStartedMoreIndented || nextMoreIndented | !foundNonEmptyLine) if (foldedNewlineStartedMoreIndented ||
nextMoreIndented | !foundNonEmptyLine)
scalar += "\n"; scalar += "\n";
foldedNewlineCount = 0; foldedNewlineCount = 0;
} }

View File

@@ -1,38 +1,66 @@
#ifndef SCANSCALAR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef SCANSCALAR_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define SCANSCALAR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define SCANSCALAR_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <string> #include <string>
#include "regex.h" #include "regex.h"
#include "stream.h" #include "stream.h"
namespace YAML namespace YAML {
{ enum CHOMP {
enum CHOMP { STRIP = -1, CLIP, KEEP }; STRIP = -1,
enum ACTION { NONE, BREAK, THROW }; CLIP,
enum FOLD { DONT_FOLD, FOLD_BLOCK, FOLD_FLOW }; KEEP
};
enum ACTION {
NONE,
BREAK,
THROW
};
enum FOLD {
DONT_FOLD,
FOLD_BLOCK,
FOLD_FLOW
};
struct ScanScalarParams { struct ScanScalarParams {
ScanScalarParams(): eatEnd(false), indent(0), detectIndent(false), eatLeadingWhitespace(0), escape(0), fold(DONT_FOLD), ScanScalarParams()
trimTrailingSpaces(0), chomp(CLIP), onDocIndicator(NONE), onTabInIndentation(NONE), leadingSpaces(false) {} : eatEnd(false),
indent(0),
detectIndent(false),
eatLeadingWhitespace(0),
escape(0),
fold(DONT_FOLD),
trimTrailingSpaces(0),
chomp(CLIP),
onDocIndicator(NONE),
onTabInIndentation(NONE),
leadingSpaces(false) {}
// input: // input:
RegEx end; // what condition ends this scalar? RegEx end; // what condition ends this scalar?
bool eatEnd; // should we eat that condition when we see it? bool eatEnd; // should we eat that condition when we see it?
int indent; // what level of indentation should be eaten and ignored? int indent; // what level of indentation should be eaten and ignored?
bool detectIndent; // should we try to autodetect the indent? bool detectIndent; // should we try to autodetect the indent?
bool eatLeadingWhitespace; // should we continue eating this delicious indentation after 'indent' spaces? bool eatLeadingWhitespace; // should we continue eating this delicious
char escape; // what character do we escape on (i.e., slash or single quote) (0 for none) // indentation after 'indent' spaces?
char escape; // what character do we escape on (i.e., slash or single quote)
// (0 for none)
FOLD fold; // how do we fold line ends? FOLD fold; // how do we fold line ends?
bool trimTrailingSpaces; // do we remove all trailing spaces (at the very end) bool trimTrailingSpaces; // do we remove all trailing spaces (at the very
CHOMP chomp; // do we strip, clip, or keep trailing newlines (at the very end) // end)
// Note: strip means kill all, clip means keep at most one, keep means keep all CHOMP chomp; // do we strip, clip, or keep trailing newlines (at the very
// end)
// Note: strip means kill all, clip means keep at most one, keep means keep
// all
ACTION onDocIndicator; // what do we do if we see a document indicator? ACTION onDocIndicator; // what do we do if we see a document indicator?
ACTION onTabInIndentation; // what do we do if we see a tab where we should be seeing indentation spaces ACTION onTabInIndentation; // what do we do if we see a tab where we should
// be seeing indentation spaces
// output: // output:
bool leadingSpaces; bool leadingSpaces;
@@ -42,4 +70,3 @@ namespace YAML
} }
#endif // SCANSCALAR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // SCANSCALAR_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -3,10 +3,8 @@
#include "exp.h" #include "exp.h"
#include "yaml-cpp/exceptions.h" #include "yaml-cpp/exceptions.h"
namespace YAML namespace YAML {
{ const std::string ScanVerbatimTag(Stream& INPUT) {
const std::string ScanVerbatimTag(Stream& INPUT)
{
std::string tag; std::string tag;
// eat the start character // eat the start character
@@ -29,8 +27,7 @@ namespace YAML
throw ParserException(INPUT.mark(), ErrorMsg::END_OF_VERBATIM_TAG); throw ParserException(INPUT.mark(), ErrorMsg::END_OF_VERBATIM_TAG);
} }
const std::string ScanTagHandle(Stream& INPUT, bool& canBeHandle) const std::string ScanTagHandle(Stream& INPUT, bool& canBeHandle) {
{
std::string tag; std::string tag;
canBeHandle = true; canBeHandle = true;
Mark firstNonWordChar; Mark firstNonWordChar;
@@ -63,8 +60,7 @@ namespace YAML
return tag; return tag;
} }
const std::string ScanTagSuffix(Stream& INPUT) const std::string ScanTagSuffix(Stream& INPUT) {
{
std::string tag; std::string tag;
while (INPUT) { while (INPUT) {
@@ -81,4 +77,3 @@ namespace YAML
return tag; return tag;
} }
} }

View File

@@ -1,20 +1,19 @@
#ifndef SCANTAG_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef SCANTAG_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define SCANTAG_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define SCANTAG_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <string> #include <string>
#include "stream.h" #include "stream.h"
namespace YAML namespace YAML {
{
const std::string ScanVerbatimTag(Stream& INPUT); const std::string ScanVerbatimTag(Stream& INPUT);
const std::string ScanTagHandle(Stream& INPUT, bool& canBeHandle); const std::string ScanTagHandle(Stream& INPUT, bool& canBeHandle);
const std::string ScanTagSuffix(Stream& INPUT); const std::string ScanTagSuffix(Stream& INPUT);
} }
#endif // SCANTAG_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // SCANTAG_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -7,15 +7,13 @@
#include "tag.h" #include "tag.h"
#include <sstream> #include <sstream>
namespace YAML namespace YAML {
{
/////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////
// Specialization for scanning specific tokens // Specialization for scanning specific tokens
// Directive // Directive
// . Note: no semantic checking is done here (that's for the parser to do) // . Note: no semantic checking is done here (that's for the parser to do)
void Scanner::ScanDirective() void Scanner::ScanDirective() {
{
std::string name; std::string name;
std::vector<std::string> params; std::vector<std::string> params;
@@ -56,8 +54,7 @@ namespace YAML
} }
// DocStart // DocStart
void Scanner::ScanDocStart() void Scanner::ScanDocStart() {
{
PopAllIndents(); PopAllIndents();
PopAllSimpleKeys(); PopAllSimpleKeys();
m_simpleKeyAllowed = false; m_simpleKeyAllowed = false;
@@ -70,8 +67,7 @@ namespace YAML
} }
// DocEnd // DocEnd
void Scanner::ScanDocEnd() void Scanner::ScanDocEnd() {
{
PopAllIndents(); PopAllIndents();
PopAllSimpleKeys(); PopAllSimpleKeys();
m_simpleKeyAllowed = false; m_simpleKeyAllowed = false;
@@ -84,8 +80,7 @@ namespace YAML
} }
// FlowStart // FlowStart
void Scanner::ScanFlowStart() void Scanner::ScanFlowStart() {
{
// flows can be simple keys // flows can be simple keys
InsertPotentialSimpleKey(); InsertPotentialSimpleKey();
m_simpleKeyAllowed = true; m_simpleKeyAllowed = true;
@@ -96,13 +91,13 @@ namespace YAML
char ch = INPUT.get(); char ch = INPUT.get();
FLOW_MARKER flowType = (ch == Keys::FlowSeqStart ? FLOW_SEQ : FLOW_MAP); FLOW_MARKER flowType = (ch == Keys::FlowSeqStart ? FLOW_SEQ : FLOW_MAP);
m_flows.push(flowType); m_flows.push(flowType);
Token::TYPE type = (flowType == FLOW_SEQ ? Token::FLOW_SEQ_START : Token::FLOW_MAP_START); Token::TYPE type =
(flowType == FLOW_SEQ ? Token::FLOW_SEQ_START : Token::FLOW_MAP_START);
m_tokens.push(Token(type, mark)); m_tokens.push(Token(type, mark));
} }
// FlowEnd // FlowEnd
void Scanner::ScanFlowEnd() void Scanner::ScanFlowEnd() {
{
if (InBlockContext()) if (InBlockContext())
throw ParserException(INPUT.mark(), ErrorMsg::FLOW_END); throw ParserException(INPUT.mark(), ErrorMsg::FLOW_END);
@@ -132,8 +127,7 @@ namespace YAML
} }
// FlowEntry // FlowEntry
void Scanner::ScanFlowEntry() void Scanner::ScanFlowEntry() {
{
// we might have a solo entry in the flow context // we might have a solo entry in the flow context
if (InFlowContext()) { if (InFlowContext()) {
if (m_flows.top() == FLOW_MAP && VerifySimpleKey()) if (m_flows.top() == FLOW_MAP && VerifySimpleKey())
@@ -152,8 +146,7 @@ namespace YAML
} }
// BlockEntry // BlockEntry
void Scanner::ScanBlockEntry() void Scanner::ScanBlockEntry() {
{
// we better be in the block context! // we better be in the block context!
if (InFlowContext()) if (InFlowContext())
throw ParserException(INPUT.mark(), ErrorMsg::BLOCK_ENTRY); throw ParserException(INPUT.mark(), ErrorMsg::BLOCK_ENTRY);
@@ -173,8 +166,7 @@ namespace YAML
} }
// Key // Key
void Scanner::ScanKey() void Scanner::ScanKey() {
{
// handle keys diffently in the block context (and manage indents) // handle keys diffently in the block context (and manage indents)
if (InBlockContext()) { if (InBlockContext()) {
if (!m_simpleKeyAllowed) if (!m_simpleKeyAllowed)
@@ -193,14 +185,14 @@ namespace YAML
} }
// Value // Value
void Scanner::ScanValue() void Scanner::ScanValue() {
{
// and check that simple key // and check that simple key
bool isSimpleKey = VerifySimpleKey(); bool isSimpleKey = VerifySimpleKey();
m_canBeJSONFlow = false; m_canBeJSONFlow = false;
if (isSimpleKey) { if (isSimpleKey) {
// can't follow a simple key with another simple key (dunno why, though - it seems fine) // can't follow a simple key with another simple key (dunno why, though - it
// seems fine)
m_simpleKeyAllowed = false; m_simpleKeyAllowed = false;
} else { } else {
// handle values diffently in the block context (and manage indents) // handle values diffently in the block context (and manage indents)
@@ -222,8 +214,7 @@ namespace YAML
} }
// AnchorOrAlias // AnchorOrAlias
void Scanner::ScanAnchorOrAlias() void Scanner::ScanAnchorOrAlias() {
{
bool alias; bool alias;
std::string name; std::string name;
@@ -243,11 +234,13 @@ namespace YAML
// we need to have read SOMETHING! // we need to have read SOMETHING!
if (name.empty()) if (name.empty())
throw ParserException(INPUT.mark(), alias ? ErrorMsg::ALIAS_NOT_FOUND : ErrorMsg::ANCHOR_NOT_FOUND); throw ParserException(INPUT.mark(), alias ? ErrorMsg::ALIAS_NOT_FOUND
: ErrorMsg::ANCHOR_NOT_FOUND);
// and needs to end correctly // and needs to end correctly
if (INPUT && !Exp::AnchorEnd().Matches(INPUT)) if (INPUT && !Exp::AnchorEnd().Matches(INPUT))
throw ParserException(INPUT.mark(), alias ? ErrorMsg::CHAR_IN_ALIAS : ErrorMsg::CHAR_IN_ANCHOR); throw ParserException(INPUT.mark(), alias ? ErrorMsg::CHAR_IN_ALIAS
: ErrorMsg::CHAR_IN_ANCHOR);
// and we're done // and we're done
Token token(alias ? Token::ALIAS : Token::ANCHOR, mark); Token token(alias ? Token::ALIAS : Token::ANCHOR, mark);
@@ -256,8 +249,7 @@ namespace YAML
} }
// Tag // Tag
void Scanner::ScanTag() void Scanner::ScanTag() {
{
// insert a potential simple key // insert a potential simple key
InsertPotentialSimpleKey(); InsertPotentialSimpleKey();
m_simpleKeyAllowed = false; m_simpleKeyAllowed = false;
@@ -296,13 +288,13 @@ namespace YAML
} }
// PlainScalar // PlainScalar
void Scanner::ScanPlainScalar() void Scanner::ScanPlainScalar() {
{
std::string scalar; std::string scalar;
// set up the scanning parameters // set up the scanning parameters
ScanScalarParams params; ScanScalarParams params;
params.end = (InFlowContext() ? Exp::EndScalarInFlow() : Exp::EndScalar()) || (Exp::BlankOrBreak() + Exp::Comment()); params.end = (InFlowContext() ? Exp::EndScalarInFlow() : Exp::EndScalar()) ||
(Exp::BlankOrBreak() + Exp::Comment());
params.eatEnd = false; params.eatEnd = false;
params.indent = (InFlowContext() ? 0 : GetTopIndent() + 1); params.indent = (InFlowContext() ? 0 : GetTopIndent() + 1);
params.fold = FOLD_FLOW; params.fold = FOLD_FLOW;
@@ -332,11 +324,11 @@ namespace YAML
} }
// QuotedScalar // QuotedScalar
void Scanner::ScanQuotedScalar() void Scanner::ScanQuotedScalar() {
{
std::string scalar; std::string scalar;
// peek at single or double quote (don't eat because we need to preserve (for the time being) the input position) // peek at single or double quote (don't eat because we need to preserve (for
// the time being) the input position)
char quote = INPUT.peek(); char quote = INPUT.peek();
bool single = (quote == '\''); bool single = (quote == '\'');
@@ -372,10 +364,10 @@ namespace YAML
// BlockScalarToken // BlockScalarToken
// . These need a little extra processing beforehand. // . These need a little extra processing beforehand.
// . We need to scan the line where the indicator is (this doesn't count as part of the scalar), // . We need to scan the line where the indicator is (this doesn't count as part
// of the scalar),
// and then we need to figure out what level of indentation we'll be using. // and then we need to figure out what level of indentation we'll be using.
void Scanner::ScanBlockScalar() void Scanner::ScanBlockScalar() {
{
std::string scalar; std::string scalar;
ScanScalarParams params; ScanScalarParams params;
@@ -428,7 +420,8 @@ namespace YAML
scalar = ScanScalar(INPUT, params); scalar = ScanScalar(INPUT, params);
// simple keys always ok after block scalars (since we're gonna start a new line anyways) // simple keys always ok after block scalars (since we're gonna start a new
// line anyways)
m_simpleKeyAllowed = true; m_simpleKeyAllowed = true;
m_canBeJSONFlow = false; m_canBeJSONFlow = false;

View File

@@ -1,54 +1,47 @@
#ifndef SETTING_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef SETTING_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define SETTING_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define SETTING_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <memory> #include <memory>
#include <vector> #include <vector>
#include "yaml-cpp/noncopyable.h" #include "yaml-cpp/noncopyable.h"
namespace YAML namespace YAML {
{
class SettingChangeBase; class SettingChangeBase;
template <typename T> template <typename T>
class Setting class Setting {
{
public: public:
Setting() : m_value() {} Setting() : m_value() {}
const T get() const { return m_value; } const T get() const { return m_value; }
std::auto_ptr<SettingChangeBase> set(const T& value); std::auto_ptr<SettingChangeBase> set(const T& value);
void restore(const Setting<T>& oldSetting) { void restore(const Setting<T>& oldSetting) { m_value = oldSetting.get(); }
m_value = oldSetting.get();
}
private: private:
T m_value; T m_value;
}; };
class SettingChangeBase class SettingChangeBase {
{
public: public:
virtual ~SettingChangeBase() {} virtual ~SettingChangeBase() {}
virtual void pop() = 0; virtual void pop() = 0;
}; };
template <typename T> template <typename T>
class SettingChange: public SettingChangeBase class SettingChange : public SettingChangeBase {
{
public: public:
SettingChange(Setting<T>* pSetting) : m_pCurSetting(pSetting) { SettingChange(Setting<T>* pSetting) : m_pCurSetting(pSetting) {
// copy old setting to save its state // copy old setting to save its state
m_oldSetting = *pSetting; m_oldSetting = *pSetting;
} }
virtual void pop() { virtual void pop() { m_pCurSetting->restore(m_oldSetting); }
m_pCurSetting->restore(m_oldSetting);
}
private: private:
Setting<T>* m_pCurSetting; Setting<T>* m_pCurSetting;
@@ -62,8 +55,7 @@ namespace YAML
return pChange; return pChange;
} }
class SettingChanges: private noncopyable class SettingChanges : private noncopyable {
{
public: public:
SettingChanges() {} SettingChanges() {}
~SettingChanges() { clear(); } ~SettingChanges() { clear(); }
@@ -71,13 +63,15 @@ namespace YAML
void clear() { void clear() {
restore(); restore();
for(setting_changes::const_iterator it=m_settingChanges.begin();it!=m_settingChanges.end();++it) for (setting_changes::const_iterator it = m_settingChanges.begin();
it != m_settingChanges.end(); ++it)
delete *it; delete *it;
m_settingChanges.clear(); m_settingChanges.clear();
} }
void restore() { void restore() {
for(setting_changes::const_iterator it=m_settingChanges.begin();it!=m_settingChanges.end();++it) for (setting_changes::const_iterator it = m_settingChanges.begin();
it != m_settingChanges.end(); ++it)
(*it)->pop(); (*it)->pop();
} }

View File

@@ -3,15 +3,11 @@
#include "yaml-cpp/exceptions.h" #include "yaml-cpp/exceptions.h"
#include "exp.h" #include "exp.h"
namespace YAML namespace YAML {
{
Scanner::SimpleKey::SimpleKey(const Mark& mark_, int flowLevel_) Scanner::SimpleKey::SimpleKey(const Mark& mark_, int flowLevel_)
: mark(mark_), flowLevel(flowLevel_), pIndent(0), pMapStart(0), pKey(0) : mark(mark_), flowLevel(flowLevel_), pIndent(0), pMapStart(0), pKey(0) {}
{
}
void Scanner::SimpleKey::Validate() void Scanner::SimpleKey::Validate() {
{
// Note: pIndent will *not* be garbage here; // Note: pIndent will *not* be garbage here;
// we "garbage collect" them so we can // we "garbage collect" them so we can
// always refer to them // always refer to them
@@ -23,8 +19,7 @@ namespace YAML
pKey->status = Token::VALID; pKey->status = Token::VALID;
} }
void Scanner::SimpleKey::Invalidate() void Scanner::SimpleKey::Invalidate() {
{
if (pIndent) if (pIndent)
pIndent->status = IndentMarker::INVALID; pIndent->status = IndentMarker::INVALID;
if (pMapStart) if (pMapStart)
@@ -34,8 +29,7 @@ namespace YAML
} }
// CanInsertPotentialSimpleKey // CanInsertPotentialSimpleKey
bool Scanner::CanInsertPotentialSimpleKey() const bool Scanner::CanInsertPotentialSimpleKey() const {
{
if (!m_simpleKeyAllowed) if (!m_simpleKeyAllowed)
return false; return false;
@@ -44,9 +38,9 @@ namespace YAML
// ExistsActiveSimpleKey // ExistsActiveSimpleKey
// . Returns true if there's a potential simple key at our flow level // . Returns true if there's a potential simple key at our flow level
// (there's allowed at most one per flow level, i.e., at the start of the flow start token) // (there's allowed at most one per flow level, i.e., at the start of the flow
bool Scanner::ExistsActiveSimpleKey() const // start token)
{ bool Scanner::ExistsActiveSimpleKey() const {
if (m_simpleKeys.empty()) if (m_simpleKeys.empty())
return false; return false;
@@ -57,8 +51,7 @@ namespace YAML
// InsertPotentialSimpleKey // InsertPotentialSimpleKey
// . If we can, add a potential simple key to the queue, // . If we can, add a potential simple key to the queue,
// and save it on a stack. // and save it on a stack.
void Scanner::InsertPotentialSimpleKey() void Scanner::InsertPotentialSimpleKey() {
{
if (!CanInsertPotentialSimpleKey()) if (!CanInsertPotentialSimpleKey())
return; return;
@@ -84,8 +77,7 @@ namespace YAML
// InvalidateSimpleKey // InvalidateSimpleKey
// . Automatically invalidate the simple key in our flow level // . Automatically invalidate the simple key in our flow level
void Scanner::InvalidateSimpleKey() void Scanner::InvalidateSimpleKey() {
{
if (m_simpleKeys.empty()) if (m_simpleKeys.empty())
return; return;
@@ -101,8 +93,7 @@ namespace YAML
// VerifySimpleKey // VerifySimpleKey
// . Determines whether the latest simple key to be added is valid, // . Determines whether the latest simple key to be added is valid,
// and if so, makes it valid. // and if so, makes it valid.
bool Scanner::VerifySimpleKey() bool Scanner::VerifySimpleKey() {
{
if (m_simpleKeys.empty()) if (m_simpleKeys.empty())
return false; return false;
@@ -130,10 +121,8 @@ namespace YAML
return isValid; return isValid;
} }
void Scanner::PopAllSimpleKeys() void Scanner::PopAllSimpleKeys() {
{
while (!m_simpleKeys.empty()) while (!m_simpleKeys.empty())
m_simpleKeys.pop(); m_simpleKeys.pop();
} }
} }

View File

@@ -10,21 +10,19 @@
#include <cstdio> #include <cstdio>
#include <algorithm> #include <algorithm>
namespace YAML namespace YAML {
{ SingleDocParser::SingleDocParser(Scanner& scanner, const Directives& directives)
SingleDocParser::SingleDocParser(Scanner& scanner, const Directives& directives): m_scanner(scanner), m_directives(directives), m_pCollectionStack(new CollectionStack), m_curAnchor(0) : m_scanner(scanner),
{ m_directives(directives),
} m_pCollectionStack(new CollectionStack),
m_curAnchor(0) {}
SingleDocParser::~SingleDocParser() SingleDocParser::~SingleDocParser() {}
{
}
// HandleDocument // HandleDocument
// . Handles the next document // . Handles the next document
// . Throws a ParserException on error. // . Throws a ParserException on error.
void SingleDocParser::HandleDocument(EventHandler& eventHandler) void SingleDocParser::HandleDocument(EventHandler& eventHandler) {
{
assert(!m_scanner.empty()); // guaranteed that there are tokens assert(!m_scanner.empty()); // guaranteed that there are tokens
assert(!m_curAnchor); assert(!m_curAnchor);
@@ -44,8 +42,7 @@ namespace YAML
m_scanner.pop(); m_scanner.pop();
} }
void SingleDocParser::HandleNode(EventHandler& eventHandler) void SingleDocParser::HandleNode(EventHandler& eventHandler) {
{
// an empty node *is* a possibility // an empty node *is* a possibility
if (m_scanner.empty()) { if (m_scanner.empty()) {
eventHandler.OnNull(m_scanner.mark(), NullAnchor); eventHandler.OnNull(m_scanner.mark(), NullAnchor);
@@ -107,7 +104,8 @@ namespace YAML
return; return;
case Token::KEY: case Token::KEY:
// compact maps can only go in a flow sequence // compact maps can only go in a flow sequence
if(m_pCollectionStack->GetCurCollectionType() == CollectionType::FlowSeq) { if (m_pCollectionStack->GetCurCollectionType() ==
CollectionType::FlowSeq) {
eventHandler.OnMapStart(mark, tag, anchor); eventHandler.OnMapStart(mark, tag, anchor);
HandleMap(eventHandler); HandleMap(eventHandler);
eventHandler.OnMapEnd(); eventHandler.OnMapEnd();
@@ -124,18 +122,21 @@ namespace YAML
eventHandler.OnScalar(mark, tag, anchor, ""); eventHandler.OnScalar(mark, tag, anchor, "");
} }
void SingleDocParser::HandleSequence(EventHandler& eventHandler) void SingleDocParser::HandleSequence(EventHandler& eventHandler) {
{
// split based on start token // split based on start token
switch (m_scanner.peek().type) { switch (m_scanner.peek().type) {
case Token::BLOCK_SEQ_START: HandleBlockSequence(eventHandler); break; case Token::BLOCK_SEQ_START:
case Token::FLOW_SEQ_START: HandleFlowSequence(eventHandler); break; HandleBlockSequence(eventHandler);
default: break; break;
case Token::FLOW_SEQ_START:
HandleFlowSequence(eventHandler);
break;
default:
break;
} }
} }
void SingleDocParser::HandleBlockSequence(EventHandler& eventHandler) void SingleDocParser::HandleBlockSequence(EventHandler& eventHandler) {
{
// eat start token // eat start token
m_scanner.pop(); m_scanner.pop();
m_pCollectionStack->PushCollectionType(CollectionType::BlockSeq); m_pCollectionStack->PushCollectionType(CollectionType::BlockSeq);
@@ -155,7 +156,8 @@ namespace YAML
// check for null // check for null
if (!m_scanner.empty()) { if (!m_scanner.empty()) {
const Token& token = m_scanner.peek(); const Token& token = m_scanner.peek();
if(token.type == Token::BLOCK_ENTRY || token.type == Token::BLOCK_SEQ_END) { if (token.type == Token::BLOCK_ENTRY ||
token.type == Token::BLOCK_SEQ_END) {
eventHandler.OnNull(token.mark, NullAnchor); eventHandler.OnNull(token.mark, NullAnchor);
continue; continue;
} }
@@ -167,8 +169,7 @@ namespace YAML
m_pCollectionStack->PopCollectionType(CollectionType::BlockSeq); m_pCollectionStack->PopCollectionType(CollectionType::BlockSeq);
} }
void SingleDocParser::HandleFlowSequence(EventHandler& eventHandler) void SingleDocParser::HandleFlowSequence(EventHandler& eventHandler) {
{
// eat start token // eat start token
m_scanner.pop(); m_scanner.pop();
m_pCollectionStack->PushCollectionType(CollectionType::FlowSeq); m_pCollectionStack->PushCollectionType(CollectionType::FlowSeq);
@@ -189,7 +190,8 @@ namespace YAML
if (m_scanner.empty()) if (m_scanner.empty())
throw ParserException(m_scanner.mark(), ErrorMsg::END_OF_SEQ_FLOW); throw ParserException(m_scanner.mark(), ErrorMsg::END_OF_SEQ_FLOW);
// now eat the separator (or could be a sequence end, which we ignore - but if it's neither, then it's a bad node) // now eat the separator (or could be a sequence end, which we ignore - but
// if it's neither, then it's a bad node)
Token& token = m_scanner.peek(); Token& token = m_scanner.peek();
if (token.type == Token::FLOW_ENTRY) if (token.type == Token::FLOW_ENTRY)
m_scanner.pop(); m_scanner.pop();
@@ -200,20 +202,27 @@ namespace YAML
m_pCollectionStack->PopCollectionType(CollectionType::FlowSeq); m_pCollectionStack->PopCollectionType(CollectionType::FlowSeq);
} }
void SingleDocParser::HandleMap(EventHandler& eventHandler) void SingleDocParser::HandleMap(EventHandler& eventHandler) {
{
// split based on start token // split based on start token
switch (m_scanner.peek().type) { switch (m_scanner.peek().type) {
case Token::BLOCK_MAP_START: HandleBlockMap(eventHandler); break; case Token::BLOCK_MAP_START:
case Token::FLOW_MAP_START: HandleFlowMap(eventHandler); break; HandleBlockMap(eventHandler);
case Token::KEY: HandleCompactMap(eventHandler); break; break;
case Token::VALUE: HandleCompactMapWithNoKey(eventHandler); break; case Token::FLOW_MAP_START:
default: break; HandleFlowMap(eventHandler);
break;
case Token::KEY:
HandleCompactMap(eventHandler);
break;
case Token::VALUE:
HandleCompactMapWithNoKey(eventHandler);
break;
default:
break;
} }
} }
void SingleDocParser::HandleBlockMap(EventHandler& eventHandler) void SingleDocParser::HandleBlockMap(EventHandler& eventHandler) {
{
// eat start token // eat start token
m_scanner.pop(); m_scanner.pop();
m_pCollectionStack->PushCollectionType(CollectionType::BlockMap); m_pCollectionStack->PushCollectionType(CollectionType::BlockMap);
@@ -223,7 +232,8 @@ namespace YAML
throw ParserException(m_scanner.mark(), ErrorMsg::END_OF_MAP); throw ParserException(m_scanner.mark(), ErrorMsg::END_OF_MAP);
Token token = m_scanner.peek(); Token token = m_scanner.peek();
if(token.type != Token::KEY && token.type != Token::VALUE && token.type != Token::BLOCK_MAP_END) if (token.type != Token::KEY && token.type != Token::VALUE &&
token.type != Token::BLOCK_MAP_END)
throw ParserException(token.mark, ErrorMsg::END_OF_MAP); throw ParserException(token.mark, ErrorMsg::END_OF_MAP);
if (token.type == Token::BLOCK_MAP_END) { if (token.type == Token::BLOCK_MAP_END) {
@@ -251,8 +261,7 @@ namespace YAML
m_pCollectionStack->PopCollectionType(CollectionType::BlockMap); m_pCollectionStack->PopCollectionType(CollectionType::BlockMap);
} }
void SingleDocParser::HandleFlowMap(EventHandler& eventHandler) void SingleDocParser::HandleFlowMap(EventHandler& eventHandler) {
{
// eat start token // eat start token
m_scanner.pop(); m_scanner.pop();
m_pCollectionStack->PushCollectionType(CollectionType::FlowMap); m_pCollectionStack->PushCollectionType(CollectionType::FlowMap);
@@ -288,7 +297,8 @@ namespace YAML
if (m_scanner.empty()) if (m_scanner.empty())
throw ParserException(m_scanner.mark(), ErrorMsg::END_OF_MAP_FLOW); throw ParserException(m_scanner.mark(), ErrorMsg::END_OF_MAP_FLOW);
// now eat the separator (or could be a map end, which we ignore - but if it's neither, then it's a bad node) // now eat the separator (or could be a map end, which we ignore - but if
// it's neither, then it's a bad node)
Token& nextToken = m_scanner.peek(); Token& nextToken = m_scanner.peek();
if (nextToken.type == Token::FLOW_ENTRY) if (nextToken.type == Token::FLOW_ENTRY)
m_scanner.pop(); m_scanner.pop();
@@ -300,8 +310,7 @@ namespace YAML
} }
// . Single "key: value" pair in a flow sequence // . Single "key: value" pair in a flow sequence
void SingleDocParser::HandleCompactMap(EventHandler& eventHandler) void SingleDocParser::HandleCompactMap(EventHandler& eventHandler) {
{
m_pCollectionStack->PushCollectionType(CollectionType::CompactMap); m_pCollectionStack->PushCollectionType(CollectionType::CompactMap);
// grab key // grab key
@@ -321,8 +330,7 @@ namespace YAML
} }
// . Single ": value" pair in a flow sequence // . Single ": value" pair in a flow sequence
void SingleDocParser::HandleCompactMapWithNoKey(EventHandler& eventHandler) void SingleDocParser::HandleCompactMapWithNoKey(EventHandler& eventHandler) {
{
m_pCollectionStack->PushCollectionType(CollectionType::CompactMap); m_pCollectionStack->PushCollectionType(CollectionType::CompactMap);
// null key // null key
@@ -337,8 +345,7 @@ namespace YAML
// ParseProperties // ParseProperties
// . Grabs any tag or anchor tokens and deals with them. // . Grabs any tag or anchor tokens and deals with them.
void SingleDocParser::ParseProperties(std::string& tag, anchor_t& anchor) void SingleDocParser::ParseProperties(std::string& tag, anchor_t& anchor) {
{
tag.clear(); tag.clear();
anchor = NullAnchor; anchor = NullAnchor;
@@ -347,15 +354,19 @@ namespace YAML
return; return;
switch (m_scanner.peek().type) { switch (m_scanner.peek().type) {
case Token::TAG: ParseTag(tag); break; case Token::TAG:
case Token::ANCHOR: ParseAnchor(anchor); break; ParseTag(tag);
default: return; break;
case Token::ANCHOR:
ParseAnchor(anchor);
break;
default:
return;
} }
} }
} }
void SingleDocParser::ParseTag(std::string& tag) void SingleDocParser::ParseTag(std::string& tag) {
{
Token& token = m_scanner.peek(); Token& token = m_scanner.peek();
if (!tag.empty()) if (!tag.empty())
throw ParserException(token.mark, ErrorMsg::MULTIPLE_TAGS); throw ParserException(token.mark, ErrorMsg::MULTIPLE_TAGS);
@@ -365,8 +376,7 @@ namespace YAML
m_scanner.pop(); m_scanner.pop();
} }
void SingleDocParser::ParseAnchor(anchor_t& anchor) void SingleDocParser::ParseAnchor(anchor_t& anchor) {
{
Token& token = m_scanner.peek(); Token& token = m_scanner.peek();
if (anchor) if (anchor)
throw ParserException(token.mark, ErrorMsg::MULTIPLE_ANCHORS); throw ParserException(token.mark, ErrorMsg::MULTIPLE_ANCHORS);
@@ -375,16 +385,15 @@ namespace YAML
m_scanner.pop(); m_scanner.pop();
} }
anchor_t SingleDocParser::RegisterAnchor(const std::string& name) anchor_t SingleDocParser::RegisterAnchor(const std::string& name) {
{
if (name.empty()) if (name.empty())
return NullAnchor; return NullAnchor;
return m_anchors[name] = ++m_curAnchor; return m_anchors[name] = ++m_curAnchor;
} }
anchor_t SingleDocParser::LookupAnchor(const Mark& mark, const std::string& name) const anchor_t SingleDocParser::LookupAnchor(const Mark& mark,
{ const std::string& name) const {
Anchors::const_iterator it = m_anchors.find(name); Anchors::const_iterator it = m_anchors.find(name);
if (it == m_anchors.end()) if (it == m_anchors.end())
throw ParserException(mark, ErrorMsg::UNKNOWN_ANCHOR); throw ParserException(mark, ErrorMsg::UNKNOWN_ANCHOR);

View File

@@ -1,19 +1,19 @@
#ifndef SINGLEDOCPARSER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef SINGLEDOCPARSER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define SINGLEDOCPARSER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define SINGLEDOCPARSER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/anchor.h" #include "yaml-cpp/anchor.h"
#include "yaml-cpp/noncopyable.h" #include "yaml-cpp/noncopyable.h"
#include <string> #include <string>
#include <map> #include <map>
#include <memory> #include <memory>
namespace YAML namespace YAML {
{
struct Directives; struct Directives;
struct Mark; struct Mark;
struct Token; struct Token;
@@ -22,8 +22,7 @@ namespace YAML
class Node; class Node;
class Scanner; class Scanner;
class SingleDocParser: private noncopyable class SingleDocParser : private noncopyable {
{
public: public:
SingleDocParser(Scanner& scanner, const Directives& directives); SingleDocParser(Scanner& scanner, const Directives& directives);
~SingleDocParser(); ~SingleDocParser();

View File

@@ -11,8 +11,7 @@
#define CP_REPLACEMENT_CHARACTER (0xFFFD) #define CP_REPLACEMENT_CHARACTER (0xFFFD)
namespace YAML namespace YAML {
{
enum UtfIntroState { enum UtfIntroState {
uis_start, uis_start,
uis_utfbe_b1, uis_utfbe_b1,
@@ -47,8 +46,7 @@ namespace YAML
uictMax uictMax
}; };
static bool s_introFinalState[] = { static bool s_introFinalState[] = {false, // uis_start
false, //uis_start
false, // uis_utfbe_b1 false, // uis_utfbe_b1
false, // uis_utf32be_b2 false, // uis_utf32be_b2
false, // uis_utf32be_bom3 false, // uis_utf32be_bom3
@@ -70,26 +68,44 @@ namespace YAML
}; };
static UtfIntroState s_introTransitions[][uictMax] = { static UtfIntroState s_introTransitions[][uictMax] = {
// uict00, uictBB, uictBF, uictEF, uictFE, uictFF, uictAscii, uictOther // uict00, uictBB, uictBF, uictEF,
{uis_utfbe_b1, uis_utf8, uis_utf8, uis_utf8_bom1, uis_utf16be_bom1, uis_utfle_bom1, uis_utf8_imp, uis_utf8}, // uictFE, uictFF, uictAscii, uictOther
{uis_utf32be_b2, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf16be, uis_utf8}, {uis_utfbe_b1, uis_utf8, uis_utf8, uis_utf8_bom1,
{uis_utf32be, uis_utf8, uis_utf8, uis_utf8, uis_utf32be_bom3, uis_utf8, uis_utf8, uis_utf8}, uis_utf16be_bom1, uis_utfle_bom1, uis_utf8_imp, uis_utf8},
{uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf32be, uis_utf8, uis_utf8}, {uis_utf32be_b2, uis_utf8, uis_utf8, uis_utf8,
{uis_utf32be, uis_utf32be, uis_utf32be, uis_utf32be, uis_utf32be, uis_utf32be, uis_utf32be, uis_utf32be}, uis_utf8, uis_utf8, uis_utf16be, uis_utf8},
{uis_utf16be, uis_utf16be, uis_utf16be, uis_utf16be, uis_utf16be, uis_utf16be, uis_utf16be, uis_utf16be}, {uis_utf32be, uis_utf8, uis_utf8, uis_utf8,
{uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf16be, uis_utf8, uis_utf8}, uis_utf32be_bom3, uis_utf8, uis_utf8, uis_utf8},
{uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf16le_bom2, uis_utf8, uis_utf8, uis_utf8}, {uis_utf8, uis_utf8, uis_utf8, uis_utf8,
{uis_utf32le_bom3, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le}, uis_utf8, uis_utf32be, uis_utf8, uis_utf8},
{uis_utf32le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le}, {uis_utf32be, uis_utf32be, uis_utf32be, uis_utf32be,
{uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le}, uis_utf32be, uis_utf32be, uis_utf32be, uis_utf32be},
{uis_utf32le, uis_utf32le, uis_utf32le, uis_utf32le, uis_utf32le, uis_utf32le, uis_utf32le, uis_utf32le}, {uis_utf16be, uis_utf16be, uis_utf16be, uis_utf16be,
{uis_utf16le_imp, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8}, uis_utf16be, uis_utf16be, uis_utf16be, uis_utf16be},
{uis_utf32le_imp3, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le}, {uis_utf8, uis_utf8, uis_utf8, uis_utf8,
{uis_utf32le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le}, uis_utf8, uis_utf16be, uis_utf8, uis_utf8},
{uis_utf8, uis_utf8_bom2, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8}, {uis_utf8, uis_utf8, uis_utf8, uis_utf8,
{uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8}, uis_utf16le_bom2, uis_utf8, uis_utf8, uis_utf8},
{uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8, uis_utf8}, {uis_utf32le_bom3, uis_utf16le, uis_utf16le, uis_utf16le,
}; uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le},
{uis_utf32le, uis_utf16le, uis_utf16le, uis_utf16le,
uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le},
{uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le,
uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le},
{uis_utf32le, uis_utf32le, uis_utf32le, uis_utf32le,
uis_utf32le, uis_utf32le, uis_utf32le, uis_utf32le},
{uis_utf16le_imp, uis_utf8, uis_utf8, uis_utf8,
uis_utf8, uis_utf8, uis_utf8, uis_utf8},
{uis_utf32le_imp3, uis_utf16le, uis_utf16le, uis_utf16le,
uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le},
{uis_utf32le, uis_utf16le, uis_utf16le, uis_utf16le,
uis_utf16le, uis_utf16le, uis_utf16le, uis_utf16le},
{uis_utf8, uis_utf8_bom2, uis_utf8, uis_utf8,
uis_utf8, uis_utf8, uis_utf8, uis_utf8},
{uis_utf8, uis_utf8, uis_utf8, uis_utf8,
uis_utf8, uis_utf8, uis_utf8, uis_utf8},
{uis_utf8, uis_utf8, uis_utf8, uis_utf8,
uis_utf8, uis_utf8, uis_utf8, uis_utf8}, };
static char s_introUngetCount[][uictMax] = { static char s_introUngetCount[][uictMax] = {
// uict00, uictBB, uictBF, uictEF, uictFE, uictFF, uictAscii, uictOther // uict00, uictBB, uictBF, uictEF, uictFE, uictFF, uictAscii, uictOther
@@ -110,22 +126,26 @@ namespace YAML
{4, 4, 4, 4, 4, 4, 4, 4}, {4, 4, 4, 4, 4, 4, 4, 4},
{2, 0, 2, 2, 2, 2, 2, 2}, {2, 0, 2, 2, 2, 2, 2, 2},
{3, 3, 0, 3, 3, 3, 3, 3}, {3, 3, 0, 3, 3, 3, 3, 3},
{1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1, 1}, };
};
inline UtfIntroCharType IntroCharTypeOf(std::istream::int_type ch) inline UtfIntroCharType IntroCharTypeOf(std::istream::int_type ch) {
{
if (std::istream::traits_type::eof() == ch) { if (std::istream::traits_type::eof() == ch) {
return uictOther; return uictOther;
} }
switch (ch) { switch (ch) {
case 0: return uict00; case 0:
case 0xBB: return uictBB; return uict00;
case 0xBF: return uictBF; case 0xBB:
case 0xEF: return uictEF; return uictBB;
case 0xFE: return uictFE; case 0xBF:
case 0xFF: return uictFF; return uictBF;
case 0xEF:
return uictEF;
case 0xFE:
return uictFE;
case 0xFF:
return uictFF;
} }
if ((ch > 0) && (ch < 0xFF)) { if ((ch > 0) && (ch < 0xFF)) {
@@ -135,41 +155,31 @@ namespace YAML
return uictOther; return uictOther;
} }
inline char Utf8Adjust(unsigned long ch, unsigned char lead_bits, unsigned char rshift) inline char Utf8Adjust(unsigned long ch, unsigned char lead_bits,
{ unsigned char rshift) {
const unsigned char header = ((1 << lead_bits) - 1) << (8 - lead_bits); const unsigned char header = ((1 << lead_bits) - 1) << (8 - lead_bits);
const unsigned char mask = (0xFF >> (lead_bits + 1)); const unsigned char mask = (0xFF >> (lead_bits + 1));
return static_cast<char>(static_cast<unsigned char>( return static_cast<char>(
header | ((ch >> rshift) & mask) static_cast<unsigned char>(header | ((ch >> rshift) & mask)));
));
} }
inline void QueueUnicodeCodepoint(std::deque<char>& q, unsigned long ch) inline void QueueUnicodeCodepoint(std::deque<char>& q, unsigned long ch) {
{
// We are not allowed to queue the Stream::eof() codepoint, so // We are not allowed to queue the Stream::eof() codepoint, so
// replace it with CP_REPLACEMENT_CHARACTER // replace it with CP_REPLACEMENT_CHARACTER
if (static_cast<unsigned long>(Stream::eof()) == ch) if (static_cast<unsigned long>(Stream::eof()) == ch) {
{
ch = CP_REPLACEMENT_CHARACTER; ch = CP_REPLACEMENT_CHARACTER;
} }
if (ch < 0x80) if (ch < 0x80) {
{
q.push_back(Utf8Adjust(ch, 0, 0)); q.push_back(Utf8Adjust(ch, 0, 0));
} } else if (ch < 0x800) {
else if (ch < 0x800)
{
q.push_back(Utf8Adjust(ch, 2, 6)); q.push_back(Utf8Adjust(ch, 2, 6));
q.push_back(Utf8Adjust(ch, 1, 0)); q.push_back(Utf8Adjust(ch, 1, 0));
} } else if (ch < 0x10000) {
else if (ch < 0x10000)
{
q.push_back(Utf8Adjust(ch, 3, 12)); q.push_back(Utf8Adjust(ch, 3, 12));
q.push_back(Utf8Adjust(ch, 1, 6)); q.push_back(Utf8Adjust(ch, 1, 6));
q.push_back(Utf8Adjust(ch, 1, 0)); q.push_back(Utf8Adjust(ch, 1, 0));
} } else {
else
{
q.push_back(Utf8Adjust(ch, 4, 18)); q.push_back(Utf8Adjust(ch, 4, 18));
q.push_back(Utf8Adjust(ch, 1, 12)); q.push_back(Utf8Adjust(ch, 1, 12));
q.push_back(Utf8Adjust(ch, 1, 6)); q.push_back(Utf8Adjust(ch, 1, 6));
@@ -180,8 +190,8 @@ namespace YAML
Stream::Stream(std::istream& input) Stream::Stream(std::istream& input)
: m_input(input), : m_input(input),
m_pPrefetched(new unsigned char[YAML_PREFETCH_SIZE]), m_pPrefetched(new unsigned char[YAML_PREFETCH_SIZE]),
m_nPrefetchedAvailable(0), m_nPrefetchedUsed(0) m_nPrefetchedAvailable(0),
{ m_nPrefetchedUsed(0) {
typedef std::istream::traits_type char_traits; typedef std::istream::traits_type char_traits;
if (!input) if (!input)
@@ -209,41 +219,47 @@ namespace YAML
} }
switch (state) { switch (state) {
case uis_utf8: m_charSet = utf8; break; case uis_utf8:
case uis_utf16le: m_charSet = utf16le; break; m_charSet = utf8;
case uis_utf16be: m_charSet = utf16be; break; break;
case uis_utf32le: m_charSet = utf32le; break; case uis_utf16le:
case uis_utf32be: m_charSet = utf32be; break; m_charSet = utf16le;
default: m_charSet = utf8; break; break;
case uis_utf16be:
m_charSet = utf16be;
break;
case uis_utf32le:
m_charSet = utf32le;
break;
case uis_utf32be:
m_charSet = utf32be;
break;
default:
m_charSet = utf8;
break;
} }
ReadAheadTo(0); ReadAheadTo(0);
} }
Stream::~Stream() Stream::~Stream() { delete[] m_pPrefetched; }
{
delete[] m_pPrefetched;
}
char Stream::peek() const char Stream::peek() const {
{ if (m_readahead.empty()) {
if (m_readahead.empty())
{
return Stream::eof(); return Stream::eof();
} }
return m_readahead[0]; return m_readahead[0];
} }
Stream::operator bool() const Stream::operator bool() const {
{ return m_input.good() ||
return m_input.good() || (!m_readahead.empty() && m_readahead[0] != Stream::eof()); (!m_readahead.empty() && m_readahead[0] != Stream::eof());
} }
// get // get
// . Extracts a character from the stream and updates our position // . Extracts a character from the stream and updates our position
char Stream::get() char Stream::get() {
{
char ch = peek(); char ch = peek();
AdvanceCurrent(); AdvanceCurrent();
m_mark.column++; m_mark.column++;
@@ -258,8 +274,7 @@ namespace YAML
// get // get
// . Extracts 'n' characters from the stream and updates our position // . Extracts 'n' characters from the stream and updates our position
std::string Stream::get(int n) std::string Stream::get(int n) {
{
std::string ret; std::string ret;
ret.reserve(n); ret.reserve(n);
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
@@ -269,16 +284,13 @@ namespace YAML
// eat // eat
// . Eats 'n' characters and updates our position. // . Eats 'n' characters and updates our position.
void Stream::eat(int n) void Stream::eat(int n) {
{
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
get(); get();
} }
void Stream::AdvanceCurrent() void Stream::AdvanceCurrent() {
{ if (!m_readahead.empty()) {
if (!m_readahead.empty())
{
m_readahead.pop_front(); m_readahead.pop_front();
m_mark.pos++; m_mark.pos++;
} }
@@ -286,17 +298,24 @@ namespace YAML
ReadAheadTo(0); ReadAheadTo(0);
} }
bool Stream::_ReadAheadTo(size_t i) const bool Stream::_ReadAheadTo(size_t i) const {
{ while (m_input.good() && (m_readahead.size() <= i)) {
while (m_input.good() && (m_readahead.size() <= i)) switch (m_charSet) {
{ case utf8:
switch (m_charSet) StreamInUtf8();
{ break;
case utf8: StreamInUtf8(); break; case utf16le:
case utf16le: StreamInUtf16(); break; StreamInUtf16();
case utf16be: StreamInUtf16(); break; break;
case utf32le: StreamInUtf32(); break; case utf16be:
case utf32be: StreamInUtf32(); break; StreamInUtf16();
break;
case utf32le:
StreamInUtf32();
break;
case utf32be:
StreamInUtf32();
break;
} }
} }
@@ -307,68 +326,56 @@ namespace YAML
return m_readahead.size() > i; return m_readahead.size() > i;
} }
void Stream::StreamInUtf8() const void Stream::StreamInUtf8() const {
{
unsigned char b = GetNextByte(); unsigned char b = GetNextByte();
if (m_input.good()) if (m_input.good()) {
{
m_readahead.push_back(b); m_readahead.push_back(b);
} }
} }
void Stream::StreamInUtf16() const void Stream::StreamInUtf16() const {
{
unsigned long ch = 0; unsigned long ch = 0;
unsigned char bytes[2]; unsigned char bytes[2];
int nBigEnd = (m_charSet == utf16be) ? 0 : 1; int nBigEnd = (m_charSet == utf16be) ? 0 : 1;
bytes[0] = GetNextByte(); bytes[0] = GetNextByte();
bytes[1] = GetNextByte(); bytes[1] = GetNextByte();
if (!m_input.good()) if (!m_input.good()) {
{
return; return;
} }
ch = (static_cast<unsigned long>(bytes[nBigEnd]) << 8) | ch = (static_cast<unsigned long>(bytes[nBigEnd]) << 8) |
static_cast<unsigned long>(bytes[1 ^ nBigEnd]); static_cast<unsigned long>(bytes[1 ^ nBigEnd]);
if (ch >= 0xDC00 && ch < 0xE000) if (ch >= 0xDC00 && ch < 0xE000) {
{
// Trailing (low) surrogate...ugh, wrong order // Trailing (low) surrogate...ugh, wrong order
QueueUnicodeCodepoint(m_readahead, CP_REPLACEMENT_CHARACTER); QueueUnicodeCodepoint(m_readahead, CP_REPLACEMENT_CHARACTER);
return; return;
} } else if (ch >= 0xD800 && ch < 0xDC00) {
else if (ch >= 0xD800 && ch < 0xDC00)
{
// ch is a leading (high) surrogate // ch is a leading (high) surrogate
// Four byte UTF-8 code point // Four byte UTF-8 code point
// Read the trailing (low) surrogate // Read the trailing (low) surrogate
for (;;) for (;;) {
{
bytes[0] = GetNextByte(); bytes[0] = GetNextByte();
bytes[1] = GetNextByte(); bytes[1] = GetNextByte();
if (!m_input.good()) if (!m_input.good()) {
{
QueueUnicodeCodepoint(m_readahead, CP_REPLACEMENT_CHARACTER); QueueUnicodeCodepoint(m_readahead, CP_REPLACEMENT_CHARACTER);
return; return;
} }
unsigned long chLow = (static_cast<unsigned long>(bytes[nBigEnd]) << 8) | unsigned long chLow = (static_cast<unsigned long>(bytes[nBigEnd]) << 8) |
static_cast<unsigned long>(bytes[1 ^ nBigEnd]); static_cast<unsigned long>(bytes[1 ^ nBigEnd]);
if (chLow < 0xDC00 || ch >= 0xE000) if (chLow < 0xDC00 || ch >= 0xE000) {
{ // Trouble...not a low surrogate. Dump a REPLACEMENT CHARACTER into the
// Trouble...not a low surrogate. Dump a REPLACEMENT CHARACTER into the stream. // stream.
QueueUnicodeCodepoint(m_readahead, CP_REPLACEMENT_CHARACTER); QueueUnicodeCodepoint(m_readahead, CP_REPLACEMENT_CHARACTER);
// Deal with the next UTF-16 unit // Deal with the next UTF-16 unit
if (chLow < 0xD800 || ch >= 0xE000) if (chLow < 0xD800 || ch >= 0xE000) {
{
// Easiest case: queue the codepoint and return // Easiest case: queue the codepoint and return
QueueUnicodeCodepoint(m_readahead, ch); QueueUnicodeCodepoint(m_readahead, ch);
return; return;
} } else {
else
{
// Start the loop over with the new high surrogate // Start the loop over with the new high surrogate
ch = chLow; ch = chLow;
continue; continue;
@@ -390,25 +397,21 @@ namespace YAML
QueueUnicodeCodepoint(m_readahead, ch); QueueUnicodeCodepoint(m_readahead, ch);
} }
inline char* ReadBuffer(unsigned char* pBuffer) inline char* ReadBuffer(unsigned char* pBuffer) {
{
return reinterpret_cast<char*>(pBuffer); return reinterpret_cast<char*>(pBuffer);
} }
unsigned char Stream::GetNextByte() const unsigned char Stream::GetNextByte() const {
{ if (m_nPrefetchedUsed >= m_nPrefetchedAvailable) {
if (m_nPrefetchedUsed >= m_nPrefetchedAvailable)
{
std::streambuf* pBuf = m_input.rdbuf(); std::streambuf* pBuf = m_input.rdbuf();
m_nPrefetchedAvailable = static_cast<std::size_t>(pBuf->sgetn(ReadBuffer(m_pPrefetched), YAML_PREFETCH_SIZE)); m_nPrefetchedAvailable = static_cast<std::size_t>(
pBuf->sgetn(ReadBuffer(m_pPrefetched), YAML_PREFETCH_SIZE));
m_nPrefetchedUsed = 0; m_nPrefetchedUsed = 0;
if (!m_nPrefetchedAvailable) if (!m_nPrefetchedAvailable) {
{
m_input.setstate(std::ios_base::eofbit); m_input.setstate(std::ios_base::eofbit);
} }
if (0 == m_nPrefetchedAvailable) if (0 == m_nPrefetchedAvailable) {
{
return 0; return 0;
} }
} }
@@ -416,12 +419,8 @@ namespace YAML
return m_pPrefetched[m_nPrefetchedUsed++]; return m_pPrefetched[m_nPrefetchedUsed++];
} }
void Stream::StreamInUtf32() const void Stream::StreamInUtf32() const {
{ static int indexes[2][4] = {{3, 2, 1, 0}, {0, 1, 2, 3}};
static int indexes[2][4] = {
{3, 2, 1, 0},
{0, 1, 2, 3}
};
unsigned long ch = 0; unsigned long ch = 0;
unsigned char bytes[4]; unsigned char bytes[4];
@@ -431,13 +430,11 @@ namespace YAML
bytes[1] = GetNextByte(); bytes[1] = GetNextByte();
bytes[2] = GetNextByte(); bytes[2] = GetNextByte();
bytes[3] = GetNextByte(); bytes[3] = GetNextByte();
if (!m_input.good()) if (!m_input.good()) {
{
return; return;
} }
for (int i = 0; i < 4; ++i) for (int i = 0; i < 4; ++i) {
{
ch <<= 8; ch <<= 8;
ch |= bytes[pIndexes[i]]; ch |= bytes[pIndexes[i]];
} }

View File

@@ -1,11 +1,12 @@
#ifndef STREAM_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef STREAM_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define STREAM_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define STREAM_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/noncopyable.h" #include "yaml-cpp/noncopyable.h"
#include "yaml-cpp/mark.h" #include "yaml-cpp/mark.h"
#include <cstddef> #include <cstddef>
@@ -15,10 +16,8 @@
#include <set> #include <set>
#include <string> #include <string>
namespace YAML namespace YAML {
{ class Stream : private noncopyable {
class Stream: private noncopyable
{
public: public:
friend class StreamCharSource; friend class StreamCharSource;
@@ -42,7 +41,13 @@ namespace YAML
void ResetColumn() { m_mark.column = 0; } void ResetColumn() { m_mark.column = 0; }
private: private:
enum CharacterSet {utf8, utf16le, utf16be, utf32le, utf32be}; enum CharacterSet {
utf8,
utf16le,
utf16be,
utf32le,
utf32be
};
std::istream& m_input; std::istream& m_input;
Mark m_mark; Mark m_mark;
@@ -65,9 +70,7 @@ namespace YAML
// CharAt // CharAt
// . Unchecked access // . Unchecked access
inline char Stream::CharAt(size_t i) const { inline char Stream::CharAt(size_t i) const { return m_readahead[i]; }
return m_readahead[i];
}
inline bool Stream::ReadAheadTo(size_t i) const { inline bool Stream::ReadAheadTo(size_t i) const {
if (m_readahead.size() > i) if (m_readahead.size() > i)

View File

@@ -1,21 +1,21 @@
#ifndef STREAMCHARSOURCE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef STREAMCHARSOURCE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define STREAMCHARSOURCE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define STREAMCHARSOURCE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/noncopyable.h" #include "yaml-cpp/noncopyable.h"
#include <cstddef> #include <cstddef>
namespace YAML namespace YAML {
{ class StreamCharSource {
class StreamCharSource
{
public: public:
StreamCharSource(const Stream& stream) : m_offset(0), m_stream(stream) {} StreamCharSource(const Stream& stream) : m_offset(0), m_stream(stream) {}
StreamCharSource(const StreamCharSource& source): m_offset(source.m_offset), m_stream(source.m_stream) {} StreamCharSource(const StreamCharSource& source)
: m_offset(source.m_offset), m_stream(source.m_stream) {}
~StreamCharSource() {} ~StreamCharSource() {}
operator bool() const; operator bool() const;

View File

@@ -1,19 +1,19 @@
#ifndef STRINGSOURCE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef STRINGSOURCE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define STRINGSOURCE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define STRINGSOURCE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <cstddef> #include <cstddef>
namespace YAML namespace YAML {
{ class StringCharSource {
class StringCharSource
{
public: public:
StringCharSource(const char *str, std::size_t size): m_str(str), m_size(size), m_offset(0) {} StringCharSource(const char* str, std::size_t size)
: m_str(str), m_size(size), m_offset(0) {}
operator bool() const { return m_offset < m_size; } operator bool() const { return m_offset < m_size; }
char operator[](std::size_t i) const { return m_str[m_offset + i]; } char operator[](std::size_t i) const { return m_str[m_offset + i]; }
@@ -37,6 +37,7 @@ namespace YAML
m_offset += offset; m_offset += offset;
return *this; return *this;
} }
private: private:
const char* m_str; const char* m_str;
std::size_t m_size; std::size_t m_size;

View File

@@ -4,10 +4,8 @@
#include <cassert> #include <cassert>
#include <stdexcept> #include <stdexcept>
namespace YAML namespace YAML {
{ Tag::Tag(const Token& token) : type(static_cast<TYPE>(token.data)) {
Tag::Tag(const Token& token): type(static_cast<TYPE>(token.data))
{
switch (type) { switch (type) {
case VERBATIM: case VERBATIM:
value = token.value; value = token.value;
@@ -29,8 +27,7 @@ namespace YAML
} }
} }
const std::string Tag::Translate(const Directives& directives) const std::string Tag::Translate(const Directives& directives) {
{
switch (type) { switch (type) {
case VERBATIM: case VERBATIM:
return value; return value;
@@ -49,4 +46,3 @@ namespace YAML
throw std::runtime_error("yaml-cpp: internal error, bad tag type"); throw std::runtime_error("yaml-cpp: internal error, bad tag type");
} }
} }

View File

@@ -1,20 +1,25 @@
#ifndef TAG_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef TAG_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define TAG_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define TAG_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include <string> #include <string>
namespace YAML namespace YAML {
{
struct Token; struct Token;
struct Directives; struct Directives;
struct Tag { struct Tag {
enum TYPE { enum TYPE {
VERBATIM, PRIMARY_HANDLE, SECONDARY_HANDLE, NAMED_HANDLE, NON_SPECIFIC VERBATIM,
PRIMARY_HANDLE,
SECONDARY_HANDLE,
NAMED_HANDLE,
NON_SPECIFIC
}; };
Tag(const Token& token); Tag(const Token& token);

View File

@@ -1,44 +1,32 @@
#ifndef TOKEN_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef TOKEN_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define TOKEN_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define TOKEN_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
#include "yaml-cpp/mark.h" #include "yaml-cpp/mark.h"
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <vector> #include <vector>
namespace YAML namespace YAML {
{
const std::string TokenNames[] = { const std::string TokenNames[] = {
"DIRECTIVE", "DIRECTIVE", "DOC_START", "DOC_END", "BLOCK_SEQ_START",
"DOC_START", "BLOCK_MAP_START", "BLOCK_SEQ_END", "BLOCK_MAP_END", "BLOCK_ENTRY",
"DOC_END", "FLOW_SEQ_START", "FLOW_MAP_START", "FLOW_SEQ_END", "FLOW_MAP_END",
"BLOCK_SEQ_START", "FLOW_MAP_COMPACT", "FLOW_ENTRY", "KEY", "VALUE",
"BLOCK_MAP_START", "ANCHOR", "ALIAS", "TAG", "SCALAR"};
"BLOCK_SEQ_END",
"BLOCK_MAP_END",
"BLOCK_ENTRY",
"FLOW_SEQ_START",
"FLOW_MAP_START",
"FLOW_SEQ_END",
"FLOW_MAP_END",
"FLOW_MAP_COMPACT",
"FLOW_ENTRY",
"KEY",
"VALUE",
"ANCHOR",
"ALIAS",
"TAG",
"SCALAR"
};
struct Token { struct Token {
// enums // enums
enum STATUS { VALID, INVALID, UNVERIFIED }; enum STATUS {
VALID,
INVALID,
UNVERIFIED
};
enum TYPE { enum TYPE {
DIRECTIVE, DIRECTIVE,
DOC_START, DOC_START,
@@ -64,7 +52,8 @@ namespace YAML
}; };
// data // data
Token(TYPE type_, const Mark& mark_): status(VALID), type(type_), mark(mark_), data(0) {} Token(TYPE type_, const Mark& mark_)
: status(VALID), type(type_), mark(mark_), data(0) {}
friend std::ostream& operator<<(std::ostream& out, const Token& token) { friend std::ostream& operator<<(std::ostream& out, const Token& token) {
out << TokenNames[token.type] << std::string(": ") << token.value; out << TokenNames[token.type] << std::string(": ") << token.value;

View File

@@ -3,22 +3,20 @@
#include "yaml-cpp/yaml.h" #include "yaml-cpp/yaml.h"
#include <iostream> #include <iostream>
namespace Test namespace Test {
{
namespace Parser { namespace Parser {
TEST NoEndOfMapFlow() TEST NoEndOfMapFlow() {
{
try { try {
HANDLE("---{header: {id: 1"); HANDLE("---{header: {id: 1");
} catch(const YAML::ParserException& e) { }
catch (const YAML::ParserException& e) {
YAML_ASSERT(e.msg == std::string(YAML::ErrorMsg::END_OF_MAP_FLOW)); YAML_ASSERT(e.msg == std::string(YAML::ErrorMsg::END_OF_MAP_FLOW));
return true; return true;
} }
return " no exception caught"; return " no exception caught";
} }
TEST PlainScalarStartingWithQuestionMark() TEST PlainScalarStartingWithQuestionMark() {
{
HANDLE("foo: ?bar"); HANDLE("foo: ?bar");
EXPECT_DOC_START(); EXPECT_DOC_START();
EXPECT_MAP_START("?", 0); EXPECT_MAP_START("?", 0);
@@ -29,8 +27,7 @@ namespace Test
DONE(); DONE();
} }
TEST NullStringScalar() TEST NullStringScalar() {
{
HANDLE("foo: null"); HANDLE("foo: null");
EXPECT_DOC_START(); EXPECT_DOC_START();
EXPECT_MAP_START("?", 0); EXPECT_MAP_START("?", 0);
@@ -43,11 +40,13 @@ namespace Test
} }
namespace { namespace {
void RunParserTest(TEST (*test)(), const std::string& name, int& passed, int& total) { void RunParserTest(TEST (*test)(), const std::string& name, int& passed,
int& total) {
TEST ret; TEST ret;
try { try {
ret = test(); ret = test();
} catch(const YAML::Exception& e) { }
catch (const YAML::Exception& e) {
ret.ok = false; ret.ok = false;
ret.error = std::string(" Exception caught: ") + e.what(); ret.error = std::string(" Exception caught: ") + e.what();
} }
@@ -63,12 +62,12 @@ namespace Test
} }
} }
bool RunParserTests() bool RunParserTests() {
{
int passed = 0; int passed = 0;
int total = 0; int total = 0;
RunParserTest(&Parser::NoEndOfMapFlow, "No end of map flow", passed, total); RunParserTest(&Parser::NoEndOfMapFlow, "No end of map flow", passed, total);
RunParserTest(&Parser::PlainScalarStartingWithQuestionMark, "Plain scalar starting with question mark", passed, total); RunParserTest(&Parser::PlainScalarStartingWithQuestionMark,
"Plain scalar starting with question mark", passed, total);
RunParserTest(&Parser::NullStringScalar, "Null string scalar", passed, total); RunParserTest(&Parser::NullStringScalar, "Null string scalar", passed, total);
std::cout << "Parser tests: " << passed << "/" << total << " passed\n"; std::cout << "Parser tests: " << passed << "/" << total << " passed\n";

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,9 @@
#ifndef EMITTERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef EMITTERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define EMITTERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define EMITTERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
@@ -10,4 +12,3 @@ namespace Test {
} }
#endif // EMITTERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // EMITTERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66

File diff suppressed because it is too large Load Diff

View File

@@ -14,12 +14,24 @@ namespace Test {
} }
struct Event { struct Event {
enum Type { DocStart, DocEnd, Null, Alias, Scalar, SeqStart, SeqEnd, MapStart, MapEnd }; enum Type {
DocStart,
DocEnd,
Null,
Alias,
Scalar,
SeqStart,
SeqEnd,
MapStart,
MapEnd
};
typedef YAML::Mark Mark; typedef YAML::Mark Mark;
typedef YAML::anchor_t anchor_t; typedef YAML::anchor_t anchor_t;
Event(Type type_, const std::string& tag_, anchor_t anchor_, const std::string& scalar_): type(type_), tag(tag_), anchor(anchor_), scalar(scalar_) {} Event(Type type_, const std::string& tag_, anchor_t anchor_,
const std::string& scalar_)
: type(type_), tag(tag_), anchor(anchor_), scalar(scalar_) {}
Type type; Type type;
std::string tag; std::string tag;
@@ -37,7 +49,8 @@ namespace Test {
case Alias: case Alias:
return out << "Alias(" << anchor << ")"; return out << "Alias(" << anchor << ")";
case Scalar: case Scalar:
return out << "Scalar(" << Quote(tag) << ", " << anchor << ", " << Quote(scalar) << ")"; return out << "Scalar(" << Quote(tag) << ", " << anchor << ", "
<< Quote(scalar) << ")";
case SeqStart: case SeqStart:
return out << "SeqStart(" << Quote(tag) << ", " << anchor << ")"; return out << "SeqStart(" << Quote(tag) << ", " << anchor << ")";
case SeqEnd: case SeqEnd:
@@ -57,15 +70,13 @@ namespace Test {
} }
inline bool operator==(const Event& a, const Event& b) { inline bool operator==(const Event& a, const Event& b) {
return a.type == b.type && a.tag == b.tag && a.anchor == b.anchor && a.scalar == b.scalar; return a.type == b.type && a.tag == b.tag && a.anchor == b.anchor &&
a.scalar == b.scalar;
} }
inline bool operator != (const Event& a, const Event& b) { inline bool operator!=(const Event& a, const Event& b) { return !(a == b); }
return !(a == b);
}
class MockEventHandler: public YAML::EventHandler class MockEventHandler : public YAML::EventHandler {
{
public: public:
typedef YAML::Mark Mark; typedef YAML::Mark Mark;
typedef YAML::anchor_t anchor_t; typedef YAML::anchor_t anchor_t;
@@ -88,11 +99,13 @@ namespace Test {
m_actualEvents.push_back(Event(Event::Alias, "", anchor, "")); m_actualEvents.push_back(Event(Event::Alias, "", anchor, ""));
} }
virtual void OnScalar(const Mark&, const std::string& tag, anchor_t anchor, const std::string& value) { virtual void OnScalar(const Mark&, const std::string& tag, anchor_t anchor,
const std::string& value) {
m_actualEvents.push_back(Event(Event::Scalar, tag, anchor, value)); m_actualEvents.push_back(Event(Event::Scalar, tag, anchor, value));
} }
virtual void OnSequenceStart(const Mark&, const std::string& tag, anchor_t anchor) { virtual void OnSequenceStart(const Mark&, const std::string& tag,
anchor_t anchor) {
m_actualEvents.push_back(Event(Event::SeqStart, tag, anchor, "")); m_actualEvents.push_back(Event(Event::SeqStart, tag, anchor, ""));
} }
@@ -100,7 +113,8 @@ namespace Test {
m_actualEvents.push_back(Event(Event::SeqEnd, "", 0, "")); m_actualEvents.push_back(Event(Event::SeqEnd, "", 0, ""));
} }
virtual void OnMapStart(const Mark&, const std::string& tag, anchor_t anchor) { virtual void OnMapStart(const Mark&, const std::string& tag,
anchor_t anchor) {
m_actualEvents.push_back(Event(Event::MapStart, tag, anchor, "")); m_actualEvents.push_back(Event(Event::MapStart, tag, anchor, ""));
} }
@@ -155,19 +169,16 @@ namespace Test {
MockEventHandler handler; \ MockEventHandler handler; \
std::stringstream stream(ex); \ std::stringstream stream(ex); \
YAML::Parser parser(stream); \ YAML::Parser parser(stream); \
while(parser.HandleNextDocument(handler)) {} while (parser.HandleNextDocument(handler)) { \
}
#define EXPECT_DOC_START()\ #define EXPECT_DOC_START() handler.Expect(Event(Event::DocStart, "", 0, ""))
handler.Expect(Event(Event::DocStart, "", 0, ""))
#define EXPECT_DOC_END()\ #define EXPECT_DOC_END() handler.Expect(Event(Event::DocEnd, "", 0, ""))
handler.Expect(Event(Event::DocEnd, "", 0, ""))
#define EXPECT_NULL(anchor)\ #define EXPECT_NULL(anchor) handler.Expect(Event(Event::Null, "", anchor, ""))
handler.Expect(Event(Event::Null, "", anchor, ""))
#define EXPECT_ALIAS(anchor)\ #define EXPECT_ALIAS(anchor) handler.Expect(Event(Event::Alias, "", anchor, ""))
handler.Expect(Event(Event::Alias, "", anchor, ""))
#define EXPECT_SCALAR(tag, anchor, value) \ #define EXPECT_SCALAR(tag, anchor, value) \
handler.Expect(Event(Event::Scalar, tag, anchor, value)) handler.Expect(Event(Event::Scalar, tag, anchor, value))
@@ -175,16 +186,12 @@ handler.Expect(Event(Event::Scalar, tag, anchor, value))
#define EXPECT_SEQ_START(tag, anchor) \ #define EXPECT_SEQ_START(tag, anchor) \
handler.Expect(Event(Event::SeqStart, tag, anchor, "")) handler.Expect(Event(Event::SeqStart, tag, anchor, ""))
#define EXPECT_SEQ_END()\ #define EXPECT_SEQ_END() handler.Expect(Event(Event::SeqEnd, "", 0, ""))
handler.Expect(Event(Event::SeqEnd, "", 0, ""))
#define EXPECT_MAP_START(tag, anchor) \ #define EXPECT_MAP_START(tag, anchor) \
handler.Expect(Event(Event::MapStart, tag, anchor, "")) handler.Expect(Event(Event::MapStart, tag, anchor, ""))
#define EXPECT_MAP_END()\ #define EXPECT_MAP_END() handler.Expect(Event(Event::MapEnd, "", 0, ""))
handler.Expect(Event(Event::MapEnd, "", 0, ""))
#define DONE()\
return handler.Check()
#define DONE() return handler.Check()
} }

View File

@@ -1,7 +1,6 @@
#include "tests.h" #include "tests.h"
int main() int main() {
{
Test::RunAll(); Test::RunAll();
return 0; return 0;
} }

View File

@@ -1,7 +1,9 @@
#ifndef PARSERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef PARSERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define PARSERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define PARSERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
@@ -10,4 +12,3 @@ namespace Test {
} }
#endif // PARSERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // PARSERTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -280,8 +280,7 @@ namespace Test {
"sequence: [ one, two, ]\n" "sequence: [ one, two, ]\n"
"mapping: { sky: blue, sea: green }"; "mapping: { sky: blue, sea: green }";
const char *ex5_5 = const char *ex5_5 = "# Comment only.";
"# Comment only.";
const char *ex5_6 = const char *ex5_6 =
"anchored: !local &anchor value\n" "anchored: !local &anchor value\n"
@@ -554,8 +553,7 @@ namespace Test {
" 2nd non-empty \n" " 2nd non-empty \n"
"\t3rd non-empty \""; "\t3rd non-empty \"";
const char *ex7_7 = const char *ex7_7 = " 'here''s to \"quotes\"'";
" 'here''s to \"quotes\"'";
const char *ex7_8 = const char *ex7_8 =
"'implicit block key' : [\n" "'implicit block key' : [\n"
@@ -651,7 +649,8 @@ namespace Test {
const char *ex7_22 = const char *ex7_22 =
"[ foo\n" "[ foo\n"
" bar: invalid,"; // Note: we don't check (on purpose) the >1K chars for an implicit key " bar: invalid,"; // Note: we don't check (on purpose) the >1K chars for an
// implicit key
const char *ex7_23 = const char *ex7_23 =
"- [ a, b ]\n" "- [ a, b ]\n"
@@ -847,4 +846,3 @@ namespace Test {
" foo: bar\n"; " foo: bar\n";
} }
} }

View File

@@ -2,14 +2,15 @@
#include "yaml-cpp/yaml.h" #include "yaml-cpp/yaml.h"
#include <iostream> #include <iostream>
namespace Test namespace Test {
{
namespace { namespace {
void RunSpecTest(TEST (*test)(), const std::string& index, const std::string& name, int& passed, int& total) { void RunSpecTest(TEST (*test)(), const std::string& index,
const std::string& name, int& passed, int& total) {
TEST ret; TEST ret;
try { try {
ret = test(); ret = test();
} catch(const YAML::Exception& e) { }
catch (const YAML::Exception& e) {
ret.ok = false; ret.ok = false;
ret.error = std::string(" Exception caught: ") + e.what(); ret.error = std::string(" Exception caught: ") + e.what();
} }
@@ -25,123 +26,197 @@ namespace Test
} }
} }
bool RunSpecTests() bool RunSpecTests() {
{
int passed = 0; int passed = 0;
int total = 0; int total = 0;
RunSpecTest(&Spec::SeqScalars, "2.1", "Sequence of Scalars", passed, total); RunSpecTest(&Spec::SeqScalars, "2.1", "Sequence of Scalars", passed, total);
RunSpecTest(&Spec::MappingScalarsToScalars, "2.2", "Mapping Scalars to Scalars", passed, total); RunSpecTest(&Spec::MappingScalarsToScalars, "2.2",
RunSpecTest(&Spec::MappingScalarsToSequences, "2.3", "Mapping Scalars to Sequences", passed, total); "Mapping Scalars to Scalars", passed, total);
RunSpecTest(&Spec::SequenceOfMappings, "2.4", "Sequence of Mappings", passed, total); RunSpecTest(&Spec::MappingScalarsToSequences, "2.3",
RunSpecTest(&Spec::SequenceOfSequences, "2.5", "Sequence of Sequences", passed, total); "Mapping Scalars to Sequences", passed, total);
RunSpecTest(&Spec::MappingOfMappings, "2.6", "Mapping of Mappings", passed, total); RunSpecTest(&Spec::SequenceOfMappings, "2.4", "Sequence of Mappings", passed,
RunSpecTest(&Spec::TwoDocumentsInAStream, "2.7", "Two Documents in a Stream", passed, total); total);
RunSpecTest(&Spec::PlayByPlayFeed, "2.8", "Play by Play Feed from a Game", passed, total); RunSpecTest(&Spec::SequenceOfSequences, "2.5", "Sequence of Sequences",
RunSpecTest(&Spec::SingleDocumentWithTwoComments, "2.9", "Single Document with Two Comments", passed, total); passed, total);
RunSpecTest(&Spec::SimpleAnchor, "2.10", "Node for \"Sammy Sosa\" appears twice in this document", passed, total); RunSpecTest(&Spec::MappingOfMappings, "2.6", "Mapping of Mappings", passed,
RunSpecTest(&Spec::MappingBetweenSequences, "2.11", "Mapping between Sequences", passed, total); total);
RunSpecTest(&Spec::CompactNestedMapping, "2.12", "Compact Nested Mapping", passed, total); RunSpecTest(&Spec::TwoDocumentsInAStream, "2.7", "Two Documents in a Stream",
RunSpecTest(&Spec::InLiteralsNewlinesArePreserved, "2.13", "In literals, newlines are preserved", passed, total); passed, total);
RunSpecTest(&Spec::InFoldedScalarsNewlinesBecomeSpaces, "2.14", "In folded scalars, newlines become spaces", passed, total); RunSpecTest(&Spec::PlayByPlayFeed, "2.8", "Play by Play Feed from a Game",
RunSpecTest(&Spec::FoldedNewlinesArePreservedForMoreIndentedAndBlankLines, "2.15", "Folded newlines are preserved for \"more indented\" and blank lines", passed, total); passed, total);
RunSpecTest(&Spec::IndentationDeterminesScope, "2.16", "Indentation determines scope", passed, total); RunSpecTest(&Spec::SingleDocumentWithTwoComments, "2.9",
"Single Document with Two Comments", passed, total);
RunSpecTest(&Spec::SimpleAnchor, "2.10",
"Node for \"Sammy Sosa\" appears twice in this document", passed,
total);
RunSpecTest(&Spec::MappingBetweenSequences, "2.11",
"Mapping between Sequences", passed, total);
RunSpecTest(&Spec::CompactNestedMapping, "2.12", "Compact Nested Mapping",
passed, total);
RunSpecTest(&Spec::InLiteralsNewlinesArePreserved, "2.13",
"In literals, newlines are preserved", passed, total);
RunSpecTest(&Spec::InFoldedScalarsNewlinesBecomeSpaces, "2.14",
"In folded scalars, newlines become spaces", passed, total);
RunSpecTest(
&Spec::FoldedNewlinesArePreservedForMoreIndentedAndBlankLines, "2.15",
"Folded newlines are preserved for \"more indented\" and blank lines",
passed, total);
RunSpecTest(&Spec::IndentationDeterminesScope, "2.16",
"Indentation determines scope", passed, total);
RunSpecTest(&Spec::QuotedScalars, "2.17", "Quoted scalars", passed, total); RunSpecTest(&Spec::QuotedScalars, "2.17", "Quoted scalars", passed, total);
RunSpecTest(&Spec::MultiLineFlowScalars, "2.18", "Multi-line flow scalars", passed, total); RunSpecTest(&Spec::MultiLineFlowScalars, "2.18", "Multi-line flow scalars",
passed, total);
RunSpecTest(&Spec::VariousExplicitTags, "2.23", "Various Explicit Tags", passed, total); RunSpecTest(&Spec::VariousExplicitTags, "2.23", "Various Explicit Tags",
passed, total);
RunSpecTest(&Spec::GlobalTags, "2.24", "Global Tags", passed, total); RunSpecTest(&Spec::GlobalTags, "2.24", "Global Tags", passed, total);
RunSpecTest(&Spec::UnorderedSets, "2.25", "Unordered Sets", passed, total); RunSpecTest(&Spec::UnorderedSets, "2.25", "Unordered Sets", passed, total);
RunSpecTest(&Spec::OrderedMappings, "2.26", "Ordered Mappings", passed, total); RunSpecTest(&Spec::OrderedMappings, "2.26", "Ordered Mappings", passed,
total);
RunSpecTest(&Spec::Invoice, "2.27", "Invoice", passed, total); RunSpecTest(&Spec::Invoice, "2.27", "Invoice", passed, total);
RunSpecTest(&Spec::LogFile, "2.28", "Log File", passed, total); RunSpecTest(&Spec::LogFile, "2.28", "Log File", passed, total);
RunSpecTest(&Spec::BlockStructureIndicators, "5.3", "Block Structure Indicators", passed, total); RunSpecTest(&Spec::BlockStructureIndicators, "5.3",
RunSpecTest(&Spec::FlowStructureIndicators, "5.4", "Flow Structure Indicators", passed, total); "Block Structure Indicators", passed, total);
RunSpecTest(&Spec::NodePropertyIndicators, "5.6", "Node Property Indicators", passed, total); RunSpecTest(&Spec::FlowStructureIndicators, "5.4",
RunSpecTest(&Spec::BlockScalarIndicators, "5.7", "Block Scalar Indicators", passed, total); "Flow Structure Indicators", passed, total);
RunSpecTest(&Spec::QuotedScalarIndicators, "5.8", "Quoted Scalar Indicators", passed, total); RunSpecTest(&Spec::NodePropertyIndicators, "5.6", "Node Property Indicators",
RunSpecTest(&Spec::LineBreakCharacters, "5.11", "Line Break Characters", passed, total); passed, total);
RunSpecTest(&Spec::BlockScalarIndicators, "5.7", "Block Scalar Indicators",
passed, total);
RunSpecTest(&Spec::QuotedScalarIndicators, "5.8", "Quoted Scalar Indicators",
passed, total);
RunSpecTest(&Spec::LineBreakCharacters, "5.11", "Line Break Characters",
passed, total);
RunSpecTest(&Spec::TabsAndSpaces, "5.12", "Tabs and Spaces", passed, total); RunSpecTest(&Spec::TabsAndSpaces, "5.12", "Tabs and Spaces", passed, total);
RunSpecTest(&Spec::EscapedCharacters, "5.13", "Escaped Characters", passed, total); RunSpecTest(&Spec::EscapedCharacters, "5.13", "Escaped Characters", passed,
RunSpecTest(&Spec::InvalidEscapedCharacters, "5.14", "Invalid Escaped Characters", passed, total); total);
RunSpecTest(&Spec::InvalidEscapedCharacters, "5.14",
"Invalid Escaped Characters", passed, total);
RunSpecTest(&Spec::IndentationSpaces, "6.1", "Indentation Spaces", passed, total); RunSpecTest(&Spec::IndentationSpaces, "6.1", "Indentation Spaces", passed,
RunSpecTest(&Spec::IndentationIndicators, "6.2", "Indentation Indicators", passed, total); total);
RunSpecTest(&Spec::SeparationSpaces, "6.3", "Separation Spaces", passed, total); RunSpecTest(&Spec::IndentationIndicators, "6.2", "Indentation Indicators",
passed, total);
RunSpecTest(&Spec::SeparationSpaces, "6.3", "Separation Spaces", passed,
total);
RunSpecTest(&Spec::LinePrefixes, "6.4", "Line Prefixes", passed, total); RunSpecTest(&Spec::LinePrefixes, "6.4", "Line Prefixes", passed, total);
RunSpecTest(&Spec::EmptyLines, "6.5", "Empty Lines", passed, total); RunSpecTest(&Spec::EmptyLines, "6.5", "Empty Lines", passed, total);
RunSpecTest(&Spec::LineFolding, "6.6", "Line Folding", passed, total); RunSpecTest(&Spec::LineFolding, "6.6", "Line Folding", passed, total);
RunSpecTest(&Spec::BlockFolding, "6.7", "Block Folding", passed, total); RunSpecTest(&Spec::BlockFolding, "6.7", "Block Folding", passed, total);
RunSpecTest(&Spec::FlowFolding, "6.8", "Flow Folding", passed, total); RunSpecTest(&Spec::FlowFolding, "6.8", "Flow Folding", passed, total);
RunSpecTest(&Spec::SeparatedComment, "6.9", "Separated Comment", passed, total); RunSpecTest(&Spec::SeparatedComment, "6.9", "Separated Comment", passed,
total);
RunSpecTest(&Spec::CommentLines, "6.10", "Comment Lines", passed, total); RunSpecTest(&Spec::CommentLines, "6.10", "Comment Lines", passed, total);
RunSpecTest(&Spec::MultiLineComments, "6.11", "Multi-Line Comments", passed, total); RunSpecTest(&Spec::MultiLineComments, "6.11", "Multi-Line Comments", passed,
RunSpecTest(&Spec::SeparationSpacesII, "6.12", "Separation Spaces", passed, total); total);
RunSpecTest(&Spec::ReservedDirectives, "6.13", "Reserved Directives", passed, total); RunSpecTest(&Spec::SeparationSpacesII, "6.12", "Separation Spaces", passed,
total);
RunSpecTest(&Spec::ReservedDirectives, "6.13", "Reserved Directives", passed,
total);
RunSpecTest(&Spec::YAMLDirective, "6.14", "YAML Directive", passed, total); RunSpecTest(&Spec::YAMLDirective, "6.14", "YAML Directive", passed, total);
RunSpecTest(&Spec::InvalidRepeatedYAMLDirective, "6.15", "Invalid Repeated YAML Directive", passed, total); RunSpecTest(&Spec::InvalidRepeatedYAMLDirective, "6.15",
"Invalid Repeated YAML Directive", passed, total);
RunSpecTest(&Spec::TagDirective, "6.16", "Tag Directive", passed, total); RunSpecTest(&Spec::TagDirective, "6.16", "Tag Directive", passed, total);
RunSpecTest(&Spec::InvalidRepeatedTagDirective, "6.17", "Invalid Repeated Tag Directive", passed, total); RunSpecTest(&Spec::InvalidRepeatedTagDirective, "6.17",
RunSpecTest(&Spec::PrimaryTagHandle, "6.18", "Primary Tag Handle", passed, total); "Invalid Repeated Tag Directive", passed, total);
RunSpecTest(&Spec::SecondaryTagHandle, "6.19", "SecondaryTagHandle", passed, total); RunSpecTest(&Spec::PrimaryTagHandle, "6.18", "Primary Tag Handle", passed,
total);
RunSpecTest(&Spec::SecondaryTagHandle, "6.19", "SecondaryTagHandle", passed,
total);
RunSpecTest(&Spec::TagHandles, "6.20", "TagHandles", passed, total); RunSpecTest(&Spec::TagHandles, "6.20", "TagHandles", passed, total);
RunSpecTest(&Spec::LocalTagPrefix, "6.21", "LocalTagPrefix", passed, total); RunSpecTest(&Spec::LocalTagPrefix, "6.21", "LocalTagPrefix", passed, total);
RunSpecTest(&Spec::GlobalTagPrefix, "6.22", "GlobalTagPrefix", passed, total); RunSpecTest(&Spec::GlobalTagPrefix, "6.22", "GlobalTagPrefix", passed, total);
RunSpecTest(&Spec::NodeProperties, "6.23", "NodeProperties", passed, total); RunSpecTest(&Spec::NodeProperties, "6.23", "NodeProperties", passed, total);
RunSpecTest(&Spec::VerbatimTags, "6.24", "Verbatim Tags", passed, total); RunSpecTest(&Spec::VerbatimTags, "6.24", "Verbatim Tags", passed, total);
RunSpecTest(&Spec::InvalidVerbatimTags, "6.25", "Invalid Verbatim Tags", passed, total); RunSpecTest(&Spec::InvalidVerbatimTags, "6.25", "Invalid Verbatim Tags",
passed, total);
RunSpecTest(&Spec::TagShorthands, "6.26", "Tag Shorthands", passed, total); RunSpecTest(&Spec::TagShorthands, "6.26", "Tag Shorthands", passed, total);
RunSpecTest(&Spec::InvalidTagShorthands, "6.27", "Invalid Tag Shorthands", passed, total); RunSpecTest(&Spec::InvalidTagShorthands, "6.27", "Invalid Tag Shorthands",
RunSpecTest(&Spec::NonSpecificTags, "6.28", "Non Specific Tags", passed, total); passed, total);
RunSpecTest(&Spec::NonSpecificTags, "6.28", "Non Specific Tags", passed,
total);
RunSpecTest(&Spec::NodeAnchors, "6.29", "Node Anchors", passed, total); RunSpecTest(&Spec::NodeAnchors, "6.29", "Node Anchors", passed, total);
RunSpecTest(&Spec::AliasNodes, "7.1", "Alias Nodes", passed, total); RunSpecTest(&Spec::AliasNodes, "7.1", "Alias Nodes", passed, total);
RunSpecTest(&Spec::EmptyNodes, "7.2", "Empty Nodes", passed, total); RunSpecTest(&Spec::EmptyNodes, "7.2", "Empty Nodes", passed, total);
RunSpecTest(&Spec::CompletelyEmptyNodes, "7.3", "Completely Empty Nodes", passed, total); RunSpecTest(&Spec::CompletelyEmptyNodes, "7.3", "Completely Empty Nodes",
RunSpecTest(&Spec::DoubleQuotedImplicitKeys, "7.4", "Double Quoted Implicit Keys", passed, total); passed, total);
RunSpecTest(&Spec::DoubleQuotedLineBreaks, "7.5", "Double Quoted Line Breaks", passed, total); RunSpecTest(&Spec::DoubleQuotedImplicitKeys, "7.4",
RunSpecTest(&Spec::DoubleQuotedLines, "7.6", "Double Quoted Lines", passed, total); "Double Quoted Implicit Keys", passed, total);
RunSpecTest(&Spec::SingleQuotedCharacters, "7.7", "Single Quoted Characters", passed, total); RunSpecTest(&Spec::DoubleQuotedLineBreaks, "7.5", "Double Quoted Line Breaks",
RunSpecTest(&Spec::SingleQuotedImplicitKeys, "7.8", "Single Quoted Implicit Keys", passed, total); passed, total);
RunSpecTest(&Spec::SingleQuotedLines, "7.9", "Single Quoted Lines", passed, total); RunSpecTest(&Spec::DoubleQuotedLines, "7.6", "Double Quoted Lines", passed,
RunSpecTest(&Spec::PlainCharacters, "7.10", "Plain Characters", passed, total); total);
RunSpecTest(&Spec::PlainImplicitKeys, "7.11", "Plain Implicit Keys", passed, total); RunSpecTest(&Spec::SingleQuotedCharacters, "7.7", "Single Quoted Characters",
passed, total);
RunSpecTest(&Spec::SingleQuotedImplicitKeys, "7.8",
"Single Quoted Implicit Keys", passed, total);
RunSpecTest(&Spec::SingleQuotedLines, "7.9", "Single Quoted Lines", passed,
total);
RunSpecTest(&Spec::PlainCharacters, "7.10", "Plain Characters", passed,
total);
RunSpecTest(&Spec::PlainImplicitKeys, "7.11", "Plain Implicit Keys", passed,
total);
RunSpecTest(&Spec::PlainLines, "7.12", "Plain Lines", passed, total); RunSpecTest(&Spec::PlainLines, "7.12", "Plain Lines", passed, total);
RunSpecTest(&Spec::FlowSequence, "7.13", "Flow Sequence", passed, total); RunSpecTest(&Spec::FlowSequence, "7.13", "Flow Sequence", passed, total);
RunSpecTest(&Spec::FlowSequenceEntries, "7.14", "Flow Sequence Entries", passed, total); RunSpecTest(&Spec::FlowSequenceEntries, "7.14", "Flow Sequence Entries",
passed, total);
RunSpecTest(&Spec::FlowMappings, "7.15", "Flow Mappings", passed, total); RunSpecTest(&Spec::FlowMappings, "7.15", "Flow Mappings", passed, total);
RunSpecTest(&Spec::FlowMappingEntries, "7.16", "Flow Mapping Entries", passed, total); RunSpecTest(&Spec::FlowMappingEntries, "7.16", "Flow Mapping Entries", passed,
RunSpecTest(&Spec::FlowMappingSeparateValues, "7.17", "Flow Mapping Separate Values", passed, total); total);
RunSpecTest(&Spec::FlowMappingAdjacentValues, "7.18", "Flow Mapping Adjacent Values", passed, total); RunSpecTest(&Spec::FlowMappingSeparateValues, "7.17",
RunSpecTest(&Spec::SinglePairFlowMappings, "7.19", "Single Pair Flow Mappings", passed, total); "Flow Mapping Separate Values", passed, total);
RunSpecTest(&Spec::SinglePairExplicitEntry, "7.20", "Single Pair Explicit Entry", passed, total); RunSpecTest(&Spec::FlowMappingAdjacentValues, "7.18",
RunSpecTest(&Spec::SinglePairImplicitEntries, "7.21", "Single Pair Implicit Entries", passed, total); "Flow Mapping Adjacent Values", passed, total);
RunSpecTest(&Spec::InvalidImplicitKeys, "7.22", "Invalid Implicit Keys", passed, total); RunSpecTest(&Spec::SinglePairFlowMappings, "7.19",
"Single Pair Flow Mappings", passed, total);
RunSpecTest(&Spec::SinglePairExplicitEntry, "7.20",
"Single Pair Explicit Entry", passed, total);
RunSpecTest(&Spec::SinglePairImplicitEntries, "7.21",
"Single Pair Implicit Entries", passed, total);
RunSpecTest(&Spec::InvalidImplicitKeys, "7.22", "Invalid Implicit Keys",
passed, total);
RunSpecTest(&Spec::FlowContent, "7.23", "Flow Content", passed, total); RunSpecTest(&Spec::FlowContent, "7.23", "Flow Content", passed, total);
RunSpecTest(&Spec::FlowNodes, "7.24", "FlowNodes", passed, total); RunSpecTest(&Spec::FlowNodes, "7.24", "FlowNodes", passed, total);
RunSpecTest(&Spec::BlockScalarHeader, "8.1", "Block Scalar Header", passed, total); RunSpecTest(&Spec::BlockScalarHeader, "8.1", "Block Scalar Header", passed,
RunSpecTest(&Spec::BlockIndentationHeader, "8.2", "Block Indentation Header", passed, total); total);
RunSpecTest(&Spec::InvalidBlockScalarIndentationIndicators, "8.3", "Invalid Block Scalar Indentation Indicators", passed, total); RunSpecTest(&Spec::BlockIndentationHeader, "8.2", "Block Indentation Header",
RunSpecTest(&Spec::ChompingFinalLineBreak, "8.4", "Chomping Final Line Break", passed, total); passed, total);
RunSpecTest(&Spec::ChompingTrailingLines, "8.5", "Chomping Trailing Lines", passed, total); RunSpecTest(&Spec::InvalidBlockScalarIndentationIndicators, "8.3",
RunSpecTest(&Spec::EmptyScalarChomping, "8.6", "Empty Scalar Chomping", passed, total); "Invalid Block Scalar Indentation Indicators", passed, total);
RunSpecTest(&Spec::ChompingFinalLineBreak, "8.4", "Chomping Final Line Break",
passed, total);
RunSpecTest(&Spec::ChompingTrailingLines, "8.5", "Chomping Trailing Lines",
passed, total);
RunSpecTest(&Spec::EmptyScalarChomping, "8.6", "Empty Scalar Chomping",
passed, total);
RunSpecTest(&Spec::LiteralScalar, "8.7", "Literal Scalar", passed, total); RunSpecTest(&Spec::LiteralScalar, "8.7", "Literal Scalar", passed, total);
RunSpecTest(&Spec::LiteralContent, "8.8", "Literal Content", passed, total); RunSpecTest(&Spec::LiteralContent, "8.8", "Literal Content", passed, total);
RunSpecTest(&Spec::FoldedScalar, "8.9", "Folded Scalar", passed, total); RunSpecTest(&Spec::FoldedScalar, "8.9", "Folded Scalar", passed, total);
RunSpecTest(&Spec::FoldedLines, "8.10", "Folded Lines", passed, total); RunSpecTest(&Spec::FoldedLines, "8.10", "Folded Lines", passed, total);
RunSpecTest(&Spec::MoreIndentedLines, "8.11", "More Indented Lines", passed, total); RunSpecTest(&Spec::MoreIndentedLines, "8.11", "More Indented Lines", passed,
RunSpecTest(&Spec::EmptySeparationLines, "8.12", "Empty Separation Lines", passed, total); total);
RunSpecTest(&Spec::FinalEmptyLines, "8.13", "Final Empty Lines", passed, total); RunSpecTest(&Spec::EmptySeparationLines, "8.12", "Empty Separation Lines",
passed, total);
RunSpecTest(&Spec::FinalEmptyLines, "8.13", "Final Empty Lines", passed,
total);
RunSpecTest(&Spec::BlockSequence, "8.14", "Block Sequence", passed, total); RunSpecTest(&Spec::BlockSequence, "8.14", "Block Sequence", passed, total);
RunSpecTest(&Spec::BlockSequenceEntryTypes, "8.15", "Block Sequence Entry Types", passed, total); RunSpecTest(&Spec::BlockSequenceEntryTypes, "8.15",
"Block Sequence Entry Types", passed, total);
RunSpecTest(&Spec::BlockMappings, "8.16", "Block Mappings", passed, total); RunSpecTest(&Spec::BlockMappings, "8.16", "Block Mappings", passed, total);
RunSpecTest(&Spec::ExplicitBlockMappingEntries, "8.17", "Explicit Block Mapping Entries", passed, total); RunSpecTest(&Spec::ExplicitBlockMappingEntries, "8.17",
RunSpecTest(&Spec::ImplicitBlockMappingEntries, "8.18", "Implicit Block Mapping Entries", passed, total); "Explicit Block Mapping Entries", passed, total);
RunSpecTest(&Spec::CompactBlockMappings, "8.19", "Compact Block Mappings", passed, total); RunSpecTest(&Spec::ImplicitBlockMappingEntries, "8.18",
"Implicit Block Mapping Entries", passed, total);
RunSpecTest(&Spec::CompactBlockMappings, "8.19", "Compact Block Mappings",
passed, total);
RunSpecTest(&Spec::BlockNodeTypes, "8.20", "Block Node Types", passed, total); RunSpecTest(&Spec::BlockNodeTypes, "8.20", "Block Node Types", passed, total);
RunSpecTest(&Spec::BlockScalarNodes, "8.21", "Block Scalar Nodes", passed, total); RunSpecTest(&Spec::BlockScalarNodes, "8.21", "Block Scalar Nodes", passed,
RunSpecTest(&Spec::BlockCollectionNodes, "8.22", "Block Collection Nodes", passed, total); total);
RunSpecTest(&Spec::BlockCollectionNodes, "8.22", "Block Collection Nodes",
passed, total);
std::cout << "Spec tests: " << passed << "/" << total << " passed\n"; std::cout << "Spec tests: " << passed << "/" << total << " passed\n";
return passed == total; return passed == total;

View File

@@ -1,7 +1,9 @@
#ifndef SPECTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef SPECTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define SPECTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define SPECTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
@@ -348,4 +350,3 @@ namespace Test {
} }
#endif // SPECTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // SPECTESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66

View File

@@ -1,7 +1,9 @@
#ifndef TESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #ifndef TESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#define TESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define TESTS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #if defined(_MSC_VER) || \
(defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || \
(__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4
#pragma once #pragma once
#endif #endif
@@ -18,7 +20,8 @@ namespace Test {
void FoldedScalar(std::string& inputScalar, std::string& desiredOutput); void FoldedScalar(std::string& inputScalar, std::string& desiredOutput);
void ChompedFoldedScalar(std::string& inputScalar, std::string& desiredOutput); void ChompedFoldedScalar(std::string& inputScalar, std::string& desiredOutput);
void ChompedLiteralScalar(std::string& inputScalar, std::string& desiredOutput); void ChompedLiteralScalar(std::string& inputScalar, std::string& desiredOutput);
void FoldedScalarWithIndent(std::string& inputScalar, std::string& desiredOutput); void FoldedScalarWithIndent(std::string& inputScalar,
std::string& desiredOutput);
void ColonScalar(std::string& inputScalar, std::string& desiredOutput); void ColonScalar(std::string& inputScalar, std::string& desiredOutput);
void QuotedScalar(std::string& inputScalar, std::string& desiredOutput); void QuotedScalar(std::string& inputScalar, std::string& desiredOutput);
void CommaScalar(std::string& inputScalar, std::string& desiredOutput); void CommaScalar(std::string& inputScalar, std::string& desiredOutput);

View File

@@ -2,10 +2,13 @@
#include <string> #include <string>
#define YAML_ASSERT(cond) do { if(!(cond)) return " Assert failed: " #cond; } while(false) #define YAML_ASSERT(cond) \
do { \
if (!(cond)) \
return " Assert failed: " #cond; \
} while (false)
namespace Test namespace Test {
{
struct TEST { struct TEST {
TEST() : ok(false) {} TEST() : ok(false) {}
TEST(bool ok_) : ok(ok_) {} TEST(bool ok_) : ok(ok_) {}
@@ -14,5 +17,4 @@ namespace Test
bool ok; bool ok;
std::string error; std::string error;
}; };
} }

View File

@@ -3,8 +3,7 @@
#include "yaml-cpp/yaml.h" #include "yaml-cpp/yaml.h"
#include <iostream> #include <iostream>
int main() int main() {
{
{ {
// test.yaml // test.yaml
// - foo // - foo
@@ -46,7 +45,8 @@ int main()
other.push_back(root); // &1 [5, ~, two, *1] other.push_back(root); // &1 [5, ~, two, *1]
other[3][0] = 0; // &1 [0, ~, two, *1] # since it's a true alias other[3][0] = 0; // &1 [0, ~, two, *1] # since it's a true alias
other.push_back(Copy(root)); // &1 [0, ~, two, *1, &2 [0, ~, two, *2]] other.push_back(Copy(root)); // &1 [0, ~, two, *1, &2 [0, ~, two, *2]]
other[4][0] = 5; // &1 [0, ~, two, *1, &2 [5, ~, two, *2]] # they're really different other[4][0] = 5; // &1 [0, ~, two, *1, &2 [5, ~, two, *2]] # they're
// really different
} }
{ {
@@ -54,8 +54,10 @@ int main()
node[0] = 1; // [1] # auto-construct a sequence node[0] = 1; // [1] # auto-construct a sequence
node["key"] = 5; // {0: 1, key: 5} # auto-turn it into a map node["key"] = 5; // {0: 1, key: 5} # auto-turn it into a map
node.push_back(10); // error, can't turn a map into a sequence node.push_back(10); // error, can't turn a map into a sequence
node.erase("key"); // {0: 1} # still a map, even if we remove the key that caused the problem node.erase("key"); // {0: 1} # still a map, even if we remove the key that
node = "Hello"; // Hello # assignment overwrites everything, so it's now just a plain scalar // caused the problem
node = "Hello"; // Hello # assignment overwrites everything, so it's now
// just a plain scalar
} }
{ {
@@ -74,18 +76,22 @@ int main()
{ {
YAML::Value node; YAML::Value node;
YAML::Value subnode = node["key"]; // 'subnode' is not instantiated ('node' is still null) YAML::Value subnode =
node["key"]; // 'subnode' is not instantiated ('node' is still null)
subnode = "value"; // {key: value} # now it is subnode = "value"; // {key: value} # now it is
YAML::Value subnode2 = node["key2"]; YAML::Value subnode2 = node["key2"];
node["key3"] = subnode2; // subnode2 is still not instantiated, but node["key3"] is "pseudo" aliased to it node["key3"] = subnode2; // subnode2 is still not instantiated, but
subnode2 = "monkey"; // {key: value, key2: &1 monkey, key3: *1} # bam! it instantiates both // node["key3"] is "pseudo" aliased to it
subnode2 = "monkey"; // {key: value, key2: &1 monkey, key3: *1} # bam! it
// instantiates both
} }
{ {
YAML::Value seq = YAML::Sequence(); YAML::Value seq = YAML::Sequence();
seq[0] = "zero"; // [zero] seq[0] = "zero"; // [zero]
seq[1] = seq[0]; // [&1 zero, *1] seq[1] = seq[0]; // [&1 zero, *1]
seq[0] = seq[1]; // [&1 zero, *1] # no-op (they both alias the same thing, so setting them equal is nothing) seq[0] = seq[1]; // [&1 zero, *1] # no-op (they both alias the same thing,
// so setting them equal is nothing)
Is(seq[0], seq[1]); // true Is(seq[0], seq[1]); // true
seq[1] = "one"; // [&1 one, *1] seq[1] = "one"; // [&1 one, *1]
UnAlias(seq[1]); // [one, one] UnAlias(seq[1]); // [one, one]
@@ -98,9 +104,11 @@ int main()
root.push_back("one"); root.push_back("one");
root.push_back("two"); root.push_back("two");
YAML::Value two = root[2]; YAML::Value two = root[2];
root = "scalar"; // 'two' is still "two", even though 'root' is "scalar" (the sequence effectively no longer exists) root = "scalar"; // 'two' is still "two", even though 'root' is "scalar"
// (the sequence effectively no longer exists)
// Note: in all likelihood, the memory for nodes "zero" and "one" is still allocated. How can it go away? Weak pointers? // Note: in all likelihood, the memory for nodes "zero" and "one" is still
// allocated. How can it go away? Weak pointers?
} }
{ {

View File

@@ -2,8 +2,7 @@
#include "yaml-cpp/eventhandler.h" #include "yaml-cpp/eventhandler.h"
#include <iostream> #include <iostream>
class NullEventHandler: public YAML::EventHandler class NullEventHandler : public YAML::EventHandler {
{
public: public:
typedef YAML::Mark Mark; typedef YAML::Mark Mark;
typedef YAML::anchor_t anchor_t; typedef YAML::anchor_t anchor_t;
@@ -14,15 +13,15 @@ public:
virtual void OnDocumentEnd() {} virtual void OnDocumentEnd() {}
virtual void OnNull(const Mark&, anchor_t) {} virtual void OnNull(const Mark&, anchor_t) {}
virtual void OnAlias(const Mark&, anchor_t) {} virtual void OnAlias(const Mark&, anchor_t) {}
virtual void OnScalar(const Mark&, const std::string&, anchor_t, const std::string&) {} virtual void OnScalar(const Mark&, const std::string&, anchor_t,
const std::string&) {}
virtual void OnSequenceStart(const Mark&, const std::string&, anchor_t) {} virtual void OnSequenceStart(const Mark&, const std::string&, anchor_t) {}
virtual void OnSequenceEnd() {} virtual void OnSequenceEnd() {}
virtual void OnMapStart(const Mark&, const std::string&, anchor_t) {} virtual void OnMapStart(const Mark&, const std::string&, anchor_t) {}
virtual void OnMapEnd() {} virtual void OnMapEnd() {}
}; };
int main() int main() {
{
YAML::Parser parser(std::cin); YAML::Parser parser(std::cin);
NullEventHandler handler; NullEventHandler handler;
parser.HandleNextDocument(handler); parser.HandleNextDocument(handler);

View File

@@ -2,8 +2,7 @@
#include "yaml-cpp/eventhandler.h" #include "yaml-cpp/eventhandler.h"
#include <iostream> #include <iostream>
class NullEventHandler: public YAML::EventHandler class NullEventHandler : public YAML::EventHandler {
{
public: public:
typedef YAML::Mark Mark; typedef YAML::Mark Mark;
typedef YAML::anchor_t anchor_t; typedef YAML::anchor_t anchor_t;
@@ -14,15 +13,15 @@ public:
virtual void OnDocumentEnd() {} virtual void OnDocumentEnd() {}
virtual void OnNull(const Mark&, anchor_t) {} virtual void OnNull(const Mark&, anchor_t) {}
virtual void OnAlias(const Mark&, anchor_t) {} virtual void OnAlias(const Mark&, anchor_t) {}
virtual void OnScalar(const Mark&, const std::string&, anchor_t, const std::string&) {} virtual void OnScalar(const Mark&, const std::string&, anchor_t,
const std::string&) {}
virtual void OnSequenceStart(const Mark&, const std::string&, anchor_t) {} virtual void OnSequenceStart(const Mark&, const std::string&, anchor_t) {}
virtual void OnSequenceEnd() {} virtual void OnSequenceEnd() {}
virtual void OnMapStart(const Mark&, const std::string&, anchor_t) {} virtual void OnMapStart(const Mark&, const std::string&, anchor_t) {}
virtual void OnMapEnd() {} virtual void OnMapEnd() {}
}; };
int main() int main() {
{
std::stringstream stream("---{header: {id: 1"); std::stringstream stream("---{header: {id: 1");
YAML::Parser parser(stream); YAML::Parser parser(stream);
// parser.PrintTokens(std::cout); // parser.PrintTokens(std::cout);