emitterutils.cpp 6.58 KB
Newer Older
1
2
3
4
#include "emitterutils.h"
#include "exp.h"
#include "indentation.h"
#include "exceptions.h"
5
#include "stringsource.h"
6
7
#include <sstream>
#include <iomanip>
Jesse Beder's avatar
Jesse Beder committed
8
#include <cassert>
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

namespace YAML
{
	namespace Utils
	{
		namespace {
			bool IsPrintable(char ch) {
				return (0x20 <= ch && ch <= 0x7E);
			}
			
			bool IsValidPlainScalar(const std::string& str, bool inFlow) {
				// first check the start
				const RegEx& start = (inFlow ? Exp::PlainScalarInFlow : Exp::PlainScalar);
				if(!start.Matches(str))
					return false;
				
				// and check the end for plain whitespace (which can't be faithfully kept in a plain scalar)
				if(!str.empty() && *str.rbegin() == ' ')
					return false;

				// then check until something is disallowed
				const RegEx& disallowed = (inFlow ? Exp::EndScalarInFlow : Exp::EndScalar)
				                          || (Exp::BlankOrBreak + Exp::Comment)
				                          || (!Exp::Printable)
				                          || Exp::Break
				                          || Exp::Tab;
35
36
				StringCharSource buffer(str.c_str(), str.size());
				while(buffer) {
37
38
39
40
41
42
43
					if(disallowed.Matches(buffer))
						return false;
					++buffer;
				}
				
				return true;
			}
Jesse Beder's avatar
Jesse Beder committed
44
			
Jesse Beder's avatar
Jesse Beder committed
45
46
			typedef unsigned char byte;
			byte ToByte(char ch) { return static_cast<byte>(ch); }
Jesse Beder's avatar
Jesse Beder committed
47
			
Jesse Beder's avatar
Jesse Beder committed
48
49
			typedef std::string::const_iterator StrIter;

Jesse Beder's avatar
Jesse Beder committed
50
51
52
53
54
55
56
57
58
59
60
61
			std::string WriteUnicode(unsigned value) {
				std::stringstream str;
				// TODO: for the common escaped characters, give their usual symbol
				if(value <= 0xFF)
					str << "\\x" << std::hex << std::setfill('0') << std::setw(2) << value;
				else if(value <= 0xFFFF)
					str << "\\u" << std::hex << std::setfill('0') << std::setw(4) << value;
				else
					str << "\\U" << std::hex << std::setfill('0') << std::setw(8) << value;
				return str.str();
			}
			
Jesse Beder's avatar
Jesse Beder committed
62
63
64
65
66
67
68
69
70
71
72
73
74
			// GetBytesToRead
			// . Returns the length of the UTF-8 sequence starting with 'signal'
			int GetBytesToRead(byte signal) {
				if(signal <= 0x7F) // ASCII
					return 1;
				else if(signal <= 0xBF) // invalid first characters
					return 0;
				else if(signal <= 0xDF) // Note: this allows "overlong" UTF8 (0xC0 - 0xC1) to pass unscathed. OK?
					return 2;
				else if(signal <= 0xEF)
					return 3;
				else
					return 4;
Jesse Beder's avatar
Jesse Beder committed
75
76
			}
			
Jesse Beder's avatar
Jesse Beder committed
77
78
79
80
81
82
83
84
85
86
87
88
			// ReadBytes
			// . Reads the next 'bytesToRead', if we can.
			// . Returns zero if we fail, otherwise fills the byte buffer with
			//   the data and returns the number of bytes read.
			int ReadBytes(byte bytes[4], StrIter start, StrIter end, int bytesToRead) {
				for(int i=0;i<bytesToRead;i++) {
					if(start == end)
						return 0;
					bytes[i] = ToByte(*start);
					++start;
				}
				return bytesToRead;
Jesse Beder's avatar
Jesse Beder committed
89
90
			}
			
Jesse Beder's avatar
Jesse Beder committed
91
92
93
94
95
96
97
			// IsValidUTF8
			// . Assumes bytes[0] is a valid signal byte with the right size passed
			bool IsValidUTF8(byte bytes[4], int size) {
				for(int i=1;i<size;i++)
					if(bytes[i] & 0x80 != 0x80)
						return false;
				return true;
Jesse Beder's avatar
Jesse Beder committed
98
			}
Jesse Beder's avatar
Jesse Beder committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
			
			byte UTF8SignalPrefix(int size) {
				switch(size) {
					case 1: return 0;
					case 2: return 0xC0;
					case 3: return 0xE0;
					case 4: return 0xF0;
				}
				assert(false);
				return 0;
			}
			
			unsigned UTF8ToUnicode(byte bytes[4], int size) {
				unsigned value = bytes[0] - UTF8SignalPrefix(size);
				for(int i=1;i<size;i++)
					value = (value << 6) + (bytes[i] - 0x80);
				return value;
			}

