llvm.org GIT mirror llvm / 7eb8b0f
YAMLIO: Fix string quoting logic. YAMLIO printed a string as is without quotes unless it contains a newline character. That did not suffice. We also need to quote a string if it starts with a backquote, quote, double quote or atsign, or it's the empty string. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@190469 91177308-0d34-0410-b5e6-96231b3b80d8 Rui Ueyama 6 years ago
2 changed file(s) with 68 addition(s) and 3 deletion(s). Raw diff Collapse all Expand all
509509
510510 void Output::scalarString(StringRef &S) {
511511 this->newLineCheck();
512 if (S.find('\n') == StringRef::npos) {
513 // No embedded new-line chars, just print string.
512
513 if (S.empty()) {
514 // Print '' for the empty string because leaving the field empty is not
515 // allowed.
516 this->outputUpToEndOfLine("''");
517 return;
518 }
519 if (!strchr("'`@\"", S.front()) && S.find('\n') == StringRef::npos) {
520 // Plain string cannot start with double quote or single quote. Backquote
521 // and atsign are reserved characters. Newline is not allowed.
514522 this->outputUpToEndOfLine(S);
515523 return;
516524 }
272272 }
273273 }
274274
275
275 struct StringTypes {
276 llvm::StringRef str1;
277 llvm::StringRef str2;
278 llvm::StringRef str3;
279 llvm::StringRef str4;
280 llvm::StringRef str5;
281 };
282
283 namespace llvm {
284 namespace yaml {
285 template <>
286 struct MappingTraits {
287 static void mapping(IO &io, StringTypes& st) {
288 io.mapRequired("str1", st.str1);
289 io.mapRequired("str2", st.str2);
290 io.mapRequired("str3", st.str3);
291 io.mapRequired("str4", st.str4);
292 io.mapRequired("str5", st.str5);
293 }
294 };
295 }
296 }
297
298 TEST(YAMLIO, TestReadWriteStringTypes) {
299 std::string intermediate;
300 {
301 StringTypes map;
302 map.str1 = "'aaa";
303 map.str2 = "\"bbb";
304 map.str3 = "`ccc";
305 map.str4 = "@ddd";
306 map.str5 = "";
307
308 llvm::raw_string_ostream ostr(intermediate);
309 Output yout(ostr);
310 yout << map;
311 }
312
313 llvm::StringRef flowOut(intermediate);
314 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'''aaa"));
315 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'\"bbb'"));
316 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'`ccc'"));
317 EXPECT_NE(llvm::StringRef::npos, flowOut.find("'@ddd'"));
318 EXPECT_NE(llvm::StringRef::npos, flowOut.find("''\n"));
319
320 {
321 Input yin(intermediate);
322 StringTypes map;
323 yin >> map;
324
325 EXPECT_FALSE(yin.error());
326 EXPECT_TRUE(map.str1.equals("'aaa"));
327 EXPECT_TRUE(map.str2.equals("\"bbb"));
328 EXPECT_TRUE(map.str3.equals("`ccc"));
329 EXPECT_TRUE(map.str4.equals("@ddd"));
330 EXPECT_TRUE(map.str5.equals(""));
331 }
332 }
276333
277334 //===----------------------------------------------------------------------===//
278335 // Test ScalarEnumerationTraits