The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

704 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. struct JSONParser
  20. {
  21. JSONParser (String::CharPointerType text) : startLocation (text), currentLocation (text) {}
  22. String::CharPointerType startLocation, currentLocation;
  23. struct ErrorException
  24. {
  25. String message;
  26. int line = 1, column = 1;
  27. String getDescription() const { return String (line) + ":" + String (column) + ": error: " + message; }
  28. Result getResult() const { return Result::fail (getDescription()); }
  29. };
  30. [[noreturn]] void throwError (juce::String message, String::CharPointerType location)
  31. {
  32. ErrorException e;
  33. e.message = std::move (message);
  34. for (auto i = startLocation; i < location && ! i.isEmpty(); ++i)
  35. {
  36. ++e.column;
  37. if (*i == '\n') { e.column = 1; e.line++; }
  38. }
  39. throw e;
  40. }
  41. void skipWhitespace() { currentLocation = currentLocation.findEndOfWhitespace(); }
  42. juce_wchar readChar() { return currentLocation.getAndAdvance(); }
  43. juce_wchar peekChar() const { return *currentLocation; }
  44. bool matchIf (char c) { if (peekChar() == (juce_wchar) c) { ++currentLocation; return true; } return false; }
  45. bool isEOF() const { return peekChar() == 0; }
  46. bool matchString (const char* t)
  47. {
  48. while (*t != 0)
  49. if (! matchIf (*t++))
  50. return false;
  51. return true;
  52. }
  53. var parseObjectOrArray()
  54. {
  55. skipWhitespace();
  56. if (matchIf ('{')) return parseObject();
  57. if (matchIf ('[')) return parseArray();
  58. if (! isEOF())
  59. throwError ("Expected '{' or '['", currentLocation);
  60. return {};
  61. }
  62. String parseString (const juce_wchar quoteChar)
  63. {
  64. MemoryOutputStream buffer (256);
  65. for (;;)
  66. {
  67. auto c = readChar();
  68. if (c == quoteChar)
  69. break;
  70. if (c == '\\')
  71. {
  72. auto errorLocation = currentLocation;
  73. c = readChar();
  74. switch (c)
  75. {
  76. case '"':
  77. case '\'':
  78. case '\\':
  79. case '/': break;
  80. case 'a': c = '\a'; break;
  81. case 'b': c = '\b'; break;
  82. case 'f': c = '\f'; break;
  83. case 'n': c = '\n'; break;
  84. case 'r': c = '\r'; break;
  85. case 't': c = '\t'; break;
  86. case 'u':
  87. {
  88. c = 0;
  89. for (int i = 4; --i >= 0;)
  90. {
  91. auto digitValue = CharacterFunctions::getHexDigitValue (readChar());
  92. if (digitValue < 0)
  93. throwError ("Syntax error in unicode escape sequence", errorLocation);
  94. c = (juce_wchar) ((c << 4) + static_cast<juce_wchar> (digitValue));
  95. }
  96. break;
  97. }
  98. default: break;
  99. }
  100. }
  101. if (c == 0)
  102. throwError ("Unexpected EOF in string constant", currentLocation);
  103. buffer.appendUTF8Char (c);
  104. }
  105. return buffer.toUTF8();
  106. }
  107. var parseAny()
  108. {
  109. skipWhitespace();
  110. auto originalLocation = currentLocation;
  111. switch (readChar())
  112. {
  113. case '{': return parseObject();
  114. case '[': return parseArray();
  115. case '"': return parseString ('"');
  116. case '\'': return parseString ('\'');
  117. case '-':
  118. skipWhitespace();
  119. return parseNumber (true);
  120. case '0': case '1': case '2': case '3': case '4':
  121. case '5': case '6': case '7': case '8': case '9':
  122. currentLocation = originalLocation;
  123. return parseNumber (false);
  124. case 't': // "true"
  125. if (matchString ("rue"))
  126. return var (true);
  127. break;
  128. case 'f': // "false"
  129. if (matchString ("alse"))
  130. return var (false);
  131. break;
  132. case 'n': // "null"
  133. if (matchString ("ull"))
  134. return {};
  135. break;
  136. default:
  137. break;
  138. }
  139. throwError ("Syntax error", originalLocation);
  140. }
  141. var parseNumber (bool isNegative)
  142. {
  143. auto originalPos = currentLocation;
  144. int64 intValue = readChar() - '0';
  145. jassert (intValue >= 0 && intValue < 10);
  146. for (;;)
  147. {
  148. auto lastPos = currentLocation;
  149. auto c = readChar();
  150. auto digit = ((int) c) - '0';
  151. if (isPositiveAndBelow (digit, 10))
  152. {
  153. intValue = intValue * 10 + digit;
  154. continue;
  155. }
  156. if (c == 'e' || c == 'E' || c == '.')
  157. {
  158. currentLocation = originalPos;
  159. auto asDouble = CharacterFunctions::readDoubleValue (currentLocation);
  160. return var (isNegative ? -asDouble : asDouble);
  161. }
  162. if (CharacterFunctions::isWhitespace (c)
  163. || c == ',' || c == '}' || c == ']' || c == 0)
  164. {
  165. currentLocation = lastPos;
  166. break;
  167. }
  168. throwError ("Syntax error in number", lastPos);
  169. }
  170. auto correctedValue = isNegative ? -intValue : intValue;
  171. return (intValue >> 31) != 0 ? var (correctedValue)
  172. : var ((int) correctedValue);
  173. }
  174. var parseObject()
  175. {
  176. auto resultObject = new DynamicObject();
  177. var result (resultObject);
  178. auto& resultProperties = resultObject->getProperties();
  179. auto startOfObjectDecl = currentLocation;
  180. for (;;)
  181. {
  182. skipWhitespace();
  183. auto errorLocation = currentLocation;
  184. auto c = readChar();
  185. if (c == '}')
  186. break;
  187. if (c == 0)
  188. throwError ("Unexpected EOF in object declaration", startOfObjectDecl);
  189. if (c != '"')
  190. throwError ("Expected a property name in double-quotes", errorLocation);
  191. errorLocation = currentLocation;
  192. Identifier propertyName (parseString ('"'));
  193. if (! propertyName.isValid())
  194. throwError ("Invalid property name", errorLocation);
  195. skipWhitespace();
  196. errorLocation = currentLocation;
  197. if (readChar() != ':')
  198. throwError ("Expected ':'", errorLocation);
  199. resultProperties.set (propertyName, parseAny());
  200. skipWhitespace();
  201. if (matchIf (',')) continue;
  202. if (matchIf ('}')) break;
  203. throwError ("Expected ',' or '}'", currentLocation);
  204. }
  205. return result;
  206. }
  207. var parseArray()
  208. {
  209. auto result = var (Array<var>());
  210. auto destArray = result.getArray();
  211. auto startOfArrayDecl = currentLocation;
  212. for (;;)
  213. {
  214. skipWhitespace();
  215. if (matchIf (']'))
  216. break;
  217. if (isEOF())
  218. throwError ("Unexpected EOF in array declaration", startOfArrayDecl);
  219. destArray->add (parseAny());
  220. skipWhitespace();
  221. if (matchIf (',')) continue;
  222. if (matchIf (']')) break;
  223. throwError ("Expected ',' or ']'", currentLocation);
  224. }
  225. return result;
  226. }
  227. };
  228. //==============================================================================
  229. struct JSONFormatter
  230. {
  231. static void writeEscapedChar (OutputStream& out, const unsigned short value)
  232. {
  233. out << "\\u" << String::toHexString ((int) value).paddedLeft ('0', 4);
  234. }
  235. static void writeString (OutputStream& out, String::CharPointerType t)
  236. {
  237. for (;;)
  238. {
  239. auto c = t.getAndAdvance();
  240. switch (c)
  241. {
  242. case 0: return;
  243. case '\"': out << "\\\""; break;
  244. case '\\': out << "\\\\"; break;
  245. case '\a': out << "\\a"; break;
  246. case '\b': out << "\\b"; break;
  247. case '\f': out << "\\f"; break;
  248. case '\t': out << "\\t"; break;
  249. case '\r': out << "\\r"; break;
  250. case '\n': out << "\\n"; break;
  251. default:
  252. if (c >= 32 && c < 127)
  253. {
  254. out << (char) c;
  255. }
  256. else
  257. {
  258. if (CharPointer_UTF16::getBytesRequiredFor (c) > 2)
  259. {
  260. CharPointer_UTF16::CharType chars[2];
  261. CharPointer_UTF16 utf16 (chars);
  262. utf16.write (c);
  263. for (int i = 0; i < 2; ++i)
  264. writeEscapedChar (out, (unsigned short) chars[i]);
  265. }
  266. else
  267. {
  268. writeEscapedChar (out, (unsigned short) c);
  269. }
  270. }
  271. break;
  272. }
  273. }
  274. }
  275. static void writeSpaces (OutputStream& out, int numSpaces)
  276. {
  277. out.writeRepeatedByte (' ', (size_t) numSpaces);
  278. }
  279. static void writeArray (OutputStream& out, const Array<var>& array, const JSON::FormatOptions& format)
  280. {
  281. out << '[';
  282. if (! array.isEmpty())
  283. {
  284. if (format.getSpacing() == JSON::Spacing::multiLine)
  285. out << newLine;
  286. for (int i = 0; i < array.size(); ++i)
  287. {
  288. if (format.getSpacing() == JSON::Spacing::multiLine)
  289. writeSpaces (out, format.getIndentLevel() + indentSize);
  290. JSON::writeToStream (out, array.getReference (i), format.withIndentLevel (format.getIndentLevel() + indentSize));
  291. if (i < array.size() - 1)
  292. {
  293. out << ",";
  294. switch (format.getSpacing())
  295. {
  296. case JSON::Spacing::none: break;
  297. case JSON::Spacing::singleLine: out << ' '; break;
  298. case JSON::Spacing::multiLine: out << newLine; break;
  299. }
  300. }
  301. else if (format.getSpacing() == JSON::Spacing::multiLine)
  302. out << newLine;
  303. }
  304. if (format.getSpacing() == JSON::Spacing::multiLine)
  305. writeSpaces (out, format.getIndentLevel());
  306. }
  307. out << ']';
  308. }
  309. enum { indentSize = 2 };
  310. };
  311. void JSON::writeToStream (OutputStream& out, const var& v, const FormatOptions& opt)
  312. {
  313. if (v.isString())
  314. {
  315. out << '"';
  316. JSONFormatter::writeString (out, v.toString().getCharPointer());
  317. out << '"';
  318. }
  319. else if (v.isVoid())
  320. {
  321. out << "null";
  322. }
  323. else if (v.isUndefined())
  324. {
  325. out << "undefined";
  326. }
  327. else if (v.isBool())
  328. {
  329. out << (static_cast<bool> (v) ? "true" : "false");
  330. }
  331. else if (v.isDouble())
  332. {
  333. auto d = static_cast<double> (v);
  334. if (juce_isfinite (d))
  335. {
  336. out << serialiseDouble (d);
  337. }
  338. else
  339. {
  340. out << "null";
  341. }
  342. }
  343. else if (v.isArray())
  344. {
  345. JSONFormatter::writeArray (out, *v.getArray(), opt);
  346. }
  347. else if (v.isObject())
  348. {
  349. if (auto* object = v.getDynamicObject())
  350. object->writeAsJSON (out, opt);
  351. else
  352. jassertfalse; // Only DynamicObjects can be converted to JSON!
  353. }
  354. else
  355. {
  356. // Can't convert these other types of object to JSON!
  357. jassert (! (v.isMethod() || v.isBinaryData()));
  358. out << v.toString();
  359. }
  360. }
  361. String JSON::toString (const var& v, const FormatOptions& opt)
  362. {
  363. MemoryOutputStream mo { 1024 };
  364. writeToStream (mo, v, opt);
  365. return mo.toUTF8();
  366. }
  367. //==============================================================================
  368. var JSON::parse (const String& text)
  369. {
  370. var result;
  371. if (parse (text, result))
  372. return result;
  373. return {};
  374. }
  375. var JSON::fromString (StringRef text)
  376. {
  377. try
  378. {
  379. return JSONParser (text.text).parseAny();
  380. }
  381. catch (const JSONParser::ErrorException&) {}
  382. return {};
  383. }
  384. var JSON::parse (InputStream& input)
  385. {
  386. return parse (input.readEntireStreamAsString());
  387. }
  388. var JSON::parse (const File& file)
  389. {
  390. return parse (file.loadFileAsString());
  391. }
  392. Result JSON::parse (const String& text, var& result)
  393. {
  394. try
  395. {
  396. result = JSONParser (text.getCharPointer()).parseObjectOrArray();
  397. }
  398. catch (const JSONParser::ErrorException& error)
  399. {
  400. return error.getResult();
  401. }
  402. return Result::ok();
  403. }
  404. String JSON::toString (const var& data, const bool allOnOneLine, int maximumDecimalPlaces)
  405. {
  406. return toString (data, FormatOptions{}.withSpacing (allOnOneLine ? Spacing::singleLine : Spacing::multiLine)
  407. .withMaxDecimalPlaces (maximumDecimalPlaces));
  408. }
  409. void JSON::writeToStream (OutputStream& output, const var& data, const bool allOnOneLine, int maximumDecimalPlaces)
  410. {
  411. writeToStream (output, data, FormatOptions{}.withSpacing (allOnOneLine ? Spacing::singleLine : Spacing::multiLine)
  412. .withMaxDecimalPlaces (maximumDecimalPlaces));
  413. }
  414. String JSON::escapeString (StringRef s)
  415. {
  416. MemoryOutputStream mo;
  417. JSONFormatter::writeString (mo, s.text);
  418. return mo.toString();
  419. }
  420. Result JSON::parseQuotedString (String::CharPointerType& t, var& result)
  421. {
  422. try
  423. {
  424. JSONParser parser (t);
  425. auto quote = parser.readChar();
  426. if (quote != '"' && quote != '\'')
  427. return Result::fail ("Not a quoted string!");
  428. result = parser.parseString (quote);
  429. t = parser.currentLocation;
  430. }
  431. catch (const JSONParser::ErrorException& error)
  432. {
  433. return error.getResult();
  434. }
  435. return Result::ok();
  436. }
  437. //==============================================================================
  438. //==============================================================================
  439. #if JUCE_UNIT_TESTS
  440. class JSONTests final : public UnitTest
  441. {
  442. public:
  443. JSONTests()
  444. : UnitTest ("JSON", UnitTestCategories::json)
  445. {}
  446. static String createRandomWideCharString (Random& r)
  447. {
  448. juce_wchar buffer[40] = { 0 };
  449. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  450. {
  451. if (r.nextBool())
  452. {
  453. do
  454. {
  455. buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1));
  456. }
  457. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  458. }
  459. else
  460. buffer[i] = (juce_wchar) (1 + r.nextInt (0xff));
  461. }
  462. return CharPointer_UTF32 (buffer);
  463. }
  464. static String createRandomIdentifier (Random& r)
  465. {
  466. char buffer[30] = { 0 };
  467. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  468. {
  469. static const char chars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-:";
  470. buffer[i] = chars [r.nextInt (sizeof (chars) - 1)];
  471. }
  472. return CharPointer_ASCII (buffer);
  473. }
  474. // Creates a random double that can be easily stringified, to avoid
  475. // false failures when decimal places are rounded or truncated slightly
  476. static var createRandomDouble (Random& r)
  477. {
  478. return var ((r.nextDouble() * 1000.0) + 0.1);
  479. }
  480. static var createRandomVar (Random& r, int depth)
  481. {
  482. switch (r.nextInt (depth > 3 ? 6 : 8))
  483. {
  484. case 0: return {};
  485. case 1: return r.nextInt();
  486. case 2: return r.nextInt64();
  487. case 3: return r.nextBool();
  488. case 4: return createRandomDouble (r);
  489. case 5: return createRandomWideCharString (r);
  490. case 6:
  491. {
  492. var v (createRandomVar (r, depth + 1));
  493. for (int i = 1 + r.nextInt (30); --i >= 0;)
  494. v.append (createRandomVar (r, depth + 1));
  495. return v;
  496. }
  497. case 7:
  498. {
  499. auto o = new DynamicObject();
  500. for (int i = r.nextInt (30); --i >= 0;)
  501. o->setProperty (createRandomIdentifier (r), createRandomVar (r, depth + 1));
  502. return o;
  503. }
  504. default:
  505. return {};
  506. }
  507. }
  508. void runTest() override
  509. {
  510. {
  511. beginTest ("JSON");
  512. auto r = getRandom();
  513. expect (JSON::parse (String()) == var());
  514. expect (JSON::parse ("{}").isObject());
  515. expect (JSON::parse ("[]").isArray());
  516. expect (JSON::parse ("[ 1234 ]")[0].isInt());
  517. expect (JSON::parse ("[ 12345678901234 ]")[0].isInt64());
  518. expect (JSON::parse ("[ 1.123e3 ]")[0].isDouble());
  519. expect (JSON::parse ("[ -1234]")[0].isInt());
  520. expect (JSON::parse ("[-12345678901234]")[0].isInt64());
  521. expect (JSON::parse ("[-1.123e3]")[0].isDouble());
  522. for (int i = 100; --i >= 0;)
  523. {
  524. var v;
  525. if (i > 0)
  526. v = createRandomVar (r, 0);
  527. const auto oneLine = r.nextBool();
  528. const auto asString = JSON::toString (v, oneLine);
  529. const auto parsed = JSON::parse ("[" + asString + "]")[0];
  530. const auto parsedString = JSON::toString (parsed, oneLine);
  531. expect (asString.isNotEmpty() && parsedString == asString);
  532. }
  533. }
  534. {
  535. beginTest ("Float formatting");
  536. std::map<double, String> tests;
  537. tests[1] = "1.0";
  538. tests[1.1] = "1.1";
  539. tests[1.01] = "1.01";
  540. tests[0.76378] = "0.76378";
  541. tests[-10] = "-10.0";
  542. tests[10.01] = "10.01";
  543. tests[0.0123] = "0.0123";
  544. tests[-3.7e-27] = "-3.7e-27";
  545. tests[1e+40] = "1.0e40";
  546. tests[-12345678901234567.0] = "-1.234567890123457e16";
  547. tests[192000] = "192000.0";
  548. tests[1234567] = "1.234567e6";
  549. tests[0.00006] = "0.00006";
  550. tests[0.000006] = "6.0e-6";
  551. for (auto& test : tests)
  552. expectEquals (JSON::toString (test.first), test.second);
  553. }
  554. }
  555. };
  556. static JSONTests JSONUnitTests;
  557. #endif
  558. } // namespace juce