			// ReadUTF8
			// . Returns the Unicode code point starting at 'start',
			//   and sets 'bytesRead' to the length of the UTF-8 Sequence
			// . If it's invalid UTF8, we set 'bytesRead' to zero.
			unsigned ReadUTF8(StrIter start, StrIter end, int& bytesRead) {
				int bytesToRead = GetBytesToRead(ToByte(*start));
				if(!bytesToRead) {
					bytesRead = 0;
					return 0;
				}
Jesse Beder's avatar
Jesse Beder committed
128

Jesse Beder's avatar
Jesse Beder committed
129
130
131
132
133
134
135
136
137
				byte bytes[4];
				bytesRead = ReadBytes(bytes, start, end, bytesToRead);
				if(!bytesRead)
					return 0;
				
				if(!IsValidUTF8(bytes, bytesRead)) {
					bytesRead = 0;
					return 0;
				}
Jesse Beder's avatar
Jesse Beder committed
138
				
Jesse Beder's avatar
Jesse Beder committed
139
				return UTF8ToUnicode(bytes, bytesRead);
Jesse Beder's avatar
Jesse Beder committed
140
141
142
143
			}

			// WriteNonPrintable
			// . Writes the next UTF-8 code point to the stream
Jesse Beder's avatar
Jesse Beder committed
144
145
146
147
148
149
150
151
152
			int WriteNonPrintable(ostream& out, StrIter start, StrIter end) {
				int bytesRead = 0;
				unsigned value = ReadUTF8(start, end, bytesRead);

				if(bytesRead == 0) {
					// TODO: is it ok to just write the replacement character here,
					//       or should we instead write the invalid byte (as \xNN)?
					out << WriteUnicode(0xFFFD);
					return 1;
Jesse Beder's avatar
Jesse Beder committed
153
154
				}
				
Jesse Beder's avatar
Jesse Beder committed
155
156
				out << WriteUnicode(value);
				return bytesRead;
Jesse Beder's avatar
Jesse Beder committed
157
			}
158
159
160
161
162
163
164
165
166
167
168
169
170
171
		}
		
		bool WriteString(ostream& out, const std::string& str, bool inFlow)
		{
			if(IsValidPlainScalar(str, inFlow)) {
				out << str;
				return true;
			} else
				return WriteDoubleQuotedString(out, str);
		}
		
		bool WriteSingleQuotedString(ostream& out, const std::string& str)
		{
			out << "'";
172
			for(std::size_t i=0;i<str.size();i++) {
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
				char ch = str[i];
				if(!IsPrintable(ch))
					return false;
				
				if(ch == '\'')
					out << "''";
				else
					out << ch;
			}
			out << "'";
			return true;
		}
		
		bool WriteDoubleQuotedString(ostream& out, const std::string& str)
		{
			out << "\"";
Jesse Beder's avatar
Jesse Beder committed
189
			for(StrIter it=str.begin();it!=str.end();++it) {
Jesse Beder's avatar
Jesse Beder committed
190
				char ch = *it;
191
192
193
194
195
196
197
198
				if(IsPrintable(ch)) {
					if(ch == '\"')
						out << "\\\"";
					else if(ch == '\\')
						out << "\\\\";
					else
						out << ch;
				} else {
Jesse Beder's avatar
Jesse Beder committed
199
200
201
					int bytesRead = WriteNonPrintable(out, it, str.end());
					if(bytesRead >= 1)
						it += (bytesRead - 1);
202
203
204
205
206
207
208
209
210
211
				}
			}
			out << "\"";
			return true;
		}

		bool WriteLiteralString(ostream& out, const std::string& str, int indent)
		{
			out << "|\n";
			out << IndentTo(indent);
212
			for(std::size_t i=0;i<str.size();i++) {
213
214
215
216
217
218
219
220
221
222
223
224
				if(str[i] == '\n')
					out << "\n" << IndentTo(indent);
				else
					out << str[i];
			}
			return true;
		}
		
		bool WriteComment(ostream& out, const std::string& str, int postCommentIndent)
		{
			unsigned curIndent = out.col();
			out << "#" << Indentation(postCommentIndent);
225
			for(std::size_t i=0;i<str.size();i++) {
226
227
228
229
230
231
232
233
234
235
236
				if(str[i] == '\n')
					out << "\n" << IndentTo(curIndent) << "#" << Indentation(postCommentIndent);
				else
					out << str[i];
			}
			return true;
		}

		bool WriteAlias(ostream& out, const std::string& str)
		{
			out << "*";
237
			for(std::size_t i=0;i<str.size();i++) {
238
239
240
241
242
243
244
245
246
247
248
				if(!IsPrintable(str[i]) || str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r')
					return false;
				
				out << str[i];
			}
			return true;
		}
		
		bool WriteAnchor(ostream& out, const std::string& str)
		{
			out << "&";
249
			for(std::size_t i=0;i<str.size();i++) {
250
251
252
253
254
255
256
257
258
259
				if(!IsPrintable(str[i]) || str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r')
					return false;
				
				out << str[i];
			}
			return true;
		}
	}
}