Commit 3355bbb3 authored by Jesse Beder's avatar Jesse Beder
Browse files

Merge clang-format from core

parents 5b889311 9b4db068
#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,45 +14,41 @@ ...@@ -12,45 +14,41 @@
#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)
{} : pContainer(pMap), pPrevKeyNode(pPrevKeyNode) {}
ContainerFrame(void *pMap, void* pPrevKeyNode)
: pContainer(pMap), pPrevKeyNode(pPrevKeyNode)
{}
void *pContainer; void* pContainer;
void *pPrevKeyNode; void* pPrevKeyNode;
bool isMap() const {return pPrevKeyNode != &sequenceMarker;} bool isMap() const { return pPrevKeyNode != &sequenceMarker; }
private: private:
static int sequenceMarker; static int sequenceMarker;
...@@ -61,13 +59,13 @@ namespace YAML ...@@ -61,13 +59,13 @@ namespace YAML
GraphBuilderInterface& m_builder; GraphBuilderInterface& m_builder;
ContainerStack m_containers; ContainerStack m_containers;
AnchorMap m_anchors; AnchorMap m_anchors;
void *m_pRootNode; void* m_pRootNode;
void *m_pKeyNode; void* m_pKeyNode;
void *GetCurrentParent() const; void* GetCurrentParent() const;
void RegisterAnchor(anchor_t anchor, void *pNode); void RegisterAnchor(anchor_t anchor, void* pNode);
void DispositionNode(void *pNode); void DispositionNode(void* pNode);
}; };
} }
#endif // GRAPHBUILDERADAPTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // GRAPHBUILDERADAPTER_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#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 == "!!")
return "tag:yaml.org,2002:"; return "tag:yaml.org,2002:";
return handle; return handle;
} }
return it->second; return it->second;
} }
} }
#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;
}; };
struct Directives { struct Directives {
Directives(); Directives();
const std::string TranslateTagHandle(const std::string& handle) const; const std::string TranslateTagHandle(const std::string& handle) const;
Version version; Version version;
std::map<std::string, std::string> tags; std::map<std::string, std::string> tags;
}; };
} }
#endif // DIRECTIVES_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // DIRECTIVES_H_62B23520_7C8E_11DE_8A39_0800200C9A66
...@@ -5,83 +5,71 @@ ...@@ -5,83 +5,71 @@
#include <sstream> #include <sstream>
namespace { namespace {
std::string ToString(YAML::anchor_t anchor) { std::string ToString(YAML::anchor_t anchor) {
std::stringstream stream; std::stringstream stream;
stream << anchor; stream << anchor;
return stream.str(); return stream.str();
} }
} }
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;
switch(m_stateStack.top()) { switch (m_stateStack.top()) {
case State::WaitingForKey: case State::WaitingForKey:
m_emitter << Key; m_emitter << Key;
m_stateStack.top() = State::WaitingForValue; m_stateStack.top() = State::WaitingForValue;
...@@ -93,13 +81,12 @@ namespace YAML ...@@ -93,13 +81,12 @@ namespace YAML
default: default:
break; break;
} }
} }
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)
m_emitter << Anchor(ToString(anchor)); m_emitter << Anchor(ToString(anchor));
} }
} }
...@@ -5,117 +5,89 @@ ...@@ -5,117 +5,89 @@
#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;
if(m_pState->SetBoolCaseFormat(value, FmtScope::Global)) if (m_pState->SetBoolCaseFormat(value, FmtScope::Global))
ok = true; ok = true;
if(m_pState->SetBoolLengthFormat(value, FmtScope::Global)) if (m_pState->SetBoolLengthFormat(value, FmtScope::Global))
ok = true; ok = true;
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;
if(m_pState->SetMapKeyFormat(value, FmtScope::Global)) if (m_pState->SetMapKeyFormat(value, FmtScope::Global))
ok = true; ok = true;
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;
switch(value) { switch (value) {
case BeginDoc: case BeginDoc:
EmitBeginDoc(); EmitBeginDoc();
break; break;
...@@ -149,152 +121,139 @@ namespace YAML ...@@ -149,152 +121,139 @@ namespace YAML
break; break;
} }
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)
m_pState->SetDoublePrecision(precision.doublePrecision, FmtScope::Local); m_pState->SetDoublePrecision(precision.doublePrecision, FmtScope::Local);
return *this; return *this;
} }
// EmitBeginDoc // EmitBeginDoc
void Emitter::EmitBeginDoc() void Emitter::EmitBeginDoc() {
{ if (!good())
if(!good())
return; return;
if(m_pState->CurGroupType() != GroupType::None) { if (m_pState->CurGroupType() != GroupType::None) {
m_pState->SetError("Unexpected begin document"); m_pState->SetError("Unexpected begin document");
return; return;
} }
if(m_pState->HasAnchor() || m_pState->HasTag()) { if (m_pState->HasAnchor() || m_pState->HasTag()) {
m_pState->SetError("Unexpected begin document"); m_pState->SetError("Unexpected begin document");
return; return;
} }
if(m_stream.col() > 0) if (m_stream.col() > 0)
m_stream << "\n"; m_stream << "\n";
m_stream << "---\n"; m_stream << "---\n";
m_pState->StartedDoc(); m_pState->StartedDoc();
} }
// EmitEndDoc // EmitEndDoc
void Emitter::EmitEndDoc() void Emitter::EmitEndDoc() {
{ if (!good())
if(!good())
return; return;
if(m_pState->CurGroupType() != GroupType::None) { if (m_pState->CurGroupType() != GroupType::None) {
m_pState->SetError("Unexpected begin document"); m_pState->SetError("Unexpected begin document");
return; return;
} }
if(m_pState->HasAnchor() || m_pState->HasTag()) { if (m_pState->HasAnchor() || m_pState->HasTag()) {
m_pState->SetError("Unexpected begin document"); m_pState->SetError("Unexpected begin document");
return; return;
} }
if(m_stream.col() > 0) if (m_stream.col() > 0)
m_stream << "\n"; m_stream << "\n";
m_stream << "...\n"; m_stream << "...\n";
} }
// EmitBeginSeq // EmitBeginSeq
void Emitter::EmitBeginSeq() void Emitter::EmitBeginSeq() {
{ if (!good())
if(!good())
return; return;
PrepareNode(m_pState->NextGroupType(GroupType::Seq)); PrepareNode(m_pState->NextGroupType(GroupType::Seq));
m_pState->StartedGroup(GroupType::Seq); m_pState->StartedGroup(GroupType::Seq);
} }
// EmitEndSeq // EmitEndSeq
void Emitter::EmitEndSeq() void Emitter::EmitEndSeq() {
{ if (!good())
if(!good())
return; return;
if(m_pState->CurGroupChildCount() == 0) if (m_pState->CurGroupChildCount() == 0)
m_pState->ForceFlow(); m_pState->ForceFlow();
if(m_pState->CurGroupFlowType() == FlowType::Flow) { if (m_pState->CurGroupFlowType() == FlowType::Flow) {
if(m_stream.comment()) if (m_stream.comment())
m_stream << "\n"; m_stream << "\n";
m_stream << IndentTo(m_pState->CurIndent()); m_stream << IndentTo(m_pState->CurIndent());
if(m_pState->CurGroupChildCount() == 0) if (m_pState->CurGroupChildCount() == 0)
m_stream << "["; m_stream << "[";
m_stream << "]"; m_stream << "]";
} }
m_pState->EndedGroup(GroupType::Seq); m_pState->EndedGroup(GroupType::Seq);
} }
// EmitBeginMap // EmitBeginMap
void Emitter::EmitBeginMap() void Emitter::EmitBeginMap() {
{ if (!good())
if(!good())
return; return;
PrepareNode(m_pState->NextGroupType(GroupType::Map)); PrepareNode(m_pState->NextGroupType(GroupType::Map));
m_pState->StartedGroup(GroupType::Map); m_pState->StartedGroup(GroupType::Map);
} }
// EmitEndMap // EmitEndMap
void Emitter::EmitEndMap() void Emitter::EmitEndMap() {
{ if (!good())
if(!good())
return; return;
if(m_pState->CurGroupChildCount() == 0) if (m_pState->CurGroupChildCount() == 0)
m_pState->ForceFlow(); m_pState->ForceFlow();
if(m_pState->CurGroupFlowType() == FlowType::Flow) { if (m_pState->CurGroupFlowType() == FlowType::Flow) {
if(m_stream.comment()) if (m_stream.comment())
m_stream << "\n"; m_stream << "\n";
m_stream << IndentTo(m_pState->CurIndent()); m_stream << IndentTo(m_pState->CurIndent());
if(m_pState->CurGroupChildCount() == 0) if (m_pState->CurGroupChildCount() == 0)
m_stream << "{"; m_stream << "{";
m_stream << "}"; m_stream << "}";
} }
m_pState->EndedGroup(GroupType::Map); m_pState->EndedGroup(GroupType::Map);
} }
// EmitNewline // EmitNewline
void Emitter::EmitNewline() void Emitter::EmitNewline() {
{ if (!good())
if(!good())
return; return;
PrepareNode(EmitterNodeType::None); PrepareNode(EmitterNodeType::None);
m_stream << "\n"; m_stream << "\n";
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);
break; break;
...@@ -315,19 +274,18 @@ namespace YAML ...@@ -315,19 +274,18 @@ namespace YAML
assert(false); assert(false);
break; break;
} }
} }
void Emitter::PrepareTopNode(EmitterNodeType::value child) void Emitter::PrepareTopNode(EmitterNodeType::value child) {
{ if (child == EmitterNodeType::None)
if(child == EmitterNodeType::None)
return; return;
if(m_pState->CurGroupChildCount() > 0 && m_stream.col() > 0) { if (m_pState->CurGroupChildCount() > 0 && m_stream.col() > 0) {
if(child != EmitterNodeType::None) if (child != EmitterNodeType::None)
EmitBeginDoc(); EmitBeginDoc();
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
...@@ -340,59 +298,59 @@ namespace YAML ...@@ -340,59 +298,59 @@ namespace YAML
break; break;
case EmitterNodeType::BlockSeq: case EmitterNodeType::BlockSeq:
case EmitterNodeType::BlockMap: case EmitterNodeType::BlockMap:
if(m_pState->HasBegunNode()) if (m_pState->HasBegunNode())
m_stream << "\n"; m_stream << "\n";
break; break;
} }
} }
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()) {
if(m_stream.comment()) if (m_stream.comment())
m_stream << "\n"; m_stream << "\n";
m_stream << IndentTo(lastIndent); m_stream << IndentTo(lastIndent);
if(m_pState->CurGroupChildCount() == 0) if (m_pState->CurGroupChildCount() == 0)
m_stream << "["; m_stream << "[";
else else
m_stream << ","; m_stream << ",";
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
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:
assert(false); assert(false);
break; break;
} }
} }
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();
if(child == EmitterNodeType::None) if (child == EmitterNodeType::None)
return; return;
if(!m_pState->HasBegunContent()) { if (!m_pState->HasBegunContent()) {
if(m_pState->CurGroupChildCount() > 0 || m_stream.comment()) { if (m_pState->CurGroupChildCount() > 0 || m_stream.comment()) {
m_stream << "\n"; m_stream << "\n";
} }
m_stream << IndentTo(curIndent); m_stream << IndentTo(curIndent);
m_stream << "-"; m_stream << "-";
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
...@@ -405,184 +363,186 @@ namespace YAML ...@@ -405,184 +363,186 @@ namespace YAML
m_stream << "\n"; m_stream << "\n";
break; break;
case EmitterNodeType::BlockMap: case EmitterNodeType::BlockMap:
if(m_pState->HasBegunContent() || m_stream.comment()) if (m_pState->HasBegunContent() || m_stream.comment())
m_stream << "\n"; m_stream << "\n";
break; break;
} }
} }
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();
if(m_pState->CurGroupLongKey()) if (m_pState->CurGroupLongKey())
FlowMapPrepareLongKey(child); FlowMapPrepareLongKey(child);
else else
FlowMapPrepareSimpleKey(child); FlowMapPrepareSimpleKey(child);
} else { } else {
if(m_pState->CurGroupLongKey()) if (m_pState->CurGroupLongKey())
FlowMapPrepareLongKeyValue(child); FlowMapPrepareLongKeyValue(child);
else else
FlowMapPrepareSimpleKeyValue(child); FlowMapPrepareSimpleKeyValue(child);
} }
} }
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()) {
if(m_stream.comment()) if (m_stream.comment())
m_stream << "\n"; m_stream << "\n";
m_stream << IndentTo(lastIndent); m_stream << IndentTo(lastIndent);
if(m_pState->CurGroupChildCount() == 0) if (m_pState->CurGroupChildCount() == 0)
m_stream << "{ ?"; m_stream << "{ ?";
else else
m_stream << ", ?"; m_stream << ", ?";
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
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:
assert(false); assert(false);
break; break;
} }
} }
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()) {
if(m_stream.comment()) if (m_stream.comment())
m_stream << "\n"; m_stream << "\n";
m_stream << IndentTo(lastIndent); m_stream << IndentTo(lastIndent);
m_stream << ":"; m_stream << ":";
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
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:
assert(false); assert(false);
break; break;
} }
} }
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()) {
if(m_stream.comment()) if (m_stream.comment())
m_stream << "\n"; m_stream << "\n";
m_stream << IndentTo(lastIndent); m_stream << IndentTo(lastIndent);
if(m_pState->CurGroupChildCount() == 0) if (m_pState->CurGroupChildCount() == 0)
m_stream << "{"; m_stream << "{";
else else
m_stream << ","; m_stream << ",";
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
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:
assert(false); assert(false);
break; break;
} }
} }
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()) {
if(m_stream.comment()) if (m_stream.comment())
m_stream << "\n"; m_stream << "\n";
m_stream << IndentTo(lastIndent); m_stream << IndentTo(lastIndent);
m_stream << ":"; m_stream << ":";
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
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:
assert(false); assert(false);
break; break;
} }
} }
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())
BlockMapPrepareLongKey(child); BlockMapPrepareLongKey(child);
else else
BlockMapPrepareSimpleKey(child); BlockMapPrepareSimpleKey(child);
} else { } else {
if(m_pState->CurGroupLongKey()) if (m_pState->CurGroupLongKey())
BlockMapPrepareLongKeyValue(child); BlockMapPrepareLongKeyValue(child);
else else
BlockMapPrepareSimpleKeyValue(child); BlockMapPrepareSimpleKeyValue(child);
} }
} }
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();
if(child == EmitterNodeType::None) if (child == EmitterNodeType::None)
return; return;
if(!m_pState->HasBegunContent()) { if (!m_pState->HasBegunContent()) {
if(childCount > 0) { if (childCount > 0) {
m_stream << "\n"; m_stream << "\n";
} }
if(m_stream.comment()) { if (m_stream.comment()) {
m_stream << "\n"; m_stream << "\n";
} }
m_stream << IndentTo(curIndent); m_stream << IndentTo(curIndent);
m_stream << "?"; m_stream << "?";
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
...@@ -595,22 +555,21 @@ namespace YAML ...@@ -595,22 +555,21 @@ namespace YAML
case EmitterNodeType::BlockMap: case EmitterNodeType::BlockMap:
break; break;
} }
} }
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)
return; return;
if(!m_pState->HasBegunContent()) { if (!m_pState->HasBegunContent()) {
m_stream << "\n"; m_stream << "\n";
m_stream << IndentTo(curIndent); m_stream << IndentTo(curIndent);
m_stream << ":"; m_stream << ":";
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
...@@ -622,23 +581,22 @@ namespace YAML ...@@ -622,23 +581,22 @@ namespace YAML
SpaceOrIndentTo(true, curIndent + 1); SpaceOrIndentTo(true, curIndent + 1);
break; break;
} }
} }
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();
if(child == EmitterNodeType::None) if (child == EmitterNodeType::None)
return; return;
if(!m_pState->HasBegunNode()) { if (!m_pState->HasBegunNode()) {
if(childCount > 0) { if (childCount > 0) {
m_stream << "\n"; m_stream << "\n";
} }
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
...@@ -651,18 +609,17 @@ namespace YAML ...@@ -651,18 +609,17 @@ namespace YAML
case EmitterNodeType::BlockMap: case EmitterNodeType::BlockMap:
break; break;
} }
} }
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();
if(!m_pState->HasBegunNode()) { if (!m_pState->HasBegunNode()) {
m_stream << ":"; m_stream << ":";
} }
switch(child) { switch (child) {
case EmitterNodeType::None: case EmitterNodeType::None:
break; break;
case EmitterNodeType::Property: case EmitterNodeType::Property:
...@@ -676,23 +633,21 @@ namespace YAML ...@@ -676,23 +633,21 @@ namespace YAML
m_stream << "\n"; m_stream << "\n";
break; break;
} }
} }
// 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)
m_stream << " "; m_stream << " ";
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:
stream << std::dec; stream << std::dec;
break; break;
...@@ -707,30 +662,28 @@ namespace YAML ...@@ -707,30 +662,28 @@ namespace YAML
default: default:
assert(false); assert(false);
} }
} }
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);
PrepareNode(EmitterNodeType::Scalar); PrepareNode(EmitterNodeType::Scalar);
switch(strFormat) { switch (strFormat) {
case StringFormat::Plain: case StringFormat::Plain:
m_stream << str; m_stream << str;
break; break;
...@@ -741,69 +694,81 @@ namespace YAML ...@@ -741,69 +694,81 @@ 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;
} }
StartedScalar(); StartedScalar();
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;
PrepareNode(EmitterNodeType::Scalar); PrepareNode(EmitterNodeType::Scalar);
const char *name = ComputeFullBoolName(b); const char* name = ComputeFullBoolName(b);
if(m_pState->GetBoolLengthFormat() == ShortBool) if (m_pState->GetBoolLengthFormat() == ShortBool)
m_stream << name[0]; m_stream << name[0];
else else
m_stream << name; m_stream << name;
...@@ -811,11 +776,10 @@ namespace YAML ...@@ -811,11 +776,10 @@ namespace YAML
StartedScalar(); StartedScalar();
return *this; return *this;
} }
Emitter& Emitter::Write(char ch) Emitter& Emitter::Write(char ch) {
{ if (!good())
if(!good())
return *this; return *this;
PrepareNode(EmitterNodeType::Scalar); PrepareNode(EmitterNodeType::Scalar);
...@@ -823,21 +787,20 @@ namespace YAML ...@@ -823,21 +787,20 @@ namespace YAML
StartedScalar(); StartedScalar();
return *this; return *this;
} }
Emitter& Emitter::Write(const _Alias& alias) Emitter& Emitter::Write(const _Alias& alias) {
{ if (!good())
if(!good())
return *this; return *this;
if(m_pState->HasAnchor() || m_pState->HasTag()) { if (m_pState->HasAnchor() || m_pState->HasTag()) {
m_pState->SetError(ErrorMsg::INVALID_ALIAS); m_pState->SetError(ErrorMsg::INVALID_ALIAS);
return *this; return *this;
} }
PrepareNode(EmitterNodeType::Scalar); PrepareNode(EmitterNodeType::Scalar);
if(!Utils::WriteAlias(m_stream, alias.content)) { if (!Utils::WriteAlias(m_stream, alias.content)) {
m_pState->SetError(ErrorMsg::INVALID_ALIAS); m_pState->SetError(ErrorMsg::INVALID_ALIAS);
return *this; return *this;
} }
...@@ -845,21 +808,20 @@ namespace YAML ...@@ -845,21 +808,20 @@ namespace YAML
StartedScalar(); StartedScalar();
return *this; return *this;
} }
Emitter& Emitter::Write(const _Anchor& anchor) Emitter& Emitter::Write(const _Anchor& anchor) {
{ if (!good())
if(!good())
return *this; return *this;
if(m_pState->HasAnchor()) { if (m_pState->HasAnchor()) {
m_pState->SetError(ErrorMsg::INVALID_ANCHOR); m_pState->SetError(ErrorMsg::INVALID_ANCHOR);
return *this; return *this;
} }
PrepareNode(EmitterNodeType::Property); PrepareNode(EmitterNodeType::Property);
if(!Utils::WriteAnchor(m_stream, anchor.content)) { if (!Utils::WriteAnchor(m_stream, anchor.content)) {
m_pState->SetError(ErrorMsg::INVALID_ANCHOR); m_pState->SetError(ErrorMsg::INVALID_ANCHOR);
return *this; return *this;
} }
...@@ -867,14 +829,13 @@ namespace YAML ...@@ -867,14 +829,13 @@ namespace YAML
m_pState->SetAnchor(); m_pState->SetAnchor();
return *this; return *this;
} }
Emitter& Emitter::Write(const _Tag& tag) Emitter& Emitter::Write(const _Tag& tag) {
{ if (!good())
if(!good())
return *this; return *this;
if(m_pState->HasTag()) { if (m_pState->HasTag()) {
m_pState->SetError(ErrorMsg::INVALID_TAG); m_pState->SetError(ErrorMsg::INVALID_TAG);
return *this; return *this;
} }
...@@ -882,14 +843,14 @@ namespace YAML ...@@ -882,14 +843,14 @@ namespace YAML
PrepareNode(EmitterNodeType::Property); PrepareNode(EmitterNodeType::Property);
bool success = false; bool success = false;
if(tag.type == _Tag::Type::Verbatim) if (tag.type == _Tag::Type::Verbatim)
success = Utils::WriteTag(m_stream, tag.content, true); success = Utils::WriteTag(m_stream, tag.content, true);
else if(tag.type == _Tag::Type::PrimaryHandle) else if (tag.type == _Tag::Type::PrimaryHandle)
success = Utils::WriteTag(m_stream, tag.content, false); success = Utils::WriteTag(m_stream, tag.content, false);
else else
success = Utils::WriteTagWithPrefix(m_stream, tag.prefix, tag.content); success = Utils::WriteTagWithPrefix(m_stream, tag.prefix, tag.content);
if(!success) { if (!success) {
m_pState->SetError(ErrorMsg::INVALID_TAG); m_pState->SetError(ErrorMsg::INVALID_TAG);
return *this; return *this;
} }
...@@ -897,32 +858,28 @@ namespace YAML ...@@ -897,32 +858,28 @@ namespace YAML
m_pState->SetTag(); m_pState->SetTag();
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;
PrepareNode(EmitterNodeType::None); PrepareNode(EmitterNodeType::None);
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;
PrepareNode(EmitterNodeType::Scalar); PrepareNode(EmitterNodeType::Scalar);
...@@ -932,13 +889,12 @@ namespace YAML ...@@ -932,13 +889,12 @@ namespace YAML
StartedScalar(); StartedScalar();
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())
return *this; return *this;
PrepareNode(EmitterNodeType::Scalar); PrepareNode(EmitterNodeType::Scalar);
...@@ -946,6 +902,5 @@ namespace YAML ...@@ -946,6 +902,5 @@ namespace YAML
StartedScalar(); StartedScalar();
return *this; return *this;
}
} }
}
...@@ -2,10 +2,14 @@ ...@@ -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);
...@@ -21,17 +25,14 @@ namespace YAML ...@@ -21,17 +25,14 @@ namespace YAML
m_mapKeyFmt.set(Auto); m_mapKeyFmt.set(Auto);
m_floatPrecision.set(std::numeric_limits<float>::digits10 + 1); m_floatPrecision.set(std::numeric_limits<float>::digits10 + 1);
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);
...@@ -41,66 +42,54 @@ namespace YAML ...@@ -41,66 +42,54 @@ namespace YAML
SetFlowType(GroupType::Seq, value, FmtScope::Local); SetFlowType(GroupType::Seq, value, FmtScope::Local);
SetFlowType(GroupType::Map, value, FmtScope::Local); SetFlowType(GroupType::Map, value, FmtScope::Local);
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;
assert(m_groups.top().type == GroupType::Map); assert(m_groups.top().type == GroupType::Map);
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;
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 {
m_groups.top().childCount++; m_groups.top().childCount++;
if(m_groups.top().childCount % 2 == 0) if (m_groups.top().childCount % 2 == 0)
m_groups.top().longKey = false; m_groups.top().longKey = false;
} }
m_hasAnchor = false; m_hasAnchor = false;
m_hasTag = false; m_hasTag = false;
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;
else else
return EmitterNodeType::FlowSeq; return EmitterNodeType::FlowSeq;
} else { } else {
if(GetFlowType(type) == Block) if (GetFlowType(type) == Block)
return EmitterNodeType::BlockMap; return EmitterNodeType::BlockMap;
else else
return EmitterNodeType::FlowMap; return EmitterNodeType::FlowMap;
...@@ -109,30 +98,26 @@ namespace YAML ...@@ -109,30 +98,26 @@ namespace YAML
// can't happen // can't happen
assert(false); assert(false);
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);
...@@ -144,19 +129,18 @@ namespace YAML ...@@ -144,19 +129,18 @@ namespace YAML
pGroup->modifiedSettings = m_modifiedSettings; pGroup->modifiedSettings = m_modifiedSettings;
// set up group // set up group
if(GetFlowType(type) == Block) if (GetFlowType(type) == Block)
pGroup->flowType = FlowType::Block; pGroup->flowType = FlowType::Block;
else else
pGroup->flowType = FlowType::Flow; pGroup->flowType = FlowType::Flow;
pGroup->indent = GetIndent(); pGroup->indent = GetIndent();
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);
else else
return SetError(ErrorMsg::UNEXPECTED_END_MAP); return SetError(ErrorMsg::UNEXPECTED_END_MAP);
...@@ -165,7 +149,7 @@ namespace YAML ...@@ -165,7 +149,7 @@ namespace YAML
// get rid of the current group // get rid of the current group
{ {
std::auto_ptr<Group> pFinishedGroup = m_groups.pop(); std::auto_ptr<Group> pFinishedGroup = m_groups.pop();
if(pFinishedGroup->type != type) if (pFinishedGroup->type != type)
return SetError(ErrorMsg::UNMATCHED_GROUP_TAG); return SetError(ErrorMsg::UNMATCHED_GROUP_TAG);
} }
...@@ -179,57 +163,47 @@ namespace YAML ...@@ -179,57 +163,47 @@ namespace YAML
m_globalModifiedSettings.restore(); m_globalModifiedSettings.restore();
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:
_Set(m_charset, value, scope); _Set(m_charset, value, scope);
...@@ -237,11 +211,10 @@ namespace YAML ...@@ -237,11 +211,10 @@ namespace YAML
default: default:
return false; return false;
} }
} }
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:
case DoubleQuoted: case DoubleQuoted:
...@@ -251,11 +224,10 @@ namespace YAML ...@@ -251,11 +224,10 @@ namespace YAML
default: default:
return false; return false;
} }
} }
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:
case YesNoBool: case YesNoBool:
...@@ -264,11 +236,11 @@ namespace YAML ...@@ -264,11 +236,11 @@ namespace YAML
default: default:
return false; return false;
} }
} }
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:
_Set(m_boolLengthFmt, value, scope); _Set(m_boolLengthFmt, value, scope);
...@@ -276,11 +248,11 @@ namespace YAML ...@@ -276,11 +248,11 @@ namespace YAML
default: default:
return false; return false;
} }
} }
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:
case CamelCase: case CamelCase:
...@@ -289,11 +261,10 @@ namespace YAML ...@@ -289,11 +261,10 @@ namespace YAML
default: default:
return false; return false;
} }
} }
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:
case Oct: case Oct:
...@@ -302,38 +273,35 @@ namespace YAML ...@@ -302,38 +273,35 @@ namespace YAML
default: default:
return false; return false;
} }
} }
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;
_Set(m_indent, value, scope); _Set(m_indent, value, scope);
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;
_Set(m_preCommentIndent, value, scope); _Set(m_preCommentIndent, value, scope);
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;
_Set(m_postCommentIndent, value, scope); _Set(m_postCommentIndent, value, scope);
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:
_Set(groupType == GroupType::Seq ? m_seqFmt : m_mapFmt, value, scope); _Set(groupType == GroupType::Seq ? m_seqFmt : m_mapFmt, value, scope);
...@@ -341,21 +309,19 @@ namespace YAML ...@@ -341,21 +309,19 @@ namespace YAML
default: default:
return false; return false;
} }
} }
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;
// otherwise, go with what's asked of us // otherwise, go with what's asked of us
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:
_Set(m_mapKeyFmt, value, scope); _Set(m_mapKeyFmt, value, scope);
...@@ -363,22 +329,19 @@ namespace YAML ...@@ -363,22 +329,19 @@ namespace YAML
default: default:
return false; return false;
} }
} }
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;
}
} }
}
#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 @@ ...@@ -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 ...@@ -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 ...@@ -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 ...@@ -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 ...@@ -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;
...@@ -144,13 +167,13 @@ namespace YAML ...@@ -144,13 +167,13 @@ namespace YAML
SettingChanges modifiedSettings; SettingChanges modifiedSettings;
EmitterNodeType::value NodeType() const { EmitterNodeType::value NodeType() const {
if(type == GroupType::Seq) { if (type == GroupType::Seq) {
if(flowType == FlowType::Flow) if (flowType == FlowType::Flow)
return EmitterNodeType::FlowSeq; return EmitterNodeType::FlowSeq;
else else
return EmitterNodeType::BlockSeq; return EmitterNodeType::BlockSeq;
} else { } else {
if(flowType == FlowType::Flow) if (flowType == FlowType::Flow)
return EmitterNodeType::FlowMap; return EmitterNodeType::FlowMap;
else else
return EmitterNodeType::BlockMap; return EmitterNodeType::BlockMap;
...@@ -168,23 +191,24 @@ namespace YAML ...@@ -168,23 +191,24 @@ namespace YAML
bool m_hasTag; bool m_hasTag;
bool m_hasNonContent; bool m_hasNonContent;
std::size_t m_docCount; std::size_t m_docCount;
}; };
template <typename T> template <typename T>
void EmitterState::_Set(Setting<T>& fmt, T value, FmtScope::value scope) { void EmitterState::_Set(Setting<T>& fmt, T value, FmtScope::value scope) {
switch(scope) { switch (scope) {
case FmtScope::Local: case FmtScope::Local:
m_modifiedSettings.push(fmt.set(value)); m_modifiedSettings.push(fmt.set(value));
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:
assert(false); assert(false);
} }
} }
} }
#endif // EMITTERSTATE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // EMITTERSTATE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
...@@ -7,19 +7,25 @@ ...@@ -7,19 +7,25 @@
#include <sstream> #include <sstream>
#include <iomanip> #include <iomanip>
namespace YAML namespace YAML {
{ namespace Utils {
namespace Utils namespace {
{ enum {
namespace { 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;
...@@ -43,14 +49,22 @@ namespace YAML ...@@ -43,14 +49,22 @@ namespace YAML
return false; return false;
return true; return true;
} }
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;
...@@ -59,13 +73,13 @@ namespace YAML ...@@ -59,13 +73,13 @@ namespace YAML
default: default:
return -1; return -1;
} }
} }
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;
...@@ -105,9 +119,9 @@ namespace YAML ...@@ -105,9 +119,9 @@ namespace YAML
else if (codePoint >= 0xFDD0 && codePoint <= 0xFDEF) else if (codePoint >= 0xFDD0 && codePoint <= 0xFDEF)
codePoint = REPLACEMENT_CHARACTER; codePoint = REPLACEMENT_CHARACTER;
return true; return true;
} }
void WriteCodePoint(ostream_wrapper& out, int codePoint) { void WriteCodePoint(ostream_wrapper& out, int codePoint) {
if (codePoint < 0 || codePoint > 0x10FFFF) { if (codePoint < 0 || codePoint > 0x10FFFF) {
codePoint = REPLACEMENT_CHARACTER; codePoint = REPLACEMENT_CHARACTER;
} }
...@@ -126,74 +140,75 @@ namespace YAML ...@@ -126,74 +140,75 @@ namespace YAML
<< static_cast<char>(0x80 | ((codePoint >> 6) & 0x3F)) << static_cast<char>(0x80 | ((codePoint >> 6) & 0x3F))
<< static_cast<char>(0x80 | (codePoint & 0x3F)); << static_cast<char>(0x80 | (codePoint & 0x3F));
} }
} }
bool IsValidPlainScalar(const std::string& str, FlowType::value flowType, bool allowOnlyAscii) { bool IsValidPlainScalar(const std::string& str, FlowType::value flowType,
if(str.empty()) bool allowOnlyAscii) {
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()
if(!start.Matches(str)) : Exp::PlainScalar());
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
if(!str.empty() && *str.rbegin() == ' ') // plain scalar)
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))
return false; return false;
if(allowOnlyAscii && (0x80 <= static_cast<unsigned char>(buffer[0]))) if (allowOnlyAscii && (0x80 <= static_cast<unsigned char>(buffer[0])))
return false; return false;
++buffer; ++buffer;
} }
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])))
return false; return false;
if(str[i] == '\n') if (str[i] == '\n')
return false; return false;
} }
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;
// 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])))
return false; return false;
} }
return true; return true;
} }
void WriteDoubleQuoteEscapeSequence(ostream_wrapper& out, int codePoint) { void WriteDoubleQuoteEscapeSequence(ostream_wrapper& out, int codePoint) {
static const char hexDigits[] = "0123456789abcdef"; static const char hexDigits[] = "0123456789abcdef";
out << "\\"; out << "\\";
int digits = 8; int digits = 8;
if(codePoint < 0xFF) { if (codePoint < 0xFF) {
out << "x"; out << "x";
digits = 2; digits = 2;
} else if(codePoint < 0xFFFF) { } else if (codePoint < 0xFFFF) {
out << "u"; out << "u";
digits = 4; digits = 4;
} else { } else {
...@@ -204,38 +219,38 @@ namespace YAML ...@@ -204,38 +219,38 @@ namespace YAML
// Write digits into the escape sequence // Write digits into the escape sequence
for (; digits > 0; --digits) for (; digits > 0; --digits)
out << hexDigits[(codePoint >> (4 * (digits - 1))) & 0xF]; out << hexDigits[(codePoint >> (4 * (digits - 1))) & 0xF];
} }
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;
WriteCodePoint(out, codePoint); WriteCodePoint(out, codePoint);
} }
return true; return true;
} }
} }
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,
switch(strFormat) { FlowType::value flowType,
bool escapeNonAscii) {
switch (strFormat) {
case Auto: case Auto:
if(IsValidPlainScalar(str, flowType, escapeNonAscii)) if (IsValidPlainScalar(str, flowType, escapeNonAscii))
return StringFormat::Plain; return StringFormat::Plain;
return StringFormat::DoubleQuoted; return StringFormat::DoubleQuoted;
case SingleQuoted: case SingleQuoted:
if(IsValidSingleQuotedScalar(str, escapeNonAscii)) if (IsValidSingleQuotedScalar(str, escapeNonAscii))
return StringFormat::SingleQuoted; return StringFormat::SingleQuoted;
return StringFormat::DoubleQuoted; return StringFormat::DoubleQuoted;
case DoubleQuoted: case DoubleQuoted:
return StringFormat::DoubleQuoted; return StringFormat::DoubleQuoted;
case Literal: case Literal:
if(IsValidLiteralScalar(str, flowType, escapeNonAscii)) if (IsValidLiteralScalar(str, flowType, escapeNonAscii))
return StringFormat::Literal; return StringFormat::Literal;
return StringFormat::DoubleQuoted; return StringFormat::DoubleQuoted;
default: default:
...@@ -243,18 +258,16 @@ namespace YAML ...@@ -243,18 +258,16 @@ 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 << "''";
...@@ -263,27 +276,40 @@ namespace YAML ...@@ -263,27 +276,40 @@ namespace YAML
} }
out << "'"; out << "'";
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) {
{ case '\"':
switch(codePoint) { out << "\\\"";
case '\"': out << "\\\""; break; break;
case '\\': out << "\\\\"; break; case '\\':
case '\n': out << "\\n"; break; out << "\\\\";
case '\t': out << "\\t"; break; break;
case '\r': out << "\\r"; break; case '\n':
case '\b': out << "\\b"; break; 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);
...@@ -293,36 +319,33 @@ namespace YAML ...@@ -293,36 +319,33 @@ namespace YAML
} }
out << "\""; out << "\"";
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
WriteCodePoint(out, codePoint); WriteCodePoint(out, codePoint);
} }
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 == ' ')
out << "\"" << ch << "\""; out << "\"" << ch << "\"";
else if(ch == '\t') else if (ch == '\t')
out << "\"\\t\""; out << "\"\\t\"";
else if(ch == '\n') else if (ch == '\n')
out << "\"\\n\""; out << "\"\\n\"";
else if(ch == '\b') else if (ch == '\b')
out << "\"\\b\""; out << "\"\\b\"";
else { else {
out << "\""; out << "\"";
...@@ -330,51 +353,47 @@ namespace YAML ...@@ -330,51 +353,47 @@ namespace YAML
out << "\""; out << "\"";
} }
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') {
{ out << "\n" << IndentTo(curIndent) << "#"
if(codePoint == '\n') { << Indentation(postCommentIndent);
out << "\n" << IndentTo(curIndent) << "#" << Indentation(postCommentIndent);
out.set_comment(); out.set_comment();
} else { } else {
WriteCodePoint(out, codePoint); WriteCodePoint(out, codePoint);
} }
} }
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();
while(buffer) { while (buffer) {
int n = reValid.Match(buffer); int n = reValid.Match(buffer);
if(n <= 0) if (n <= 0)
return false; return false;
while(--n >= 0) { while (--n >= 0) {
out << buffer[0]; out << buffer[0];
++buffer; ++buffer;
} }
...@@ -382,18 +401,18 @@ namespace YAML ...@@ -382,18 +401,18 @@ namespace YAML
if (verbatim) if (verbatim)
out << ">"; out << ">";
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) {
int n = Exp::URI().Match(prefixBuffer); int n = Exp::URI().Match(prefixBuffer);
if(n <= 0) if (n <= 0)
return false; return false;
while(--n >= 0) { while (--n >= 0) {
out << prefixBuffer[0]; out << prefixBuffer[0];
++prefixBuffer; ++prefixBuffer;
} }
...@@ -401,24 +420,23 @@ namespace YAML ...@@ -401,24 +420,23 @@ namespace YAML
out << "!"; out << "!";
StringCharSource tagBuffer(tag.c_str(), tag.size()); StringCharSource tagBuffer(tag.c_str(), tag.size());
while(tagBuffer) { while (tagBuffer) {
int n = Exp::Tag().Match(tagBuffer); int n = Exp::Tag().Match(tagBuffer);
if(n <= 0) if (n <= 0)
return false; return false;
while(--n >= 0) { while (--n >= 0) {
out << tagBuffer[0]; out << tagBuffer[0];
++tagBuffer; ++tagBuffer;
} }
} }
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;
}
}
} }
}
}
#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 {
struct StringFormat { enum value { Plain, SingleQuoted, DoubleQuoted, Literal }; }; enum value {
Plain,
namespace Utils SingleQuoted,
{ DoubleQuoted,
StringFormat::value ComputeStringFormat(const std::string& str, EMITTER_MANIP strFormat, FlowType::value flowType, bool escapeNonAscii); Literal
};
bool WriteSingleQuotedString(ostream_wrapper& out, const std::string& str); };
bool WriteDoubleQuotedString(ostream_wrapper& out, const std::string& str, bool escapeNonAscii);
bool WriteLiteralString(ostream_wrapper& out, const std::string& str, int indent); namespace Utils {
bool WriteChar(ostream_wrapper& out, char ch); StringFormat::value ComputeStringFormat(const std::string& str,
bool WriteComment(ostream_wrapper& out, const std::string& str, int postCommentIndent); EMITTER_MANIP strFormat,
bool WriteAlias(ostream_wrapper& out, const std::string& str); FlowType::value flowType,
bool WriteAnchor(ostream_wrapper& out, const std::string& str); bool escapeNonAscii);
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 WriteSingleQuotedString(ostream_wrapper& out, const std::string& str);
bool WriteBinary(ostream_wrapper& out, const Binary& binary); bool WriteDoubleQuotedString(ostream_wrapper& out, const std::string& str,
} bool escapeNonAscii);
bool WriteLiteralString(ostream_wrapper& out, const std::string& str,
int indent);
bool WriteChar(ostream_wrapper& out, char ch);
bool WriteComment(ostream_wrapper& out, const std::string& str,
int postCommentIndent);
bool WriteAlias(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 WriteTagWithPrefix(ostream_wrapper& out, const std::string& prefix,
const std::string& tag);
bool WriteBinary(ostream_wrapper& out, const Binary& binary);
}
} }
#endif // EMITTERUTILS_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // EMITTERUTILS_H_62B23520_7C8E_11DE_8A39_0800200C9A66
...@@ -2,21 +2,18 @@ ...@@ -2,21 +2,18 @@
#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];
int digit = 0; int digit = 0;
if('a' <= ch && ch <= 'f') if ('a' <= ch && ch <= 'f')
digit = ch - 'a' + 10; digit = ch - 'a' + 10;
else if('A' <= ch && ch <= 'F') else if ('A' <= ch && ch <= 'F')
digit = ch - 'A' + 10; digit = ch - 'A' + 10;
else if('0' <= ch && ch <= '9') else if ('0' <= ch && ch <= '9')
digit = ch - '0'; digit = ch - '0';
else else
throw ParserException(mark, ErrorMsg::INVALID_HEX); throw ParserException(mark, ErrorMsg::INVALID_HEX);
...@@ -25,51 +22,49 @@ namespace YAML ...@@ -25,51 +22,49 @@ 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
// . Throws if it's not actually hex. // the result.
std::string Escape(Stream& in, int codeLength) // . Throws if it's not actually hex.
{ 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++)
str += in.get(); str += in.get();
// get the value // get the value
unsigned value = ParseHex(str, in.mark()); unsigned value = ParseHex(str, in.mark());
// legal unicode? // legal unicode?
if((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) { if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) {
std::stringstream msg; std::stringstream msg;
msg << ErrorMsg::INVALID_UNICODE << value; msg << ErrorMsg::INVALID_UNICODE << value;
throw ParserException(in.mark(), msg.str()); throw ParserException(in.mark(), msg.str());
} }
// now break it up into chars // now break it up into chars
if(value <= 0x7F) if (value <= 0x7F)
return Str(value); return Str(value);
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
// and returns the result. // quote)
// . Throws if it's an unknown escape character. // and returns the result.
std::string Escape(Stream& in) // . Throws if it's an unknown escape character.
{ std::string Escape(Stream& in) {
// eat slash // eat slash
char escape = in.get(); char escape = in.get();
...@@ -77,37 +72,59 @@ namespace YAML ...@@ -77,37 +72,59 @@ namespace YAML
char ch = in.get(); char ch = in.get();
// first do single quote, since it's easier // first do single quote, since it's easier
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
switch(ch) { // one!)
case '0': return std::string(1, '\x00'); switch (ch) {
case 'a': return "\x07"; case '0':
case 'b': return "\x08"; return std::string(1, '\x00');
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;
throw ParserException(in.mark(), std::string(ErrorMsg::INVALID_ESCAPE) + ch); throw ParserException(in.mark(), std::string(ErrorMsg::INVALID_ESCAPE) + ch);
} }
} }
} }
#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
// Here we store a bunch of expressions for matching different parts of the file. // 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(' ');
return e; return e;
} }
inline const RegEx& Tab() { inline const RegEx& Tab() {
static const RegEx e = RegEx('\t'); static const RegEx e = RegEx('\t');
return e; return e;
} }
inline const RegEx& Blank() { inline const RegEx& Blank() {
static const RegEx e = Space() || Tab(); static const RegEx e = Space() || Tab();
return e; return e;
} }
inline const RegEx& Break() { inline const RegEx& Break() {
static const RegEx e = RegEx('\n') || RegEx("\r\n"); static const RegEx e = RegEx('\n') || RegEx("\r\n");
return e; return e;
} }
inline const RegEx& BlankOrBreak() { inline const RegEx& BlankOrBreak() {
static const RegEx e = Blank() || Break(); static const RegEx e = Blank() || Break();
return e; return e;
} }
inline const RegEx& Digit() { inline const RegEx& Digit() {
static const RegEx e = RegEx('0', '9'); static const RegEx e = RegEx('0', '9');
return e; return e;
} }
inline const RegEx& Alpha() { inline const RegEx& Alpha() {
static const RegEx e = RegEx('a', 'z') || RegEx('A', 'Z'); static const RegEx e = RegEx('a', 'z') || RegEx('A', 'Z');
return e; return e;
} }
inline const RegEx& AlphaNumeric() { inline const RegEx& AlphaNumeric() {
static const RegEx e = Alpha() || Digit(); static const RegEx e = Alpha() || Digit();
return e; return e;
} }
inline const RegEx& Word() { inline const RegEx& Word() {
static const RegEx e = AlphaNumeric() || RegEx('-'); static const RegEx e = AlphaNumeric() || RegEx('-');
return e; return e;
} }
inline const RegEx& Hex() { inline const RegEx& Hex() {
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.
inline const RegEx& NotPrintable() { // 5.1)
static const RegEx e = RegEx(0) || inline const RegEx& NotPrintable() {
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')));
return e; return e;
} }
inline const RegEx& Utf8_ByteOrderMark() { inline const RegEx& Utf8_ByteOrderMark() {
static const RegEx e = RegEx("\xEF\xBB\xBF"); static const RegEx e = RegEx("\xEF\xBB\xBF");
return e; return e;
} }
// actual tags // actual tags
inline const RegEx& DocStart() { inline const RegEx& DocStart() {
static const RegEx e = RegEx("---") + (BlankOrBreak() || RegEx()); static const RegEx e = RegEx("---") + (BlankOrBreak() || RegEx());
return e; return e;
} }
inline const RegEx& DocEnd() { inline const RegEx& DocEnd() {
static const RegEx e = RegEx("...") + (BlankOrBreak() || RegEx()); static const RegEx e = RegEx("...") + (BlankOrBreak() || RegEx());
return e; return e;
} }
inline const RegEx& DocIndicator() { inline const RegEx& DocIndicator() {
static const RegEx e = DocStart() || DocEnd(); static const RegEx e = DocStart() || DocEnd();
return e; return e;
} }
inline const RegEx& BlockEntry() { inline const RegEx& BlockEntry() {
static const RegEx e = RegEx('-') + (BlankOrBreak() || RegEx()); static const RegEx e = RegEx('-') + (BlankOrBreak() || RegEx());
return e; return e;
} }
inline const RegEx& Key() { inline const RegEx& Key() {
static const RegEx e = RegEx('?') + BlankOrBreak(); static const RegEx e = RegEx('?') + BlankOrBreak();
return e; return e;
} }
inline const RegEx& KeyInFlow() { inline const RegEx& KeyInFlow() {
static const RegEx e = RegEx('?') + BlankOrBreak(); static const RegEx e = RegEx('?') + BlankOrBreak();
return e; return e;
} }
inline const RegEx& Value() { inline const RegEx& Value() {
static const RegEx e = RegEx(':') + (BlankOrBreak() || RegEx()); static const RegEx e = RegEx(':') + (BlankOrBreak() || RegEx());
return e; return e;
} }
inline const RegEx& ValueInFlow() { inline const RegEx& ValueInFlow() {
static const RegEx e = RegEx(':') + (BlankOrBreak() || RegEx(",}", REGEX_OR)); static const RegEx e = RegEx(':') + (BlankOrBreak() || RegEx(",}", REGEX_OR));
return e; return e;
} }
inline const RegEx& ValueInJSONFlow() { inline const RegEx& ValueInJSONFlow() {
static const RegEx e = RegEx(':'); static const RegEx e = RegEx(':');
return e; return e;
} }
inline const RegEx Comment() { inline const RegEx Comment() {
static const RegEx e = RegEx('#'); static const RegEx e = RegEx('#');
return e; return e;
} }
inline const RegEx& Anchor() { inline const RegEx& Anchor() {
static const RegEx e = !(RegEx("[]{},", REGEX_OR) || BlankOrBreak()); static const RegEx e = !(RegEx("[]{},", REGEX_OR) || BlankOrBreak());
return e; return e;
} }
inline const RegEx& AnchorEnd() { inline const RegEx& AnchorEnd() {
static const RegEx e = RegEx("?:,]}%@`", REGEX_OR) || BlankOrBreak(); static const RegEx e = RegEx("?:,]}%@`", REGEX_OR) || BlankOrBreak();
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;
} }
// Plain scalar rules: // Plain scalar rules:
// . 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
inline const RegEx& PlainScalar() { // space.
static const RegEx e = !(BlankOrBreak() || RegEx(",[]{}#&*!|>\'\"%@`", REGEX_OR) || (RegEx("-?:", REGEX_OR) + (BlankOrBreak() || RegEx()))); inline const RegEx& PlainScalar() {
return e; static const RegEx e =
} !(BlankOrBreak() || RegEx(",[]{}#&*!|>\'\"%@`", REGEX_OR) ||
inline const RegEx& PlainScalarInFlow() { (RegEx("-?:", REGEX_OR) + (BlankOrBreak() || RegEx())));
static const RegEx e = !(BlankOrBreak() || RegEx("?,[]{}#&*!|>\'\"%@`", REGEX_OR) || (RegEx("-:", REGEX_OR) + Blank())); return e;
return e; }
} inline const RegEx& PlainScalarInFlow() {
inline const RegEx& EndScalar() { static const RegEx e =
!(BlankOrBreak() || RegEx("?,[]{}#&*!|>\'\"%@`", REGEX_OR) ||
(RegEx("-:", REGEX_OR) + Blank()));
return e;
}
inline const RegEx& EndScalar() {
static const RegEx e = RegEx(':') + (BlankOrBreak() || RegEx()); static const RegEx e = RegEx(':') + (BlankOrBreak() || RegEx());
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;
} }
inline const RegEx& EscSingleQuote() { inline const RegEx& EscSingleQuote() {
static const RegEx e = RegEx("\'\'"); static const RegEx e = RegEx("\'\'");
return e; return e;
} }
inline const RegEx& EscBreak() { inline const RegEx& EscBreak() {
static const RegEx e = RegEx('\\') + Break(); static const RegEx e = RegEx('\\') + Break();
return e; return e;
} }
inline const RegEx& ChompIndicator() { inline const RegEx& ChompIndicator() {
static const RegEx e = RegEx("+-", REGEX_OR); static const RegEx e = RegEx("+-", REGEX_OR);
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;
} }
// and some functions // and some functions
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 = ']'; const char FlowMapStart = '{';
const char FlowMapStart = '{'; const char FlowMapEnd = '}';
const char FlowMapEnd = '}'; const char FlowEntry = ',';
const char FlowEntry = ','; const char Alias = '*';
const char Alias = '*'; const char Anchor = '&';
const char Anchor = '&'; const char Tag = '!';
const char Tag = '!'; const char LiteralScalar = '|';
const char LiteralScalar = '|'; const char FoldedScalar = '>';
const char FoldedScalar = '>'; const char VerbatimTagStart = '<';
const char VerbatimTagStart = '<'; const char VerbatimTagEnd = '>';
const char VerbatimTagEnd = '>'; }
}
} }
#endif // EXP_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // EXP_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#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,
for(unsigned i=0;i<indent.n;i++) const Indentation& indent) {
for (unsigned i = 0; i < indent.n; i++)
out << ' '; out << ' ';
return out; return out;
} }
struct IndentTo { struct IndentTo {
IndentTo(unsigned n_): n(n_) {} IndentTo(unsigned n_) : n(n_) {}
unsigned n; unsigned n;
}; };
inline ostream_wrapper& operator << (ostream_wrapper& out, const IndentTo& indent) { inline ostream_wrapper& operator<<(ostream_wrapper& out,
while(out.col() < indent.n) const IndentTo& indent) {
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
#include "yaml-cpp/null.h" #include "yaml-cpp/null.h"
namespace YAML namespace YAML {
{ _Null Null;
_Null Null;
} }
...@@ -9,133 +9,119 @@ ...@@ -9,133 +9,119 @@
#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);
} }
// HandleNextDocument // HandleNextDocument
// . 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;
ParseDirectives(); ParseDirectives();
if(m_pScanner->empty()) if (m_pScanner->empty())
return false; return false;
SingleDocParser sdp(*m_pScanner, *m_pDirectives); SingleDocParser sdp(*m_pScanner, *m_pDirectives);
sdp.HandleDocument(eventHandler); sdp.HandleDocument(eventHandler);
return true; return true;
} }
// 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) {
if(m_pScanner->empty()) if (m_pScanner->empty())
break; break;
Token& token = m_pScanner->peek(); Token& token = m_pScanner->peek();
if(token.type != Token::DIRECTIVE) if (token.type != Token::DIRECTIVE)
break; break;
// we keep the directives from the last document if none are specified; // we keep the directives from the last document if none are specified;
// but if any directives are specific, then we reset them // but if any directives are specific, then we reset them
if(!readDirective) if (!readDirective)
m_pDirectives.reset(new Directives); m_pDirectives.reset(new Directives);
readDirective = true; readDirective = true;
HandleDirective(token); HandleDirective(token);
m_pScanner->pop(); m_pScanner->pop();
} }
} }
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")
HandleTagDirective(token); HandleTagDirective(token);
} }
// 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);
if(!m_pDirectives->version.isDefault) if (!m_pDirectives->version.isDefault)
throw ParserException(token.mark, ErrorMsg::REPEATED_YAML_DIRECTIVE); throw ParserException(token.mark, ErrorMsg::REPEATED_YAML_DIRECTIVE);
std::stringstream str(token.params[0]); std::stringstream str(token.params[0]);
str >> m_pDirectives->version.major; str >> m_pDirectives->version.major;
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);
m_pDirectives->version.isDefault = false; m_pDirectives->version.isDefault = false;
// TODO: warning on major == 1, minor > 2? // TODO: warning on major == 1, minor > 2?
} }
// 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);
const std::string& handle = token.params[0]; const std::string& handle = token.params[0];
const std::string& prefix = token.params[1]; const std::string& prefix = token.params[1];
if(m_pDirectives->tags.find(handle) != m_pDirectives->tags.end()) if (m_pDirectives->tags.find(handle) != m_pDirectives->tags.end())
throw ParserException(token.mark, ErrorMsg::REPEATED_TAG_DIRECTIVE); throw ParserException(token.mark, ErrorMsg::REPEATED_TAG_DIRECTIVE);
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;
while(1) { while (1) {
if(m_pScanner->empty()) if (m_pScanner->empty())
break; break;
out << m_pScanner->peek() << "\n"; out << m_pScanner->peek() << "\n";
m_pScanner->pop(); m_pScanner->pop();
} }
} }
} }
#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,14 +14,13 @@ ...@@ -12,14 +14,13 @@
#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(); }
void clear() { void clear() {
for(unsigned i=0;i<m_data.size();i++) for (unsigned i = 0; i < m_data.size(); i++)
delete m_data[i]; delete m_data[i];
m_data.clear(); m_data.clear();
} }
...@@ -40,9 +41,11 @@ public: ...@@ -40,9 +41,11 @@ 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;
}; };
......
#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
...@@ -13,15 +15,14 @@ ...@@ -13,15 +15,14 @@
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(); }
void clear() { void clear() {
for(unsigned i=0;i<m_data.size();i++) for (unsigned i = 0; i < m_data.size(); i++)
delete m_data[i]; delete m_data[i];
m_data.clear(); m_data.clear();
} }
...@@ -41,7 +42,7 @@ namespace YAML { ...@@ -41,7 +42,7 @@ namespace YAML {
private: private:
std::vector<T*> m_data; std::vector<T*> m_data;
}; };
} }
#endif // PTR_VECTOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // PTR_VECTOR_H_62B23520_7C8E_11DE_8A39_0800200C9A66
#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(char ch) : m_op(REGEX_MATCH), m_a(ch) {}
RegEx::RegEx(REGEX_OP op): m_op(op)
{ 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(char ch): m_op(REGEX_MATCH), m_a(ch) for (std::size_t i = 0; i < str.size(); i++)
{
}
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)
{
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;
}
} }
}
#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);
...@@ -27,39 +34,50 @@ namespace YAML ...@@ -27,39 +34,50 @@ namespace YAML
RegEx(const std::string& str, REGEX_OP op = REGEX_SEQ); RegEx(const std::string& str, REGEX_OP op = REGEX_SEQ);
~RegEx() {} ~RegEx() {}
friend RegEx operator ! (const RegEx& ex); friend RegEx operator!(const RegEx & ex);
friend RegEx operator || (const RegEx& ex1, const RegEx& ex2); friend RegEx operator||(const RegEx& ex1, const RegEx& ex2);
friend RegEx operator && (const RegEx& ex1, const RegEx& ex2); friend RegEx operator&&(const RegEx& ex1, const RegEx& ex2);
friend RegEx operator + (const RegEx& ex1, const RegEx& ex2); friend RegEx operator+(const RegEx& ex1, const RegEx& ex2);
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;
char m_a, m_z; char m_a, m_z;
std::vector <RegEx> m_params; std::vector<RegEx> m_params;
}; };
} }
#include "regeximpl.h" #include "regeximpl.h"
......
#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;
str += ch; str += ch;
return Matches(str); return Matches(str);
} }
inline bool RegEx::Matches(const std::string& str) const { inline bool RegEx::Matches(const std::string& str) const {
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 {
return Match(source) >= 0; return Match(source) >= 0;
} }
// Match // Match
// . Matches the given string against this regular expression. // . Matches the given string against this regular expression.
// . Returns the number of characters matched. // . Returns the number of characters matched.
// . Returns -1 if no characters were matched (the reason for // . Returns -1 if no characters were matched (the reason for
// 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:
return source; return source;
default: default:
return true; return true;
} }
} }
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);
case REGEX_MATCH: case REGEX_MATCH:
...@@ -96,91 +89,98 @@ namespace YAML ...@@ -96,91 +89,98 @@ namespace YAML
} }
return -1; return -1;
} }
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
// Operators // Operators
// Note: the convention MatchOp*<Source> is that we can assume IsSourceValid(source). // Note: the convention MatchOp*<Source> is that we can assume
// So we do all our checks *before* we call these functions // IsSourceValid(source).
// So we do all our checks *before* we call these functions
// EmptyOperator // EmptyOperator
template <typename Source> template <typename Source>
inline int RegEx::MatchOpEmpty(const Source& source) const { inline int RegEx::MatchOpEmpty(const Source& source) const {
return source[0] == Stream::eof() ? 0 : -1; return source[0] == Stream::eof() ? 0 : -1;
} }
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
template <typename Source> template <typename Source>
inline int RegEx::MatchOpMatch(const Source& source) const { inline int RegEx::MatchOpMatch(const Source& source) const {
if(source[0] != m_a) if (source[0] != m_a)
return -1; return -1;
return 1; return 1;
} }
// RangeOperator // RangeOperator
template <typename Source> template <typename Source>
inline int RegEx::MatchOpRange(const Source& source) const { inline int RegEx::MatchOpRange(const Source& source) const {
if(m_a > source[0] || m_z < source[0]) if (m_a > source[0] || m_z < source[0])
return -1; return -1;
return 1; return 1;
} }
// OrOperator // OrOperator
template <typename Source> template <typename Source>
inline int RegEx::MatchOpOr(const Source& source) const { inline int RegEx::MatchOpOr(const Source& source) const {
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].MatchUnchecked(source); int n = m_params[i].MatchUnchecked(source);
if(n >= 0) if (n >= 0)
return n; return n;
} }
return -1; return -1;
} }
// AndOperator // AndOperator
// Note: 'AND' is a little funny, since we may be required to match things // Note: 'AND' is a little funny, since we may be required to match things
// of different lengths. If we find a match, we return the length of // of different lengths. If we find a match, we return the length of
// the FIRST entry on the list. // the FIRST entry on the list.
template <typename Source> template <typename Source>
inline int RegEx::MatchOpAnd(const Source& source) const { inline int RegEx::MatchOpAnd(const Source& source) const {
int first = -1; int first = -1;
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].MatchUnchecked(source); int n = m_params[i].MatchUnchecked(source);
if(n == -1) if (n == -1)
return -1; return -1;
if(i == 0) if (i == 0)
first = n; first = n;
} }
return first; return first;
} }
// NotOperator // NotOperator
template <typename Source> template <typename Source>
inline int RegEx::MatchOpNot(const Source& source) const { inline int RegEx::MatchOpNot(const Source& source) const {
if(m_params.empty()) if (m_params.empty())
return -1; return -1;
if(m_params[0].MatchUnchecked(source) >= 0) if (m_params[0].MatchUnchecked(source) >= 0)
return -1; return -1;
return 1; return 1;
} }
// SeqOperator // SeqOperator
template <typename Source> template <typename Source>
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
if(n == -1) // MatchUnchecked because we
// need to check validity after
// the offset
if (n == -1)
return -1; return -1;
offset += n; offset += n;
} }
return offset; return offset;
} }
} }
#endif // REGEXIMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #endif // REGEXIMPL_H_62B23520_7C8E_11DE_8A39_0800200C9A66
...@@ -5,40 +5,37 @@ ...@@ -5,40 +5,37 @@
#include <cassert> #include <cassert>
#include <memory> #include <memory>
namespace YAML namespace YAML {
{ Scanner::Scanner(std::istream& in)
Scanner::Scanner(std::istream& in) : INPUT(in),
: INPUT(in), m_startedStream(false), m_endedStream(false), m_simpleKeyAllowed(false), m_canBeJSONFlow(false) 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();
} }
// 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
...@@ -49,30 +46,26 @@ namespace YAML ...@@ -49,30 +46,26 @@ namespace YAML
#endif #endif
return m_tokens.front(); return m_tokens.front();
} }
// 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();
// if this guy's valid, then we're done // if this guy's valid, then we're done
if(token.status == Token::VALID) if (token.status == Token::VALID)
return; return;
// here's where we clean up the impossible tokens // here's where we clean up the impossible tokens
if(token.status == Token::INVALID) { if (token.status == Token::INVALID) {
m_tokens.pop(); m_tokens.pop();
continue; continue;
} }
...@@ -81,23 +74,22 @@ namespace YAML ...@@ -81,23 +74,22 @@ namespace YAML
} }
// no token? maybe we've actually finished // no token? maybe we've actually finished
if(m_endedStream) if (m_endedStream)
return; return;
// no? then scan... // no? then scan...
ScanNextToken(); ScanNextToken();
} }
} }
// 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;
if(!m_startedStream) if (!m_startedStream)
return StartStream(); return StartStream();
// get rid of whitespace, etc. (in between tokens it should be irrelevent) // get rid of whitespace, etc. (in between tokens it should be irrelevent)
...@@ -111,83 +103,84 @@ namespace YAML ...@@ -111,83 +103,84 @@ namespace YAML
// ***** // *****
// end of stream // end of stream
if(!INPUT) if (!INPUT)
return EndStream(); return EndStream();
if(INPUT.column() == 0 && INPUT.peek() == Keys::Directive) if (INPUT.column() == 0 && INPUT.peek() == Keys::Directive)
return ScanDirective(); return ScanDirective();
// document token // document token
if(INPUT.column() == 0 && Exp::DocStart().Matches(INPUT)) if (INPUT.column() == 0 && Exp::DocStart().Matches(INPUT))
return ScanDocStart(); return ScanDocStart();
if(INPUT.column() == 0 && Exp::DocEnd().Matches(INPUT)) if (INPUT.column() == 0 && Exp::DocEnd().Matches(INPUT))
return ScanDocEnd(); return ScanDocEnd();
// flow start/end/entry // flow start/end/entry
if(INPUT.peek() == Keys::FlowSeqStart || INPUT.peek() == Keys::FlowMapStart) if (INPUT.peek() == Keys::FlowSeqStart || INPUT.peek() == Keys::FlowMapStart)
return ScanFlowStart(); return ScanFlowStart();
if(INPUT.peek() == Keys::FlowSeqEnd || INPUT.peek() == Keys::FlowMapEnd) if (INPUT.peek() == Keys::FlowSeqEnd || INPUT.peek() == Keys::FlowMapEnd)
return ScanFlowEnd(); return ScanFlowEnd();
if(INPUT.peek() == Keys::FlowEntry) if (INPUT.peek() == Keys::FlowEntry)
return ScanFlowEntry(); return ScanFlowEntry();
// block/map stuff // block/map stuff
if(Exp::BlockEntry().Matches(INPUT)) if (Exp::BlockEntry().Matches(INPUT))
return ScanBlockEntry(); return ScanBlockEntry();
if((InBlockContext() ? Exp::Key() : Exp::KeyInFlow()).Matches(INPUT)) if ((InBlockContext() ? Exp::Key() : Exp::KeyInFlow()).Matches(INPUT))
return ScanKey(); return ScanKey();
if(GetValueRegex().Matches(INPUT)) if (GetValueRegex().Matches(INPUT))
return ScanValue(); return ScanValue();
// alias/anchor // alias/anchor
if(INPUT.peek() == Keys::Alias || INPUT.peek() == Keys::Anchor) if (INPUT.peek() == Keys::Alias || INPUT.peek() == Keys::Anchor)
return ScanAnchorOrAlias(); return ScanAnchorOrAlias();
// tag // tag
if(INPUT.peek() == Keys::Tag) if (INPUT.peek() == Keys::Tag)
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!
throw ParserException(INPUT.mark(), ErrorMsg::UNKNOWN_TOKEN); throw ParserException(INPUT.mark(), ErrorMsg::UNKNOWN_TOKEN);
} }
// 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())) {
if(InBlockContext() && Exp::Tab().Matches(INPUT)) if (InBlockContext() && Exp::Tab().Matches(INPUT))
m_simpleKeyAllowed = false; m_simpleKeyAllowed = false;
INPUT.eat(1); INPUT.eat(1);
} }
// then eat a comment // then eat a comment
if(Exp::Comment().Matches(INPUT)) { if (Exp::Comment().Matches(INPUT)) {
// eat until line break // eat until line break
while(INPUT && !Exp::Break().Matches(INPUT)) while (INPUT && !Exp::Break().Matches(INPUT))
INPUT.eat(1); INPUT.eat(1);
} }
// if it's NOT a line break, then we're done! // if it's NOT a line break, then we're done!
if(!Exp::Break().Matches(INPUT)) if (!Exp::Break().Matches(INPUT))
break; break;
// otherwise, let's eat the line break and keep going // otherwise, let's eat the line break and keep going
...@@ -198,60 +191,57 @@ namespace YAML ...@@ -198,60 +191,57 @@ namespace YAML
InvalidateSimpleKey(); InvalidateSimpleKey();
// new line - we may be able to accept a simple key now // new line - we may be able to accept a simple key now
if(InBlockContext()) if (InBlockContext())
m_simpleKeyAllowed = true; m_simpleKeyAllowed = true;
} }
} }
/////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////
// Misc. helpers // Misc. helpers
// IsWhitespaceToBeEaten // IsWhitespaceToBeEaten
// . 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 // ':')"
// that they can't contribute to indentation, so once you've seen a tab in a // I think this is wrong, since tabs can be non-content whitespace; it's just
// line, you can't start a simple key // that they can't contribute to indentation, so once you've seen a tab in a
bool Scanner::IsWhitespaceToBeEaten(char ch) // line, you can't start a simple key
{ bool Scanner::IsWhitespaceToBeEaten(char ch) {
if(ch == ' ') if (ch == ' ')
return true; return true;
if(ch == '\t') if (ch == '\t')
return true; return true;
return false; return false;
} }
// 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();
return m_canBeJSONFlow ? Exp::ValueInJSONFlow() : Exp::ValueInFlow(); return m_canBeJSONFlow ? Exp::ValueInJSONFlow() : Exp::ValueInFlow();
} }
// 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));
m_indentRefs.push_back(pIndent); m_indentRefs.push_back(pIndent);
m_indents.push(&m_indentRefs.back()); m_indents.push(&m_indentRefs.back());
} }
// 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();
PopAllIndents(); PopAllIndents();
...@@ -259,33 +249,35 @@ namespace YAML ...@@ -259,33 +249,35 @@ namespace YAML
m_simpleKeyAllowed = false; m_simpleKeyAllowed = false;
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:
case IndentMarker::SEQ: return Token::BLOCK_SEQ_START; return Token::BLOCK_SEQ_START;
case IndentMarker::MAP: return Token::BLOCK_MAP_START; case IndentMarker::MAP:
case IndentMarker::NONE: assert(false); break; 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");
} }
// PushIndentTo // PushIndentTo
// . 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;
std::auto_ptr<IndentMarker> pIndent(new IndentMarker(column, type)); std::auto_ptr<IndentMarker> pIndent(new IndentMarker(column, type));
...@@ -293,9 +285,11 @@ namespace YAML ...@@ -293,9 +285,11 @@ namespace YAML
const IndentMarker& lastIndent = *m_indents.top(); const IndentMarker& lastIndent = *m_indents.top();
// 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
...@@ -305,90 +299,86 @@ namespace YAML ...@@ -305,90 +299,86 @@ namespace YAML
m_indents.push(&indent); m_indents.push(&indent);
m_indentRefs.push_back(pIndent); m_indentRefs.push_back(pIndent);
return &m_indentRefs.back(); return &m_indentRefs.back();
} }
// 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
// and enqueues the proper token each time. // level,
// . Then pops all invalid indentations off. // and enqueues the proper token each time.
void Scanner::PopIndentToHere() // . Then pops all invalid indentations off.
{ void Scanner::PopIndentToHere() {
// are we in flow? // are we in flow?
if(InFlowContext()) if (InFlowContext())
return; return;
// now pop away // now pop away
while(!m_indents.empty()) { while (!m_indents.empty()) {
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();
} }
while(!m_indents.empty() && m_indents.top()->status == IndentMarker::INVALID) while (!m_indents.empty() && m_indents.top()->status == IndentMarker::INVALID)
PopIndent(); PopIndent();
} }
// 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;
// now pop away // now pop away
while(!m_indents.empty()) { while (!m_indents.empty()) {
const IndentMarker& indent = *m_indents.top(); const IndentMarker& indent = *m_indents.top();
if(indent.type == IndentMarker::NONE) if (indent.type == IndentMarker::NONE)
break; break;
PopIndent(); PopIndent();
} }
} }
// 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();
if(indent.status != IndentMarker::VALID) { if (indent.status != IndentMarker::VALID) {
InvalidateSimpleKey(); InvalidateSimpleKey();
return; return;
} }
if(indent.type == IndentMarker::SEQ) if (indent.type == IndentMarker::SEQ)
m_tokens.push(Token(Token::BLOCK_SEQ_END, INPUT.mark())); m_tokens.push(Token(Token::BLOCK_SEQ_END, INPUT.mark()));
else if(indent.type == IndentMarker::MAP) else if (indent.type == IndentMarker::MAP)
m_tokens.push(Token(Token::BLOCK_MAP_END, INPUT.mark())); m_tokens.push(Token(Token::BLOCK_MAP_END, INPUT.mark()));
} }
// 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;
} }
// ThrowParserException // ThrowParserException
// . 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();
mark = token.mark; mark = token.mark;
} }
throw ParserException(mark, msg); throw ParserException(mark, msg);
}
} }
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment