cpptoml.h 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668
  1. /**
  2. * @file cpptoml.h
  3. * @author Chase Geigle
  4. * @date May 2013
  5. */
  6. #ifndef CPPTOML_H
  7. #define CPPTOML_H
  8. #include <algorithm>
  9. #include <cassert>
  10. #include <clocale>
  11. #include <cstdint>
  12. #include <cstring>
  13. #include <fstream>
  14. #include <iomanip>
  15. #include <map>
  16. #include <memory>
  17. #include <sstream>
  18. #include <stdexcept>
  19. #include <string>
  20. #include <unordered_map>
  21. #include <vector>
  22. #if __cplusplus > 201103L
  23. #define CPPTOML_DEPRECATED(reason) [[deprecated(reason)]]
  24. #elif defined(__clang__)
  25. #define CPPTOML_DEPRECATED(reason) __attribute__((deprecated(reason)))
  26. #elif defined(__GNUG__)
  27. #define CPPTOML_DEPRECATED(reason) __attribute__((deprecated))
  28. #elif defined(_MSC_VER)
  29. #if _MSC_VER < 1910
  30. #define CPPTOML_DEPRECATED(reason) __declspec(deprecated)
  31. #else
  32. #define CPPTOML_DEPRECATED(reason) [[deprecated(reason)]]
  33. #endif
  34. #endif
  35. namespace cpptoml
  36. {
  37. class writer; // forward declaration
  38. class base; // forward declaration
  39. #if defined(CPPTOML_USE_MAP)
  40. // a std::map will ensure that entries a sorted, albeit at a slight
  41. // performance penalty relative to the (default) unordered_map
  42. using string_to_base_map = std::map<std::string, std::shared_ptr<base>>;
  43. #else
  44. // by default an unordered_map is used for best performance as the
  45. // toml specification does not require entries to be sorted
  46. using string_to_base_map
  47. = std::unordered_map<std::string, std::shared_ptr<base>>;
  48. #endif
  49. // if defined, `base` will retain type information in form of an enum class
  50. // such that static_cast can be used instead of dynamic_cast
  51. // #define CPPTOML_NO_RTTI
  52. template <class T>
  53. class option
  54. {
  55. public:
  56. option() : empty_{true}
  57. {
  58. // nothing
  59. }
  60. option(T value) : empty_{false}, value_(std::move(value))
  61. {
  62. // nothing
  63. }
  64. explicit operator bool() const
  65. {
  66. return !empty_;
  67. }
  68. const T& operator*() const
  69. {
  70. return value_;
  71. }
  72. const T* operator->() const
  73. {
  74. return &value_;
  75. }
  76. template <class U>
  77. T value_or(U&& alternative) const
  78. {
  79. if (!empty_)
  80. return value_;
  81. return static_cast<T>(std::forward<U>(alternative));
  82. }
  83. private:
  84. bool empty_;
  85. T value_;
  86. };
  87. struct local_date
  88. {
  89. int year = 0;
  90. int month = 0;
  91. int day = 0;
  92. };
  93. struct local_time
  94. {
  95. int hour = 0;
  96. int minute = 0;
  97. int second = 0;
  98. int microsecond = 0;
  99. };
  100. struct zone_offset
  101. {
  102. int hour_offset = 0;
  103. int minute_offset = 0;
  104. };
  105. struct local_datetime : local_date, local_time
  106. {
  107. };
  108. struct offset_datetime : local_datetime, zone_offset
  109. {
  110. static inline struct offset_datetime from_zoned(const struct tm& t)
  111. {
  112. offset_datetime dt;
  113. dt.year = t.tm_year + 1900;
  114. dt.month = t.tm_mon + 1;
  115. dt.day = t.tm_mday;
  116. dt.hour = t.tm_hour;
  117. dt.minute = t.tm_min;
  118. dt.second = t.tm_sec;
  119. char buf[16];
  120. strftime(buf, 16, "%z", &t);
  121. int offset = std::stoi(buf);
  122. dt.hour_offset = offset / 100;
  123. dt.minute_offset = offset % 100;
  124. return dt;
  125. }
  126. CPPTOML_DEPRECATED("from_local has been renamed to from_zoned")
  127. static inline struct offset_datetime from_local(const struct tm& t)
  128. {
  129. return from_zoned(t);
  130. }
  131. static inline struct offset_datetime from_utc(const struct tm& t)
  132. {
  133. offset_datetime dt;
  134. dt.year = t.tm_year + 1900;
  135. dt.month = t.tm_mon + 1;
  136. dt.day = t.tm_mday;
  137. dt.hour = t.tm_hour;
  138. dt.minute = t.tm_min;
  139. dt.second = t.tm_sec;
  140. return dt;
  141. }
  142. };
  143. CPPTOML_DEPRECATED("datetime has been renamed to offset_datetime")
  144. typedef offset_datetime datetime;
  145. class fill_guard
  146. {
  147. public:
  148. fill_guard(std::ostream& os) : os_(os), fill_{os.fill()}
  149. {
  150. // nothing
  151. }
  152. ~fill_guard()
  153. {
  154. os_.fill(fill_);
  155. }
  156. private:
  157. std::ostream& os_;
  158. std::ostream::char_type fill_;
  159. };
  160. inline std::ostream& operator<<(std::ostream& os, const local_date& dt)
  161. {
  162. fill_guard g{os};
  163. os.fill('0');
  164. using std::setw;
  165. os << setw(4) << dt.year << "-" << setw(2) << dt.month << "-" << setw(2)
  166. << dt.day;
  167. return os;
  168. }
  169. inline std::ostream& operator<<(std::ostream& os, const local_time& ltime)
  170. {
  171. fill_guard g{os};
  172. os.fill('0');
  173. using std::setw;
  174. os << setw(2) << ltime.hour << ":" << setw(2) << ltime.minute << ":"
  175. << setw(2) << ltime.second;
  176. if (ltime.microsecond > 0)
  177. {
  178. os << ".";
  179. int power = 100000;
  180. for (int curr_us = ltime.microsecond; curr_us; power /= 10)
  181. {
  182. auto num = curr_us / power;
  183. os << num;
  184. curr_us -= num * power;
  185. }
  186. }
  187. return os;
  188. }
  189. inline std::ostream& operator<<(std::ostream& os, const zone_offset& zo)
  190. {
  191. fill_guard g{os};
  192. os.fill('0');
  193. using std::setw;
  194. if (zo.hour_offset != 0 || zo.minute_offset != 0)
  195. {
  196. if (zo.hour_offset > 0)
  197. {
  198. os << "+";
  199. }
  200. else
  201. {
  202. os << "-";
  203. }
  204. os << setw(2) << std::abs(zo.hour_offset) << ":" << setw(2)
  205. << std::abs(zo.minute_offset);
  206. }
  207. else
  208. {
  209. os << "Z";
  210. }
  211. return os;
  212. }
  213. inline std::ostream& operator<<(std::ostream& os, const local_datetime& dt)
  214. {
  215. return os << static_cast<const local_date&>(dt) << "T"
  216. << static_cast<const local_time&>(dt);
  217. }
  218. inline std::ostream& operator<<(std::ostream& os, const offset_datetime& dt)
  219. {
  220. return os << static_cast<const local_datetime&>(dt)
  221. << static_cast<const zone_offset&>(dt);
  222. }
  223. template <class T, class... Ts>
  224. struct is_one_of;
  225. template <class T, class V>
  226. struct is_one_of<T, V> : std::is_same<T, V>
  227. {
  228. };
  229. template <class T, class V, class... Ts>
  230. struct is_one_of<T, V, Ts...>
  231. {
  232. const static bool value
  233. = std::is_same<T, V>::value || is_one_of<T, Ts...>::value;
  234. };
  235. template <class T>
  236. class value;
  237. template <class T>
  238. struct valid_value
  239. : is_one_of<T, std::string, int64_t, double, bool, local_date, local_time,
  240. local_datetime, offset_datetime>
  241. {
  242. };
  243. template <class T, class Enable = void>
  244. struct value_traits;
  245. template <class T>
  246. struct valid_value_or_string_convertible
  247. {
  248. const static bool value = valid_value<typename std::decay<T>::type>::value
  249. || std::is_convertible<T, std::string>::value;
  250. };
  251. template <class T>
  252. struct value_traits<T, typename std::enable_if<
  253. valid_value_or_string_convertible<T>::value>::type>
  254. {
  255. using value_type = typename std::conditional<
  256. valid_value<typename std::decay<T>::type>::value,
  257. typename std::decay<T>::type, std::string>::type;
  258. using type = value<value_type>;
  259. static value_type construct(T&& val)
  260. {
  261. return value_type(val);
  262. }
  263. };
  264. template <class T>
  265. struct value_traits<
  266. T,
  267. typename std::enable_if<
  268. !valid_value_or_string_convertible<T>::value
  269. && std::is_floating_point<typename std::decay<T>::type>::value>::type>
  270. {
  271. using value_type = typename std::decay<T>::type;
  272. using type = value<double>;
  273. static value_type construct(T&& val)
  274. {
  275. return value_type(val);
  276. }
  277. };
  278. template <class T>
  279. struct value_traits<
  280. T, typename std::enable_if<
  281. !valid_value_or_string_convertible<T>::value
  282. && !std::is_floating_point<typename std::decay<T>::type>::value
  283. && std::is_signed<typename std::decay<T>::type>::value>::type>
  284. {
  285. using value_type = int64_t;
  286. using type = value<int64_t>;
  287. static value_type construct(T&& val)
  288. {
  289. if (val < (std::numeric_limits<int64_t>::min)())
  290. throw std::underflow_error{"constructed value cannot be "
  291. "represented by a 64-bit signed "
  292. "integer"};
  293. if (val > (std::numeric_limits<int64_t>::max)())
  294. throw std::overflow_error{"constructed value cannot be represented "
  295. "by a 64-bit signed integer"};
  296. return static_cast<int64_t>(val);
  297. }
  298. };
  299. template <class T>
  300. struct value_traits<
  301. T, typename std::enable_if<
  302. !valid_value_or_string_convertible<T>::value
  303. && std::is_unsigned<typename std::decay<T>::type>::value>::type>
  304. {
  305. using value_type = int64_t;
  306. using type = value<int64_t>;
  307. static value_type construct(T&& val)
  308. {
  309. if (val > static_cast<uint64_t>((std::numeric_limits<int64_t>::max)()))
  310. throw std::overflow_error{"constructed value cannot be represented "
  311. "by a 64-bit signed integer"};
  312. return static_cast<int64_t>(val);
  313. }
  314. };
  315. class array;
  316. class table;
  317. class table_array;
  318. template <class T>
  319. struct array_of_trait
  320. {
  321. using return_type = option<std::vector<T>>;
  322. };
  323. template <>
  324. struct array_of_trait<array>
  325. {
  326. using return_type = option<std::vector<std::shared_ptr<array>>>;
  327. };
  328. template <class T>
  329. inline std::shared_ptr<typename value_traits<T>::type> make_value(T&& val);
  330. inline std::shared_ptr<array> make_array();
  331. namespace detail
  332. {
  333. template <class T>
  334. inline std::shared_ptr<T> make_element();
  335. }
  336. inline std::shared_ptr<table> make_table();
  337. inline std::shared_ptr<table_array> make_table_array(bool is_inline = false);
  338. #if defined(CPPTOML_NO_RTTI)
  339. /// Base type used to store underlying data type explicitly if RTTI is disabled
  340. enum class base_type
  341. {
  342. NONE,
  343. STRING,
  344. LOCAL_TIME,
  345. LOCAL_DATE,
  346. LOCAL_DATETIME,
  347. OFFSET_DATETIME,
  348. INT,
  349. FLOAT,
  350. BOOL,
  351. TABLE,
  352. ARRAY,
  353. TABLE_ARRAY
  354. };
  355. /// Type traits class to convert C++ types to enum member
  356. template <class T>
  357. struct base_type_traits;
  358. template <>
  359. struct base_type_traits<std::string>
  360. {
  361. static const base_type type = base_type::STRING;
  362. };
  363. template <>
  364. struct base_type_traits<local_time>
  365. {
  366. static const base_type type = base_type::LOCAL_TIME;
  367. };
  368. template <>
  369. struct base_type_traits<local_date>
  370. {
  371. static const base_type type = base_type::LOCAL_DATE;
  372. };
  373. template <>
  374. struct base_type_traits<local_datetime>
  375. {
  376. static const base_type type = base_type::LOCAL_DATETIME;
  377. };
  378. template <>
  379. struct base_type_traits<offset_datetime>
  380. {
  381. static const base_type type = base_type::OFFSET_DATETIME;
  382. };
  383. template <>
  384. struct base_type_traits<int64_t>
  385. {
  386. static const base_type type = base_type::INT;
  387. };
  388. template <>
  389. struct base_type_traits<double>
  390. {
  391. static const base_type type = base_type::FLOAT;
  392. };
  393. template <>
  394. struct base_type_traits<bool>
  395. {
  396. static const base_type type = base_type::BOOL;
  397. };
  398. template <>
  399. struct base_type_traits<table>
  400. {
  401. static const base_type type = base_type::TABLE;
  402. };
  403. template <>
  404. struct base_type_traits<array>
  405. {
  406. static const base_type type = base_type::ARRAY;
  407. };
  408. template <>
  409. struct base_type_traits<table_array>
  410. {
  411. static const base_type type = base_type::TABLE_ARRAY;
  412. };
  413. #endif
  414. /**
  415. * A generic base TOML value used for type erasure.
  416. */
  417. class base : public std::enable_shared_from_this<base>
  418. {
  419. public:
  420. virtual ~base() = default;
  421. virtual std::shared_ptr<base> clone() const = 0;
  422. /**
  423. * Determines if the given TOML element is a value.
  424. */
  425. virtual bool is_value() const
  426. {
  427. return false;
  428. }
  429. /**
  430. * Determines if the given TOML element is a table.
  431. */
  432. virtual bool is_table() const
  433. {
  434. return false;
  435. }
  436. /**
  437. * Converts the TOML element into a table.
  438. */
  439. std::shared_ptr<table> as_table()
  440. {
  441. if (is_table())
  442. return std::static_pointer_cast<table>(shared_from_this());
  443. return nullptr;
  444. }
  445. /**
  446. * Determines if the TOML element is an array of "leaf" elements.
  447. */
  448. virtual bool is_array() const
  449. {
  450. return false;
  451. }
  452. /**
  453. * Converts the TOML element to an array.
  454. */
  455. std::shared_ptr<array> as_array()
  456. {
  457. if (is_array())
  458. return std::static_pointer_cast<array>(shared_from_this());
  459. return nullptr;
  460. }
  461. /**
  462. * Determines if the given TOML element is an array of tables.
  463. */
  464. virtual bool is_table_array() const
  465. {
  466. return false;
  467. }
  468. /**
  469. * Converts the TOML element into a table array.
  470. */
  471. std::shared_ptr<table_array> as_table_array()
  472. {
  473. if (is_table_array())
  474. return std::static_pointer_cast<table_array>(shared_from_this());
  475. return nullptr;
  476. }
  477. /**
  478. * Attempts to coerce the TOML element into a concrete TOML value
  479. * of type T.
  480. */
  481. template <class T>
  482. std::shared_ptr<value<T>> as();
  483. template <class T>
  484. std::shared_ptr<const value<T>> as() const;
  485. template <class Visitor, class... Args>
  486. void accept(Visitor&& visitor, Args&&... args) const;
  487. #if defined(CPPTOML_NO_RTTI)
  488. base_type type() const
  489. {
  490. return type_;
  491. }
  492. protected:
  493. base(const base_type t) : type_(t)
  494. {
  495. // nothing
  496. }
  497. private:
  498. const base_type type_ = base_type::NONE;
  499. #else
  500. protected:
  501. base()
  502. {
  503. // nothing
  504. }
  505. #endif
  506. };
  507. /**
  508. * A concrete TOML value representing the "leaves" of the "tree".
  509. */
  510. template <class T>
  511. class value : public base
  512. {
  513. struct make_shared_enabler
  514. {
  515. // nothing; this is a private key accessible only to friends
  516. };
  517. template <class U>
  518. friend std::shared_ptr<typename value_traits<U>::type>
  519. cpptoml::make_value(U&& val);
  520. public:
  521. static_assert(valid_value<T>::value, "invalid value type");
  522. std::shared_ptr<base> clone() const override;
  523. value(const make_shared_enabler&, const T& val) : value(val)
  524. {
  525. // nothing; note that users cannot actually invoke this function
  526. // because they lack access to the make_shared_enabler.
  527. }
  528. bool is_value() const override
  529. {
  530. return true;
  531. }
  532. /**
  533. * Gets the data associated with this value.
  534. */
  535. T& get()
  536. {
  537. return data_;
  538. }
  539. /**
  540. * Gets the data associated with this value. Const version.
  541. */
  542. const T& get() const
  543. {
  544. return data_;
  545. }
  546. private:
  547. T data_;
  548. /**
  549. * Constructs a value from the given data.
  550. */
  551. #if defined(CPPTOML_NO_RTTI)
  552. value(const T& val) : base(base_type_traits<T>::type), data_(val)
  553. {
  554. }
  555. #else
  556. value(const T& val) : data_(val)
  557. {
  558. }
  559. #endif
  560. value(const value& val) = delete;
  561. value& operator=(const value& val) = delete;
  562. };
  563. template <class T>
  564. std::shared_ptr<typename value_traits<T>::type> make_value(T&& val)
  565. {
  566. using value_type = typename value_traits<T>::type;
  567. using enabler = typename value_type::make_shared_enabler;
  568. return std::make_shared<value_type>(
  569. enabler{}, value_traits<T>::construct(std::forward<T>(val)));
  570. }
  571. template <class T>
  572. inline std::shared_ptr<value<T>> base::as()
  573. {
  574. #if defined(CPPTOML_NO_RTTI)
  575. if (type() == base_type_traits<T>::type)
  576. return std::static_pointer_cast<value<T>>(shared_from_this());
  577. else
  578. return nullptr;
  579. #else
  580. return std::dynamic_pointer_cast<value<T>>(shared_from_this());
  581. #endif
  582. }
  583. // special case value<double> to allow getting an integer parameter as a
  584. // double value
  585. template <>
  586. inline std::shared_ptr<value<double>> base::as()
  587. {
  588. #if defined(CPPTOML_NO_RTTI)
  589. if (type() == base_type::FLOAT)
  590. return std::static_pointer_cast<value<double>>(shared_from_this());
  591. if (type() == base_type::INT)
  592. {
  593. auto v = std::static_pointer_cast<value<int64_t>>(shared_from_this());
  594. return make_value<double>(static_cast<double>(v->get()));
  595. }
  596. #else
  597. if (auto v = std::dynamic_pointer_cast<value<double>>(shared_from_this()))
  598. return v;
  599. if (auto v = std::dynamic_pointer_cast<value<int64_t>>(shared_from_this()))
  600. return make_value<double>(static_cast<double>(v->get()));
  601. #endif
  602. return nullptr;
  603. }
  604. template <class T>
  605. inline std::shared_ptr<const value<T>> base::as() const
  606. {
  607. #if defined(CPPTOML_NO_RTTI)
  608. if (type() == base_type_traits<T>::type)
  609. return std::static_pointer_cast<const value<T>>(shared_from_this());
  610. else
  611. return nullptr;
  612. #else
  613. return std::dynamic_pointer_cast<const value<T>>(shared_from_this());
  614. #endif
  615. }
  616. // special case value<double> to allow getting an integer parameter as a
  617. // double value
  618. template <>
  619. inline std::shared_ptr<const value<double>> base::as() const
  620. {
  621. #if defined(CPPTOML_NO_RTTI)
  622. if (type() == base_type::FLOAT)
  623. return std::static_pointer_cast<const value<double>>(
  624. shared_from_this());
  625. if (type() == base_type::INT)
  626. {
  627. auto v = as<int64_t>();
  628. // the below has to be a non-const value<double> due to a bug in
  629. // libc++: https://llvm.org/bugs/show_bug.cgi?id=18843
  630. return make_value<double>(static_cast<double>(v->get()));
  631. }
  632. #else
  633. if (auto v
  634. = std::dynamic_pointer_cast<const value<double>>(shared_from_this()))
  635. return v;
  636. if (auto v = as<int64_t>())
  637. {
  638. // the below has to be a non-const value<double> due to a bug in
  639. // libc++: https://llvm.org/bugs/show_bug.cgi?id=18843
  640. return make_value<double>(static_cast<double>(v->get()));
  641. }
  642. #endif
  643. return nullptr;
  644. }
  645. /**
  646. * Exception class for array insertion errors.
  647. */
  648. class array_exception : public std::runtime_error
  649. {
  650. public:
  651. array_exception(const std::string& err) : std::runtime_error{err}
  652. {
  653. }
  654. };
  655. class array : public base
  656. {
  657. public:
  658. friend std::shared_ptr<array> make_array();
  659. std::shared_ptr<base> clone() const override;
  660. virtual bool is_array() const override
  661. {
  662. return true;
  663. }
  664. using size_type = std::size_t;
  665. /**
  666. * arrays can be iterated over
  667. */
  668. using iterator = std::vector<std::shared_ptr<base>>::iterator;
  669. /**
  670. * arrays can be iterated over. Const version.
  671. */
  672. using const_iterator = std::vector<std::shared_ptr<base>>::const_iterator;
  673. iterator begin()
  674. {
  675. return values_.begin();
  676. }
  677. const_iterator begin() const
  678. {
  679. return values_.begin();
  680. }
  681. iterator end()
  682. {
  683. return values_.end();
  684. }
  685. const_iterator end() const
  686. {
  687. return values_.end();
  688. }
  689. /**
  690. * Obtains the array (vector) of base values.
  691. */
  692. std::vector<std::shared_ptr<base>>& get()
  693. {
  694. return values_;
  695. }
  696. /**
  697. * Obtains the array (vector) of base values. Const version.
  698. */
  699. const std::vector<std::shared_ptr<base>>& get() const
  700. {
  701. return values_;
  702. }
  703. std::shared_ptr<base> at(size_t idx) const
  704. {
  705. return values_.at(idx);
  706. }
  707. /**
  708. * Obtains an array of value<T>s. Note that elements may be
  709. * nullptr if they cannot be converted to a value<T>.
  710. */
  711. template <class T>
  712. std::vector<std::shared_ptr<value<T>>> array_of() const
  713. {
  714. std::vector<std::shared_ptr<value<T>>> result(values_.size());
  715. std::transform(values_.begin(), values_.end(), result.begin(),
  716. [&](std::shared_ptr<base> v) { return v->as<T>(); });
  717. return result;
  718. }
  719. /**
  720. * Obtains a option<vector<T>>. The option will be empty if the array
  721. * contains values that are not of type T.
  722. */
  723. template <class T>
  724. inline typename array_of_trait<T>::return_type get_array_of() const
  725. {
  726. std::vector<T> result;
  727. result.reserve(values_.size());
  728. for (const auto& val : values_)
  729. {
  730. if (auto v = val->as<T>())
  731. result.push_back(v->get());
  732. else
  733. return {};
  734. }
  735. return {std::move(result)};
  736. }
  737. /**
  738. * Obtains an array of arrays. Note that elements may be nullptr
  739. * if they cannot be converted to a array.
  740. */
  741. std::vector<std::shared_ptr<array>> nested_array() const
  742. {
  743. std::vector<std::shared_ptr<array>> result(values_.size());
  744. std::transform(values_.begin(), values_.end(), result.begin(),
  745. [&](std::shared_ptr<base> v) -> std::shared_ptr<array> {
  746. if (v->is_array())
  747. return std::static_pointer_cast<array>(v);
  748. return std::shared_ptr<array>{};
  749. });
  750. return result;
  751. }
  752. /**
  753. * Add a value to the end of the array
  754. */
  755. template <class T>
  756. void push_back(const std::shared_ptr<value<T>>& val)
  757. {
  758. if (values_.empty() || values_[0]->as<T>())
  759. {
  760. values_.push_back(val);
  761. }
  762. else
  763. {
  764. throw array_exception{"Arrays must be homogenous."};
  765. }
  766. }
  767. /**
  768. * Add an array to the end of the array
  769. */
  770. void push_back(const std::shared_ptr<array>& val)
  771. {
  772. if (values_.empty() || values_[0]->is_array())
  773. {
  774. values_.push_back(val);
  775. }
  776. else
  777. {
  778. throw array_exception{"Arrays must be homogenous."};
  779. }
  780. }
  781. /**
  782. * Convenience function for adding a simple element to the end
  783. * of the array.
  784. */
  785. template <class T>
  786. void push_back(T&& val, typename value_traits<T>::type* = 0)
  787. {
  788. push_back(make_value(std::forward<T>(val)));
  789. }
  790. /**
  791. * Insert a value into the array
  792. */
  793. template <class T>
  794. iterator insert(iterator position, const std::shared_ptr<value<T>>& value)
  795. {
  796. if (values_.empty() || values_[0]->as<T>())
  797. {
  798. return values_.insert(position, value);
  799. }
  800. else
  801. {
  802. throw array_exception{"Arrays must be homogenous."};
  803. }
  804. }
  805. /**
  806. * Insert an array into the array
  807. */
  808. iterator insert(iterator position, const std::shared_ptr<array>& value)
  809. {
  810. if (values_.empty() || values_[0]->is_array())
  811. {
  812. return values_.insert(position, value);
  813. }
  814. else
  815. {
  816. throw array_exception{"Arrays must be homogenous."};
  817. }
  818. }
  819. /**
  820. * Convenience function for inserting a simple element in the array
  821. */
  822. template <class T>
  823. iterator insert(iterator position, T&& val,
  824. typename value_traits<T>::type* = 0)
  825. {
  826. return insert(position, make_value(std::forward<T>(val)));
  827. }
  828. /**
  829. * Erase an element from the array
  830. */
  831. iterator erase(iterator position)
  832. {
  833. return values_.erase(position);
  834. }
  835. /**
  836. * Clear the array
  837. */
  838. void clear()
  839. {
  840. values_.clear();
  841. }
  842. /**
  843. * Reserve space for n values.
  844. */
  845. void reserve(size_type n)
  846. {
  847. values_.reserve(n);
  848. }
  849. private:
  850. #if defined(CPPTOML_NO_RTTI)
  851. array() : base(base_type::ARRAY)
  852. {
  853. // empty
  854. }
  855. #else
  856. array() = default;
  857. #endif
  858. template <class InputIterator>
  859. array(InputIterator begin, InputIterator end) : values_{begin, end}
  860. {
  861. // nothing
  862. }
  863. array(const array& obj) = delete;
  864. array& operator=(const array& obj) = delete;
  865. std::vector<std::shared_ptr<base>> values_;
  866. };
  867. inline std::shared_ptr<array> make_array()
  868. {
  869. struct make_shared_enabler : public array
  870. {
  871. make_shared_enabler()
  872. {
  873. // nothing
  874. }
  875. };
  876. return std::make_shared<make_shared_enabler>();
  877. }
  878. namespace detail
  879. {
  880. template <>
  881. inline std::shared_ptr<array> make_element<array>()
  882. {
  883. return make_array();
  884. }
  885. } // namespace detail
  886. /**
  887. * Obtains a option<vector<T>>. The option will be empty if the array
  888. * contains values that are not of type T.
  889. */
  890. template <>
  891. inline typename array_of_trait<array>::return_type
  892. array::get_array_of<array>() const
  893. {
  894. std::vector<std::shared_ptr<array>> result;
  895. result.reserve(values_.size());
  896. for (const auto& val : values_)
  897. {
  898. if (auto v = val->as_array())
  899. result.push_back(v);
  900. else
  901. return {};
  902. }
  903. return {std::move(result)};
  904. }
  905. class table;
  906. class table_array : public base
  907. {
  908. friend class table;
  909. friend std::shared_ptr<table_array> make_table_array(bool);
  910. public:
  911. std::shared_ptr<base> clone() const override;
  912. using size_type = std::size_t;
  913. /**
  914. * arrays can be iterated over
  915. */
  916. using iterator = std::vector<std::shared_ptr<table>>::iterator;
  917. /**
  918. * arrays can be iterated over. Const version.
  919. */
  920. using const_iterator = std::vector<std::shared_ptr<table>>::const_iterator;
  921. iterator begin()
  922. {
  923. return array_.begin();
  924. }
  925. const_iterator begin() const
  926. {
  927. return array_.begin();
  928. }
  929. iterator end()
  930. {
  931. return array_.end();
  932. }
  933. const_iterator end() const
  934. {
  935. return array_.end();
  936. }
  937. virtual bool is_table_array() const override
  938. {
  939. return true;
  940. }
  941. std::vector<std::shared_ptr<table>>& get()
  942. {
  943. return array_;
  944. }
  945. const std::vector<std::shared_ptr<table>>& get() const
  946. {
  947. return array_;
  948. }
  949. /**
  950. * Add a table to the end of the array
  951. */
  952. void push_back(const std::shared_ptr<table>& val)
  953. {
  954. array_.push_back(val);
  955. }
  956. /**
  957. * Insert a table into the array
  958. */
  959. iterator insert(iterator position, const std::shared_ptr<table>& value)
  960. {
  961. return array_.insert(position, value);
  962. }
  963. /**
  964. * Erase an element from the array
  965. */
  966. iterator erase(iterator position)
  967. {
  968. return array_.erase(position);
  969. }
  970. /**
  971. * Clear the array
  972. */
  973. void clear()
  974. {
  975. array_.clear();
  976. }
  977. /**
  978. * Reserve space for n tables.
  979. */
  980. void reserve(size_type n)
  981. {
  982. array_.reserve(n);
  983. }
  984. /**
  985. * Whether or not the table array is declared inline. This mostly
  986. * matters for parsing, where statically defined arrays cannot be
  987. * appended to using the array-of-table syntax.
  988. */
  989. bool is_inline() const
  990. {
  991. return is_inline_;
  992. }
  993. private:
  994. #if defined(CPPTOML_NO_RTTI)
  995. table_array(bool is_inline = false)
  996. : base(base_type::TABLE_ARRAY), is_inline_(is_inline)
  997. {
  998. // nothing
  999. }
  1000. #else
  1001. table_array(bool is_inline = false) : is_inline_(is_inline)
  1002. {
  1003. // nothing
  1004. }
  1005. #endif
  1006. table_array(const table_array& obj) = delete;
  1007. table_array& operator=(const table_array& rhs) = delete;
  1008. std::vector<std::shared_ptr<table>> array_;
  1009. const bool is_inline_ = false;
  1010. };
  1011. inline std::shared_ptr<table_array> make_table_array(bool is_inline)
  1012. {
  1013. struct make_shared_enabler : public table_array
  1014. {
  1015. make_shared_enabler(bool mse_is_inline) : table_array(mse_is_inline)
  1016. {
  1017. // nothing
  1018. }
  1019. };
  1020. return std::make_shared<make_shared_enabler>(is_inline);
  1021. }
  1022. namespace detail
  1023. {
  1024. template <>
  1025. inline std::shared_ptr<table_array> make_element<table_array>()
  1026. {
  1027. return make_table_array(true);
  1028. }
  1029. } // namespace detail
  1030. // The below are overloads for fetching specific value types out of a value
  1031. // where special casting behavior (like bounds checking) is desired
  1032. template <class T>
  1033. typename std::enable_if<!std::is_floating_point<T>::value
  1034. && std::is_signed<T>::value,
  1035. option<T>>::type
  1036. get_impl(const std::shared_ptr<base>& elem)
  1037. {
  1038. if (auto v = elem->as<int64_t>())
  1039. {
  1040. if (v->get() < (std::numeric_limits<T>::min)())
  1041. throw std::underflow_error{
  1042. "T cannot represent the value requested in get"};
  1043. if (v->get() > (std::numeric_limits<T>::max)())
  1044. throw std::overflow_error{
  1045. "T cannot represent the value requested in get"};
  1046. return {static_cast<T>(v->get())};
  1047. }
  1048. else
  1049. {
  1050. return {};
  1051. }
  1052. }
  1053. template <class T>
  1054. typename std::enable_if<!std::is_same<T, bool>::value
  1055. && std::is_unsigned<T>::value,
  1056. option<T>>::type
  1057. get_impl(const std::shared_ptr<base>& elem)
  1058. {
  1059. if (auto v = elem->as<int64_t>())
  1060. {
  1061. if (v->get() < 0)
  1062. throw std::underflow_error{"T cannot store negative value in get"};
  1063. if (static_cast<uint64_t>(v->get()) > (std::numeric_limits<T>::max)())
  1064. throw std::overflow_error{
  1065. "T cannot represent the value requested in get"};
  1066. return {static_cast<T>(v->get())};
  1067. }
  1068. else
  1069. {
  1070. return {};
  1071. }
  1072. }
  1073. template <class T>
  1074. typename std::enable_if<!std::is_integral<T>::value
  1075. || std::is_same<T, bool>::value,
  1076. option<T>>::type
  1077. get_impl(const std::shared_ptr<base>& elem)
  1078. {
  1079. if (auto v = elem->as<T>())
  1080. {
  1081. return {v->get()};
  1082. }
  1083. else
  1084. {
  1085. return {};
  1086. }
  1087. }
  1088. /**
  1089. * Represents a TOML keytable.
  1090. */
  1091. class table : public base
  1092. {
  1093. public:
  1094. friend class table_array;
  1095. friend std::shared_ptr<table> make_table();
  1096. std::shared_ptr<base> clone() const override;
  1097. /**
  1098. * tables can be iterated over.
  1099. */
  1100. using iterator = string_to_base_map::iterator;
  1101. /**
  1102. * tables can be iterated over. Const version.
  1103. */
  1104. using const_iterator = string_to_base_map::const_iterator;
  1105. iterator begin()
  1106. {
  1107. return map_.begin();
  1108. }
  1109. const_iterator begin() const
  1110. {
  1111. return map_.begin();
  1112. }
  1113. iterator end()
  1114. {
  1115. return map_.end();
  1116. }
  1117. const_iterator end() const
  1118. {
  1119. return map_.end();
  1120. }
  1121. bool is_table() const override
  1122. {
  1123. return true;
  1124. }
  1125. bool empty() const
  1126. {
  1127. return map_.empty();
  1128. }
  1129. /**
  1130. * Determines if this key table contains the given key.
  1131. */
  1132. bool contains(const std::string& key) const
  1133. {
  1134. return map_.find(key) != map_.end();
  1135. }
  1136. /**
  1137. * Determines if this key table contains the given key. Will
  1138. * resolve "qualified keys". Qualified keys are the full access
  1139. * path separated with dots like "grandparent.parent.child".
  1140. */
  1141. bool contains_qualified(const std::string& key) const
  1142. {
  1143. return resolve_qualified(key);
  1144. }
  1145. /**
  1146. * Obtains the base for a given key.
  1147. * @throw std::out_of_range if the key does not exist
  1148. */
  1149. std::shared_ptr<base> get(const std::string& key) const
  1150. {
  1151. return map_.at(key);
  1152. }
  1153. /**
  1154. * Obtains the base for a given key. Will resolve "qualified
  1155. * keys". Qualified keys are the full access path separated with
  1156. * dots like "grandparent.parent.child".
  1157. *
  1158. * @throw std::out_of_range if the key does not exist
  1159. */
  1160. std::shared_ptr<base> get_qualified(const std::string& key) const
  1161. {
  1162. std::shared_ptr<base> p;
  1163. resolve_qualified(key, &p);
  1164. return p;
  1165. }
  1166. /**
  1167. * Obtains a table for a given key, if possible.
  1168. */
  1169. std::shared_ptr<table> get_table(const std::string& key) const
  1170. {
  1171. if (contains(key) && get(key)->is_table())
  1172. return std::static_pointer_cast<table>(get(key));
  1173. return nullptr;
  1174. }
  1175. /**
  1176. * Obtains a table for a given key, if possible. Will resolve
  1177. * "qualified keys".
  1178. */
  1179. std::shared_ptr<table> get_table_qualified(const std::string& key) const
  1180. {
  1181. if (contains_qualified(key) && get_qualified(key)->is_table())
  1182. return std::static_pointer_cast<table>(get_qualified(key));
  1183. return nullptr;
  1184. }
  1185. /**
  1186. * Obtains an array for a given key.
  1187. */
  1188. std::shared_ptr<array> get_array(const std::string& key) const
  1189. {
  1190. if (!contains(key))
  1191. return nullptr;
  1192. return get(key)->as_array();
  1193. }
  1194. /**
  1195. * Obtains an array for a given key. Will resolve "qualified keys".
  1196. */
  1197. std::shared_ptr<array> get_array_qualified(const std::string& key) const
  1198. {
  1199. if (!contains_qualified(key))
  1200. return nullptr;
  1201. return get_qualified(key)->as_array();
  1202. }
  1203. /**
  1204. * Obtains a table_array for a given key, if possible.
  1205. */
  1206. std::shared_ptr<table_array> get_table_array(const std::string& key) const
  1207. {
  1208. if (!contains(key))
  1209. return nullptr;
  1210. return get(key)->as_table_array();
  1211. }
  1212. /**
  1213. * Obtains a table_array for a given key, if possible. Will resolve
  1214. * "qualified keys".
  1215. */
  1216. std::shared_ptr<table_array>
  1217. get_table_array_qualified(const std::string& key) const
  1218. {
  1219. if (!contains_qualified(key))
  1220. return nullptr;
  1221. return get_qualified(key)->as_table_array();
  1222. }
  1223. /**
  1224. * Helper function that attempts to get a value corresponding
  1225. * to the template parameter from a given key.
  1226. */
  1227. template <class T>
  1228. option<T> get_as(const std::string& key) const
  1229. {
  1230. try
  1231. {
  1232. return get_impl<T>(get(key));
  1233. }
  1234. catch (const std::out_of_range&)
  1235. {
  1236. return {};
  1237. }
  1238. }
  1239. /**
  1240. * Helper function that attempts to get a value corresponding
  1241. * to the template parameter from a given key. Will resolve "qualified
  1242. * keys".
  1243. */
  1244. template <class T>
  1245. option<T> get_qualified_as(const std::string& key) const
  1246. {
  1247. try
  1248. {
  1249. return get_impl<T>(get_qualified(key));
  1250. }
  1251. catch (const std::out_of_range&)
  1252. {
  1253. return {};
  1254. }
  1255. }
  1256. /**
  1257. * Helper function that attempts to get an array of values of a given
  1258. * type corresponding to the template parameter for a given key.
  1259. *
  1260. * If the key doesn't exist, doesn't exist as an array type, or one or
  1261. * more keys inside the array type are not of type T, an empty option
  1262. * is returned. Otherwise, an option containing a vector of the values
  1263. * is returned.
  1264. */
  1265. template <class T>
  1266. inline typename array_of_trait<T>::return_type
  1267. get_array_of(const std::string& key) const
  1268. {
  1269. if (auto v = get_array(key))
  1270. {
  1271. std::vector<T> result;
  1272. result.reserve(v->get().size());
  1273. for (const auto& b : v->get())
  1274. {
  1275. if (auto val = b->as<T>())
  1276. result.push_back(val->get());
  1277. else
  1278. return {};
  1279. }
  1280. return {std::move(result)};
  1281. }
  1282. return {};
  1283. }
  1284. /**
  1285. * Helper function that attempts to get an array of values of a given
  1286. * type corresponding to the template parameter for a given key. Will
  1287. * resolve "qualified keys".
  1288. *
  1289. * If the key doesn't exist, doesn't exist as an array type, or one or
  1290. * more keys inside the array type are not of type T, an empty option
  1291. * is returned. Otherwise, an option containing a vector of the values
  1292. * is returned.
  1293. */
  1294. template <class T>
  1295. inline typename array_of_trait<T>::return_type
  1296. get_qualified_array_of(const std::string& key) const
  1297. {
  1298. if (auto v = get_array_qualified(key))
  1299. {
  1300. std::vector<T> result;
  1301. result.reserve(v->get().size());
  1302. for (const auto& b : v->get())
  1303. {
  1304. if (auto val = b->as<T>())
  1305. result.push_back(val->get());
  1306. else
  1307. return {};
  1308. }
  1309. return {std::move(result)};
  1310. }
  1311. return {};
  1312. }
  1313. /**
  1314. * Adds an element to the keytable.
  1315. */
  1316. void insert(const std::string& key, const std::shared_ptr<base>& value)
  1317. {
  1318. map_[key] = value;
  1319. }
  1320. /**
  1321. * Convenience shorthand for adding a simple element to the
  1322. * keytable.
  1323. */
  1324. template <class T>
  1325. void insert(const std::string& key, T&& val,
  1326. typename value_traits<T>::type* = 0)
  1327. {
  1328. insert(key, make_value(std::forward<T>(val)));
  1329. }
  1330. /**
  1331. * Removes an element from the table.
  1332. */
  1333. void erase(const std::string& key)
  1334. {
  1335. map_.erase(key);
  1336. }
  1337. private:
  1338. #if defined(CPPTOML_NO_RTTI)
  1339. table() : base(base_type::TABLE)
  1340. {
  1341. // nothing
  1342. }
  1343. #else
  1344. table()
  1345. {
  1346. // nothing
  1347. }
  1348. #endif
  1349. table(const table& obj) = delete;
  1350. table& operator=(const table& rhs) = delete;
  1351. std::vector<std::string> split(const std::string& value,
  1352. char separator) const
  1353. {
  1354. std::vector<std::string> result;
  1355. std::string::size_type p = 0;
  1356. std::string::size_type q;
  1357. while ((q = value.find(separator, p)) != std::string::npos)
  1358. {
  1359. result.emplace_back(value, p, q - p);
  1360. p = q + 1;
  1361. }
  1362. result.emplace_back(value, p);
  1363. return result;
  1364. }
  1365. // If output parameter p is specified, fill it with the pointer to the
  1366. // specified entry and throw std::out_of_range if it couldn't be found.
  1367. //
  1368. // Otherwise, just return true if the entry could be found or false
  1369. // otherwise and do not throw.
  1370. bool resolve_qualified(const std::string& key,
  1371. std::shared_ptr<base>* p = nullptr) const
  1372. {
  1373. auto parts = split(key, '.');
  1374. auto last_key = parts.back();
  1375. parts.pop_back();
  1376. auto cur_table = this;
  1377. for (const auto& part : parts)
  1378. {
  1379. cur_table = cur_table->get_table(part).get();
  1380. if (!cur_table)
  1381. {
  1382. if (!p)
  1383. return false;
  1384. throw std::out_of_range{key + " is not a valid key"};
  1385. }
  1386. }
  1387. if (!p)
  1388. return cur_table->map_.count(last_key) != 0;
  1389. *p = cur_table->map_.at(last_key);
  1390. return true;
  1391. }
  1392. string_to_base_map map_;
  1393. };
  1394. /**
  1395. * Helper function that attempts to get an array of arrays for a given
  1396. * key.
  1397. *
  1398. * If the key doesn't exist, doesn't exist as an array type, or one or
  1399. * more keys inside the array type are not of type T, an empty option
  1400. * is returned. Otherwise, an option containing a vector of the values
  1401. * is returned.
  1402. */
  1403. template <>
  1404. inline typename array_of_trait<array>::return_type
  1405. table::get_array_of<array>(const std::string& key) const
  1406. {
  1407. if (auto v = get_array(key))
  1408. {
  1409. std::vector<std::shared_ptr<array>> result;
  1410. result.reserve(v->get().size());
  1411. for (const auto& b : v->get())
  1412. {
  1413. if (auto val = b->as_array())
  1414. result.push_back(val);
  1415. else
  1416. return {};
  1417. }
  1418. return {std::move(result)};
  1419. }
  1420. return {};
  1421. }
  1422. /**
  1423. * Helper function that attempts to get an array of arrays for a given
  1424. * key. Will resolve "qualified keys".
  1425. *
  1426. * If the key doesn't exist, doesn't exist as an array type, or one or
  1427. * more keys inside the array type are not of type T, an empty option
  1428. * is returned. Otherwise, an option containing a vector of the values
  1429. * is returned.
  1430. */
  1431. template <>
  1432. inline typename array_of_trait<array>::return_type
  1433. table::get_qualified_array_of<array>(const std::string& key) const
  1434. {
  1435. if (auto v = get_array_qualified(key))
  1436. {
  1437. std::vector<std::shared_ptr<array>> result;
  1438. result.reserve(v->get().size());
  1439. for (const auto& b : v->get())
  1440. {
  1441. if (auto val = b->as_array())
  1442. result.push_back(val);
  1443. else
  1444. return {};
  1445. }
  1446. return {std::move(result)};
  1447. }
  1448. return {};
  1449. }
  1450. std::shared_ptr<table> make_table()
  1451. {
  1452. struct make_shared_enabler : public table
  1453. {
  1454. make_shared_enabler()
  1455. {
  1456. // nothing
  1457. }
  1458. };
  1459. return std::make_shared<make_shared_enabler>();
  1460. }
  1461. namespace detail
  1462. {
  1463. template <>
  1464. inline std::shared_ptr<table> make_element<table>()
  1465. {
  1466. return make_table();
  1467. }
  1468. } // namespace detail
  1469. template <class T>
  1470. std::shared_ptr<base> value<T>::clone() const
  1471. {
  1472. return make_value(data_);
  1473. }
  1474. inline std::shared_ptr<base> array::clone() const
  1475. {
  1476. auto result = make_array();
  1477. result->reserve(values_.size());
  1478. for (const auto& ptr : values_)
  1479. result->values_.push_back(ptr->clone());
  1480. return result;
  1481. }
  1482. inline std::shared_ptr<base> table_array::clone() const
  1483. {
  1484. auto result = make_table_array(is_inline());
  1485. result->reserve(array_.size());
  1486. for (const auto& ptr : array_)
  1487. result->array_.push_back(ptr->clone()->as_table());
  1488. return result;
  1489. }
  1490. inline std::shared_ptr<base> table::clone() const
  1491. {
  1492. auto result = make_table();
  1493. for (const auto& pr : map_)
  1494. result->insert(pr.first, pr.second->clone());
  1495. return result;
  1496. }
  1497. /**
  1498. * Exception class for all TOML parsing errors.
  1499. */
  1500. class parse_exception : public std::runtime_error
  1501. {
  1502. public:
  1503. parse_exception(const std::string& err) : std::runtime_error{err}
  1504. {
  1505. }
  1506. parse_exception(const std::string& err, std::size_t line_number)
  1507. : std::runtime_error{err + " at line " + std::to_string(line_number)}
  1508. {
  1509. }
  1510. };
  1511. inline bool is_number(char c)
  1512. {
  1513. return c >= '0' && c <= '9';
  1514. }
  1515. inline bool is_hex(char c)
  1516. {
  1517. return is_number(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
  1518. }
  1519. /**
  1520. * Helper object for consuming expected characters.
  1521. */
  1522. template <class OnError>
  1523. class consumer
  1524. {
  1525. public:
  1526. consumer(std::string::iterator& it, const std::string::iterator& end,
  1527. OnError&& on_error)
  1528. : it_(it), end_(end), on_error_(std::forward<OnError>(on_error))
  1529. {
  1530. // nothing
  1531. }
  1532. void operator()(char c)
  1533. {
  1534. if (it_ == end_ || *it_ != c)
  1535. on_error_();
  1536. ++it_;
  1537. }
  1538. template <std::size_t N>
  1539. void operator()(const char (&str)[N])
  1540. {
  1541. std::for_each(std::begin(str), std::end(str) - 1,
  1542. [&](char c) { (*this)(c); });
  1543. }
  1544. void eat_or(char a, char b)
  1545. {
  1546. if (it_ == end_ || (*it_ != a && *it_ != b))
  1547. on_error_();
  1548. ++it_;
  1549. }
  1550. int eat_digits(int len)
  1551. {
  1552. int val = 0;
  1553. for (int i = 0; i < len; ++i)
  1554. {
  1555. if (!is_number(*it_) || it_ == end_)
  1556. on_error_();
  1557. val = 10 * val + (*it_++ - '0');
  1558. }
  1559. return val;
  1560. }
  1561. void error()
  1562. {
  1563. on_error_();
  1564. }
  1565. private:
  1566. std::string::iterator& it_;
  1567. const std::string::iterator& end_;
  1568. OnError on_error_;
  1569. };
  1570. template <class OnError>
  1571. consumer<OnError> make_consumer(std::string::iterator& it,
  1572. const std::string::iterator& end,
  1573. OnError&& on_error)
  1574. {
  1575. return consumer<OnError>(it, end, std::forward<OnError>(on_error));
  1576. }
  1577. // replacement for std::getline to handle incorrectly line-ended files
  1578. // https://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf
  1579. namespace detail
  1580. {
  1581. inline std::istream& getline(std::istream& input, std::string& line)
  1582. {
  1583. line.clear();
  1584. std::istream::sentry sentry{input, true};
  1585. auto sb = input.rdbuf();
  1586. while (true)
  1587. {
  1588. auto c = sb->sbumpc();
  1589. if (c == '\r')
  1590. {
  1591. if (sb->sgetc() == '\n')
  1592. c = sb->sbumpc();
  1593. }
  1594. if (c == '\n')
  1595. return input;
  1596. if (c == std::istream::traits_type::eof())
  1597. {
  1598. if (line.empty())
  1599. input.setstate(std::ios::eofbit);
  1600. return input;
  1601. }
  1602. line.push_back(static_cast<char>(c));
  1603. }
  1604. }
  1605. } // namespace detail
  1606. /**
  1607. * The parser class.
  1608. */
  1609. class parser
  1610. {
  1611. public:
  1612. /**
  1613. * Parsers are constructed from streams.
  1614. */
  1615. parser(std::istream& stream) : input_(stream)
  1616. {
  1617. // nothing
  1618. }
  1619. parser& operator=(const parser& parser) = delete;
  1620. /**
  1621. * Parses the stream this parser was created on until EOF.
  1622. * @throw parse_exception if there are errors in parsing
  1623. */
  1624. std::shared_ptr<table> parse()
  1625. {
  1626. std::shared_ptr<table> root = make_table();
  1627. table* curr_table = root.get();
  1628. while (detail::getline(input_, line_))
  1629. {
  1630. line_number_++;
  1631. auto it = line_.begin();
  1632. auto end = line_.end();
  1633. consume_whitespace(it, end);
  1634. if (it == end || *it == '#')
  1635. continue;
  1636. if (*it == '[')
  1637. {
  1638. curr_table = root.get();
  1639. parse_table(it, end, curr_table);
  1640. }
  1641. else
  1642. {
  1643. parse_key_value(it, end, curr_table);
  1644. consume_whitespace(it, end);
  1645. eol_or_comment(it, end);
  1646. }
  1647. }
  1648. return root;
  1649. }
  1650. private:
  1651. #if defined _MSC_VER
  1652. __declspec(noreturn)
  1653. #elif defined __GNUC__
  1654. __attribute__((noreturn))
  1655. #endif
  1656. void throw_parse_exception(const std::string& err)
  1657. {
  1658. throw parse_exception{err, line_number_};
  1659. }
  1660. void parse_table(std::string::iterator& it,
  1661. const std::string::iterator& end, table*& curr_table)
  1662. {
  1663. // remove the beginning keytable marker
  1664. ++it;
  1665. if (it == end)
  1666. throw_parse_exception("Unexpected end of table");
  1667. if (*it == '[')
  1668. parse_table_array(it, end, curr_table);
  1669. else
  1670. parse_single_table(it, end, curr_table);
  1671. }
  1672. void parse_single_table(std::string::iterator& it,
  1673. const std::string::iterator& end,
  1674. table*& curr_table)
  1675. {
  1676. if (it == end || *it == ']')
  1677. throw_parse_exception("Table name cannot be empty");
  1678. std::string full_table_name;
  1679. bool inserted = false;
  1680. auto key_end = [](char c) { return c == ']'; };
  1681. auto key_part_handler = [&](const std::string& part) {
  1682. if (part.empty())
  1683. throw_parse_exception("Empty component of table name");
  1684. if (!full_table_name.empty())
  1685. full_table_name += '.';
  1686. full_table_name += part;
  1687. if (curr_table->contains(part))
  1688. {
  1689. #if !defined(__PGI)
  1690. auto b = curr_table->get(part);
  1691. #else
  1692. // Workaround for PGI compiler
  1693. std::shared_ptr<base> b = curr_table->get(part);
  1694. #endif
  1695. if (b->is_table())
  1696. curr_table = static_cast<table*>(b.get());
  1697. else if (b->is_table_array())
  1698. curr_table = std::static_pointer_cast<table_array>(b)
  1699. ->get()
  1700. .back()
  1701. .get();
  1702. else
  1703. throw_parse_exception("Key " + full_table_name
  1704. + "already exists as a value");
  1705. }
  1706. else
  1707. {
  1708. inserted = true;
  1709. curr_table->insert(part, make_table());
  1710. curr_table = static_cast<table*>(curr_table->get(part).get());
  1711. }
  1712. };
  1713. key_part_handler(parse_key(it, end, key_end, key_part_handler));
  1714. if (it == end)
  1715. throw_parse_exception(
  1716. "Unterminated table declaration; did you forget a ']'?");
  1717. if (*it != ']')
  1718. {
  1719. std::string errmsg{"Unexpected character in table definition: "};
  1720. errmsg += '"';
  1721. errmsg += *it;
  1722. errmsg += '"';
  1723. throw_parse_exception(errmsg);
  1724. }
  1725. // table already existed
  1726. if (!inserted)
  1727. {
  1728. auto is_value
  1729. = [](const std::pair<const std::string&,
  1730. const std::shared_ptr<base>&>& p) {
  1731. return p.second->is_value();
  1732. };
  1733. // if there are any values, we can't add values to this table
  1734. // since it has already been defined. If there aren't any
  1735. // values, then it was implicitly created by something like
  1736. // [a.b]
  1737. if (curr_table->empty()
  1738. || std::any_of(curr_table->begin(), curr_table->end(),
  1739. is_value))
  1740. {
  1741. throw_parse_exception("Redefinition of table "
  1742. + full_table_name);
  1743. }
  1744. }
  1745. ++it;
  1746. consume_whitespace(it, end);
  1747. eol_or_comment(it, end);
  1748. }
  1749. void parse_table_array(std::string::iterator& it,
  1750. const std::string::iterator& end, table*& curr_table)
  1751. {
  1752. ++it;
  1753. if (it == end || *it == ']')
  1754. throw_parse_exception("Table array name cannot be empty");
  1755. auto key_end = [](char c) { return c == ']'; };
  1756. std::string full_ta_name;
  1757. auto key_part_handler = [&](const std::string& part) {
  1758. if (part.empty())
  1759. throw_parse_exception("Empty component of table array name");
  1760. if (!full_ta_name.empty())
  1761. full_ta_name += '.';
  1762. full_ta_name += part;
  1763. if (curr_table->contains(part))
  1764. {
  1765. #if !defined(__PGI)
  1766. auto b = curr_table->get(part);
  1767. #else
  1768. // Workaround for PGI compiler
  1769. std::shared_ptr<base> b = curr_table->get(part);
  1770. #endif
  1771. // if this is the end of the table array name, add an
  1772. // element to the table array that we just looked up,
  1773. // provided it was not declared inline
  1774. if (it != end && *it == ']')
  1775. {
  1776. if (!b->is_table_array())
  1777. {
  1778. throw_parse_exception("Key " + full_ta_name
  1779. + " is not a table array");
  1780. }
  1781. auto v = b->as_table_array();
  1782. if (v->is_inline())
  1783. {
  1784. throw_parse_exception("Static array " + full_ta_name
  1785. + " cannot be appended to");
  1786. }
  1787. v->get().push_back(make_table());
  1788. curr_table = v->get().back().get();
  1789. }
  1790. // otherwise, just keep traversing down the key name
  1791. else
  1792. {
  1793. if (b->is_table())
  1794. curr_table = static_cast<table*>(b.get());
  1795. else if (b->is_table_array())
  1796. curr_table = std::static_pointer_cast<table_array>(b)
  1797. ->get()
  1798. .back()
  1799. .get();
  1800. else
  1801. throw_parse_exception("Key " + full_ta_name
  1802. + " already exists as a value");
  1803. }
  1804. }
  1805. else
  1806. {
  1807. // if this is the end of the table array name, add a new
  1808. // table array and a new table inside that array for us to
  1809. // add keys to next
  1810. if (it != end && *it == ']')
  1811. {
  1812. curr_table->insert(part, make_table_array());
  1813. auto arr = std::static_pointer_cast<table_array>(
  1814. curr_table->get(part));
  1815. arr->get().push_back(make_table());
  1816. curr_table = arr->get().back().get();
  1817. }
  1818. // otherwise, create the implicitly defined table and move
  1819. // down to it
  1820. else
  1821. {
  1822. curr_table->insert(part, make_table());
  1823. curr_table
  1824. = static_cast<table*>(curr_table->get(part).get());
  1825. }
  1826. }
  1827. };
  1828. key_part_handler(parse_key(it, end, key_end, key_part_handler));
  1829. // consume the last "]]"
  1830. auto eat = make_consumer(it, end, [this]() {
  1831. throw_parse_exception("Unterminated table array name");
  1832. });
  1833. eat(']');
  1834. eat(']');
  1835. consume_whitespace(it, end);
  1836. eol_or_comment(it, end);
  1837. }
  1838. void parse_key_value(std::string::iterator& it, std::string::iterator& end,
  1839. table* curr_table)
  1840. {
  1841. auto key_end = [](char c) { return c == '='; };
  1842. auto key_part_handler = [&](const std::string& part) {
  1843. // two cases: this key part exists already, in which case it must
  1844. // be a table, or it doesn't exist in which case we must create
  1845. // an implicitly defined table
  1846. if (curr_table->contains(part))
  1847. {
  1848. auto val = curr_table->get(part);
  1849. if (val->is_table())
  1850. {
  1851. curr_table = static_cast<table*>(val.get());
  1852. }
  1853. else
  1854. {
  1855. throw_parse_exception("Key " + part
  1856. + " already exists as a value");
  1857. }
  1858. }
  1859. else
  1860. {
  1861. auto newtable = make_table();
  1862. curr_table->insert(part, newtable);
  1863. curr_table = newtable.get();
  1864. }
  1865. };
  1866. auto key = parse_key(it, end, key_end, key_part_handler);
  1867. if (curr_table->contains(key))
  1868. throw_parse_exception("Key " + key + " already present");
  1869. if (it == end || *it != '=')
  1870. throw_parse_exception("Value must follow after a '='");
  1871. ++it;
  1872. consume_whitespace(it, end);
  1873. curr_table->insert(key, parse_value(it, end));
  1874. consume_whitespace(it, end);
  1875. }
  1876. template <class KeyEndFinder, class KeyPartHandler>
  1877. std::string
  1878. parse_key(std::string::iterator& it, const std::string::iterator& end,
  1879. KeyEndFinder&& key_end, KeyPartHandler&& key_part_handler)
  1880. {
  1881. // parse the key as a series of one or more simple-keys joined with '.'
  1882. while (it != end && !key_end(*it))
  1883. {
  1884. auto part = parse_simple_key(it, end);
  1885. consume_whitespace(it, end);
  1886. if (it == end || key_end(*it))
  1887. {
  1888. return part;
  1889. }
  1890. if (*it != '.')
  1891. {
  1892. std::string errmsg{"Unexpected character in key: "};
  1893. errmsg += '"';
  1894. errmsg += *it;
  1895. errmsg += '"';
  1896. throw_parse_exception(errmsg);
  1897. }
  1898. key_part_handler(part);
  1899. // consume the dot
  1900. ++it;
  1901. }
  1902. throw_parse_exception("Unexpected end of key");
  1903. }
  1904. std::string parse_simple_key(std::string::iterator& it,
  1905. const std::string::iterator& end)
  1906. {
  1907. consume_whitespace(it, end);
  1908. if (it == end)
  1909. throw_parse_exception("Unexpected end of key (blank key?)");
  1910. if (*it == '"' || *it == '\'')
  1911. {
  1912. return string_literal(it, end, *it);
  1913. }
  1914. else
  1915. {
  1916. auto bke = std::find_if(it, end, [](char c) {
  1917. return c == '.' || c == '=' || c == ']';
  1918. });
  1919. return parse_bare_key(it, bke);
  1920. }
  1921. }
  1922. std::string parse_bare_key(std::string::iterator& it,
  1923. const std::string::iterator& end)
  1924. {
  1925. if (it == end)
  1926. {
  1927. throw_parse_exception("Bare key missing name");
  1928. }
  1929. auto key_end = end;
  1930. --key_end;
  1931. consume_backwards_whitespace(key_end, it);
  1932. ++key_end;
  1933. std::string key{it, key_end};
  1934. if (std::find(it, key_end, '#') != key_end)
  1935. {
  1936. throw_parse_exception("Bare key " + key + " cannot contain #");
  1937. }
  1938. if (std::find_if(it, key_end,
  1939. [](char c) { return c == ' ' || c == '\t'; })
  1940. != key_end)
  1941. {
  1942. throw_parse_exception("Bare key " + key
  1943. + " cannot contain whitespace");
  1944. }
  1945. if (std::find_if(it, key_end,
  1946. [](char c) { return c == '[' || c == ']'; })
  1947. != key_end)
  1948. {
  1949. throw_parse_exception("Bare key " + key
  1950. + " cannot contain '[' or ']'");
  1951. }
  1952. it = end;
  1953. return key;
  1954. }
  1955. enum class parse_type
  1956. {
  1957. STRING = 1,
  1958. LOCAL_TIME,
  1959. LOCAL_DATE,
  1960. LOCAL_DATETIME,
  1961. OFFSET_DATETIME,
  1962. INT,
  1963. FLOAT,
  1964. BOOL,
  1965. ARRAY,
  1966. INLINE_TABLE
  1967. };
  1968. std::shared_ptr<base> parse_value(std::string::iterator& it,
  1969. std::string::iterator& end)
  1970. {
  1971. parse_type type = determine_value_type(it, end);
  1972. switch (type)
  1973. {
  1974. case parse_type::STRING:
  1975. return parse_string(it, end);
  1976. case parse_type::LOCAL_TIME:
  1977. return parse_time(it, end);
  1978. case parse_type::LOCAL_DATE:
  1979. case parse_type::LOCAL_DATETIME:
  1980. case parse_type::OFFSET_DATETIME:
  1981. return parse_date(it, end);
  1982. case parse_type::INT:
  1983. case parse_type::FLOAT:
  1984. return parse_number(it, end);
  1985. case parse_type::BOOL:
  1986. return parse_bool(it, end);
  1987. case parse_type::ARRAY:
  1988. return parse_array(it, end);
  1989. case parse_type::INLINE_TABLE:
  1990. return parse_inline_table(it, end);
  1991. default:
  1992. throw_parse_exception("Failed to parse value");
  1993. }
  1994. }
  1995. parse_type determine_value_type(const std::string::iterator& it,
  1996. const std::string::iterator& end)
  1997. {
  1998. if (it == end)
  1999. {
  2000. throw_parse_exception("Failed to parse value type");
  2001. }
  2002. if (*it == '"' || *it == '\'')
  2003. {
  2004. return parse_type::STRING;
  2005. }
  2006. else if (is_time(it, end))
  2007. {
  2008. return parse_type::LOCAL_TIME;
  2009. }
  2010. else if (auto dtype = date_type(it, end))
  2011. {
  2012. return *dtype;
  2013. }
  2014. else if (is_number(*it) || *it == '-' || *it == '+'
  2015. || (*it == 'i' && it + 1 != end && it[1] == 'n'
  2016. && it + 2 != end && it[2] == 'f')
  2017. || (*it == 'n' && it + 1 != end && it[1] == 'a'
  2018. && it + 2 != end && it[2] == 'n'))
  2019. {
  2020. return determine_number_type(it, end);
  2021. }
  2022. else if (*it == 't' || *it == 'f')
  2023. {
  2024. return parse_type::BOOL;
  2025. }
  2026. else if (*it == '[')
  2027. {
  2028. return parse_type::ARRAY;
  2029. }
  2030. else if (*it == '{')
  2031. {
  2032. return parse_type::INLINE_TABLE;
  2033. }
  2034. throw_parse_exception("Failed to parse value type");
  2035. }
  2036. parse_type determine_number_type(const std::string::iterator& it,
  2037. const std::string::iterator& end)
  2038. {
  2039. // determine if we are an integer or a float
  2040. auto check_it = it;
  2041. if (*check_it == '-' || *check_it == '+')
  2042. ++check_it;
  2043. if (check_it == end)
  2044. throw_parse_exception("Malformed number");
  2045. if (*check_it == 'i' || *check_it == 'n')
  2046. return parse_type::FLOAT;
  2047. while (check_it != end && is_number(*check_it))
  2048. ++check_it;
  2049. if (check_it != end && *check_it == '.')
  2050. {
  2051. ++check_it;
  2052. while (check_it != end && is_number(*check_it))
  2053. ++check_it;
  2054. return parse_type::FLOAT;
  2055. }
  2056. else
  2057. {
  2058. return parse_type::INT;
  2059. }
  2060. }
  2061. std::shared_ptr<value<std::string>> parse_string(std::string::iterator& it,
  2062. std::string::iterator& end)
  2063. {
  2064. auto delim = *it;
  2065. assert(delim == '"' || delim == '\'');
  2066. // end is non-const here because we have to be able to potentially
  2067. // parse multiple lines in a string, not just one
  2068. auto check_it = it;
  2069. ++check_it;
  2070. if (check_it != end && *check_it == delim)
  2071. {
  2072. ++check_it;
  2073. if (check_it != end && *check_it == delim)
  2074. {
  2075. it = ++check_it;
  2076. return parse_multiline_string(it, end, delim);
  2077. }
  2078. }
  2079. return make_value<std::string>(string_literal(it, end, delim));
  2080. }
  2081. std::shared_ptr<value<std::string>>
  2082. parse_multiline_string(std::string::iterator& it,
  2083. std::string::iterator& end, char delim)
  2084. {
  2085. std::stringstream ss;
  2086. auto is_ws = [](char c) { return c == ' ' || c == '\t'; };
  2087. bool consuming = false;
  2088. std::shared_ptr<value<std::string>> ret;
  2089. auto handle_line = [&](std::string::iterator& local_it,
  2090. std::string::iterator& local_end) {
  2091. if (consuming)
  2092. {
  2093. local_it = std::find_if_not(local_it, local_end, is_ws);
  2094. // whole line is whitespace
  2095. if (local_it == local_end)
  2096. return;
  2097. }
  2098. consuming = false;
  2099. while (local_it != local_end)
  2100. {
  2101. // handle escaped characters
  2102. if (delim == '"' && *local_it == '\\')
  2103. {
  2104. auto check = local_it;
  2105. // check if this is an actual escape sequence or a
  2106. // whitespace escaping backslash
  2107. ++check;
  2108. consume_whitespace(check, local_end);
  2109. if (check == local_end)
  2110. {
  2111. consuming = true;
  2112. break;
  2113. }
  2114. ss << parse_escape_code(local_it, local_end);
  2115. continue;
  2116. }
  2117. // if we can end the string
  2118. if (std::distance(local_it, local_end) >= 3)
  2119. {
  2120. auto check = local_it;
  2121. // check for """
  2122. if (*check++ == delim && *check++ == delim
  2123. && *check++ == delim)
  2124. {
  2125. local_it = check;
  2126. ret = make_value<std::string>(ss.str());
  2127. break;
  2128. }
  2129. }
  2130. ss << *local_it++;
  2131. }
  2132. };
  2133. // handle the remainder of the current line
  2134. handle_line(it, end);
  2135. if (ret)
  2136. return ret;
  2137. // start eating lines
  2138. while (detail::getline(input_, line_))
  2139. {
  2140. ++line_number_;
  2141. it = line_.begin();
  2142. end = line_.end();
  2143. handle_line(it, end);
  2144. if (ret)
  2145. return ret;
  2146. if (!consuming)
  2147. ss << std::endl;
  2148. }
  2149. throw_parse_exception("Unterminated multi-line basic string");
  2150. }
  2151. std::string string_literal(std::string::iterator& it,
  2152. const std::string::iterator& end, char delim)
  2153. {
  2154. ++it;
  2155. std::string val;
  2156. while (it != end)
  2157. {
  2158. // handle escaped characters
  2159. if (delim == '"' && *it == '\\')
  2160. {
  2161. val += parse_escape_code(it, end);
  2162. }
  2163. else if (*it == delim)
  2164. {
  2165. ++it;
  2166. consume_whitespace(it, end);
  2167. return val;
  2168. }
  2169. else
  2170. {
  2171. val += *it++;
  2172. }
  2173. }
  2174. throw_parse_exception("Unterminated string literal");
  2175. }
  2176. std::string parse_escape_code(std::string::iterator& it,
  2177. const std::string::iterator& end)
  2178. {
  2179. ++it;
  2180. if (it == end)
  2181. throw_parse_exception("Invalid escape sequence");
  2182. char value;
  2183. if (*it == 'b')
  2184. {
  2185. value = '\b';
  2186. }
  2187. else if (*it == 't')
  2188. {
  2189. value = '\t';
  2190. }
  2191. else if (*it == 'n')
  2192. {
  2193. value = '\n';
  2194. }
  2195. else if (*it == 'f')
  2196. {
  2197. value = '\f';
  2198. }
  2199. else if (*it == 'r')
  2200. {
  2201. value = '\r';
  2202. }
  2203. else if (*it == '"')
  2204. {
  2205. value = '"';
  2206. }
  2207. else if (*it == '\\')
  2208. {
  2209. value = '\\';
  2210. }
  2211. else if (*it == 'u' || *it == 'U')
  2212. {
  2213. return parse_unicode(it, end);
  2214. }
  2215. else
  2216. {
  2217. throw_parse_exception("Invalid escape sequence");
  2218. }
  2219. ++it;
  2220. return std::string(1, value);
  2221. }
  2222. std::string parse_unicode(std::string::iterator& it,
  2223. const std::string::iterator& end)
  2224. {
  2225. bool large = *it++ == 'U';
  2226. auto codepoint = parse_hex(it, end, large ? 0x10000000 : 0x1000);
  2227. if ((codepoint > 0xd7ff && codepoint < 0xe000) || codepoint > 0x10ffff)
  2228. {
  2229. throw_parse_exception(
  2230. "Unicode escape sequence is not a Unicode scalar value");
  2231. }
  2232. std::string result;
  2233. // See Table 3-6 of the Unicode standard
  2234. if (codepoint <= 0x7f)
  2235. {
  2236. // 1-byte codepoints: 00000000 0xxxxxxx
  2237. // repr: 0xxxxxxx
  2238. result += static_cast<char>(codepoint & 0x7f);
  2239. }
  2240. else if (codepoint <= 0x7ff)
  2241. {
  2242. // 2-byte codepoints: 00000yyy yyxxxxxx
  2243. // repr: 110yyyyy 10xxxxxx
  2244. //
  2245. // 0x1f = 00011111
  2246. // 0xc0 = 11000000
  2247. //
  2248. result += static_cast<char>(0xc0 | ((codepoint >> 6) & 0x1f));
  2249. //
  2250. // 0x80 = 10000000
  2251. // 0x3f = 00111111
  2252. //
  2253. result += static_cast<char>(0x80 | (codepoint & 0x3f));
  2254. }
  2255. else if (codepoint <= 0xffff)
  2256. {
  2257. // 3-byte codepoints: zzzzyyyy yyxxxxxx
  2258. // repr: 1110zzzz 10yyyyyy 10xxxxxx
  2259. //
  2260. // 0xe0 = 11100000
  2261. // 0x0f = 00001111
  2262. //
  2263. result += static_cast<char>(0xe0 | ((codepoint >> 12) & 0x0f));
  2264. result += static_cast<char>(0x80 | ((codepoint >> 6) & 0x1f));
  2265. result += static_cast<char>(0x80 | (codepoint & 0x3f));
  2266. }
  2267. else
  2268. {
  2269. // 4-byte codepoints: 000uuuuu zzzzyyyy yyxxxxxx
  2270. // repr: 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx
  2271. //
  2272. // 0xf0 = 11110000
  2273. // 0x07 = 00000111
  2274. //
  2275. result += static_cast<char>(0xf0 | ((codepoint >> 18) & 0x07));
  2276. result += static_cast<char>(0x80 | ((codepoint >> 12) & 0x3f));
  2277. result += static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f));
  2278. result += static_cast<char>(0x80 | (codepoint & 0x3f));
  2279. }
  2280. return result;
  2281. }
  2282. uint32_t parse_hex(std::string::iterator& it,
  2283. const std::string::iterator& end, uint32_t place)
  2284. {
  2285. uint32_t value = 0;
  2286. while (place > 0)
  2287. {
  2288. if (it == end)
  2289. throw_parse_exception("Unexpected end of unicode sequence");
  2290. if (!is_hex(*it))
  2291. throw_parse_exception("Invalid unicode escape sequence");
  2292. value += place * hex_to_digit(*it++);
  2293. place /= 16;
  2294. }
  2295. return value;
  2296. }
  2297. uint32_t hex_to_digit(char c)
  2298. {
  2299. if (is_number(c))
  2300. return static_cast<uint32_t>(c - '0');
  2301. return 10
  2302. + static_cast<uint32_t>(c
  2303. - ((c >= 'a' && c <= 'f') ? 'a' : 'A'));
  2304. }
  2305. std::shared_ptr<base> parse_number(std::string::iterator& it,
  2306. const std::string::iterator& end)
  2307. {
  2308. auto check_it = it;
  2309. auto check_end = find_end_of_number(it, end);
  2310. auto eat_sign = [&]() {
  2311. if (check_it != end && (*check_it == '-' || *check_it == '+'))
  2312. ++check_it;
  2313. };
  2314. auto check_no_leading_zero = [&]() {
  2315. if (check_it != end && *check_it == '0' && check_it + 1 != check_end
  2316. && check_it[1] != '.')
  2317. {
  2318. throw_parse_exception("Numbers may not have leading zeros");
  2319. }
  2320. };
  2321. auto eat_digits = [&](bool (*check_char)(char)) {
  2322. auto beg = check_it;
  2323. while (check_it != end && check_char(*check_it))
  2324. {
  2325. ++check_it;
  2326. if (check_it != end && *check_it == '_')
  2327. {
  2328. ++check_it;
  2329. if (check_it == end || !check_char(*check_it))
  2330. throw_parse_exception("Malformed number");
  2331. }
  2332. }
  2333. if (check_it == beg)
  2334. throw_parse_exception("Malformed number");
  2335. };
  2336. auto eat_hex = [&]() { eat_digits(&is_hex); };
  2337. auto eat_numbers = [&]() { eat_digits(&is_number); };
  2338. if (check_it != end && *check_it == '0' && check_it + 1 != check_end
  2339. && (check_it[1] == 'x' || check_it[1] == 'o' || check_it[1] == 'b'))
  2340. {
  2341. ++check_it;
  2342. char base = *check_it;
  2343. ++check_it;
  2344. if (base == 'x')
  2345. {
  2346. eat_hex();
  2347. return parse_int(it, check_it, 16);
  2348. }
  2349. else if (base == 'o')
  2350. {
  2351. auto start = check_it;
  2352. eat_numbers();
  2353. auto val = parse_int(start, check_it, 8, "0");
  2354. it = start;
  2355. return val;
  2356. }
  2357. else // if (base == 'b')
  2358. {
  2359. auto start = check_it;
  2360. eat_numbers();
  2361. auto val = parse_int(start, check_it, 2);
  2362. it = start;
  2363. return val;
  2364. }
  2365. }
  2366. eat_sign();
  2367. check_no_leading_zero();
  2368. if (check_it != end && check_it + 1 != end && check_it + 2 != end)
  2369. {
  2370. if (check_it[0] == 'i' && check_it[1] == 'n' && check_it[2] == 'f')
  2371. {
  2372. auto val = std::numeric_limits<double>::infinity();
  2373. if (*it == '-')
  2374. val = -val;
  2375. it = check_it + 3;
  2376. return make_value(val);
  2377. }
  2378. else if (check_it[0] == 'n' && check_it[1] == 'a'
  2379. && check_it[2] == 'n')
  2380. {
  2381. auto val = std::numeric_limits<double>::quiet_NaN();
  2382. if (*it == '-')
  2383. val = -val;
  2384. it = check_it + 3;
  2385. return make_value(val);
  2386. }
  2387. }
  2388. eat_numbers();
  2389. if (check_it != end
  2390. && (*check_it == '.' || *check_it == 'e' || *check_it == 'E'))
  2391. {
  2392. bool is_exp = *check_it == 'e' || *check_it == 'E';
  2393. ++check_it;
  2394. if (check_it == end)
  2395. throw_parse_exception("Floats must have trailing digits");
  2396. auto eat_exp = [&]() {
  2397. eat_sign();
  2398. check_no_leading_zero();
  2399. eat_numbers();
  2400. };
  2401. if (is_exp)
  2402. eat_exp();
  2403. else
  2404. eat_numbers();
  2405. if (!is_exp && check_it != end
  2406. && (*check_it == 'e' || *check_it == 'E'))
  2407. {
  2408. ++check_it;
  2409. eat_exp();
  2410. }
  2411. return parse_float(it, check_it);
  2412. }
  2413. else
  2414. {
  2415. return parse_int(it, check_it);
  2416. }
  2417. }
  2418. std::shared_ptr<value<int64_t>> parse_int(std::string::iterator& it,
  2419. const std::string::iterator& end,
  2420. int base = 10,
  2421. const char* prefix = "")
  2422. {
  2423. std::string v{it, end};
  2424. v = prefix + v;
  2425. v.erase(std::remove(v.begin(), v.end(), '_'), v.end());
  2426. it = end;
  2427. try
  2428. {
  2429. return make_value<int64_t>(std::stoll(v, nullptr, base));
  2430. }
  2431. catch (const std::invalid_argument& ex)
  2432. {
  2433. throw_parse_exception("Malformed number (invalid argument: "
  2434. + std::string{ex.what()} + ")");
  2435. }
  2436. catch (const std::out_of_range& ex)
  2437. {
  2438. throw_parse_exception("Malformed number (out of range: "
  2439. + std::string{ex.what()} + ")");
  2440. }
  2441. }
  2442. std::shared_ptr<value<double>> parse_float(std::string::iterator& it,
  2443. const std::string::iterator& end)
  2444. {
  2445. std::string v{it, end};
  2446. v.erase(std::remove(v.begin(), v.end(), '_'), v.end());
  2447. it = end;
  2448. char decimal_point = std::localeconv()->decimal_point[0];
  2449. std::replace(v.begin(), v.end(), '.', decimal_point);
  2450. try
  2451. {
  2452. return make_value<double>(std::stod(v));
  2453. }
  2454. catch (const std::invalid_argument& ex)
  2455. {
  2456. throw_parse_exception("Malformed number (invalid argument: "
  2457. + std::string{ex.what()} + ")");
  2458. }
  2459. catch (const std::out_of_range& ex)
  2460. {
  2461. throw_parse_exception("Malformed number (out of range: "
  2462. + std::string{ex.what()} + ")");
  2463. }
  2464. }
  2465. std::shared_ptr<value<bool>> parse_bool(std::string::iterator& it,
  2466. const std::string::iterator& end)
  2467. {
  2468. auto eat = make_consumer(it, end, [this]() {
  2469. throw_parse_exception("Attempted to parse invalid boolean value");
  2470. });
  2471. if (*it == 't')
  2472. {
  2473. eat("true");
  2474. return make_value<bool>(true);
  2475. }
  2476. else if (*it == 'f')
  2477. {
  2478. eat("false");
  2479. return make_value<bool>(false);
  2480. }
  2481. eat.error();
  2482. return nullptr;
  2483. }
  2484. std::string::iterator find_end_of_number(std::string::iterator it,
  2485. std::string::iterator end)
  2486. {
  2487. auto ret = std::find_if(it, end, [](char c) {
  2488. return !is_number(c) && c != '_' && c != '.' && c != 'e' && c != 'E'
  2489. && c != '-' && c != '+' && c != 'x' && c != 'o' && c != 'b';
  2490. });
  2491. if (ret != end && ret + 1 != end && ret + 2 != end)
  2492. {
  2493. if ((ret[0] == 'i' && ret[1] == 'n' && ret[2] == 'f')
  2494. || (ret[0] == 'n' && ret[1] == 'a' && ret[2] == 'n'))
  2495. {
  2496. ret = ret + 3;
  2497. }
  2498. }
  2499. return ret;
  2500. }
  2501. std::string::iterator find_end_of_date(std::string::iterator it,
  2502. std::string::iterator end)
  2503. {
  2504. auto end_of_date = std::find_if(it, end, [](char c) {
  2505. return !is_number(c) && c != '-';
  2506. });
  2507. if (end_of_date != end && *end_of_date == ' ' && end_of_date + 1 != end
  2508. && is_number(end_of_date[1]))
  2509. end_of_date++;
  2510. return std::find_if(end_of_date, end, [](char c) {
  2511. return !is_number(c) && c != 'T' && c != 'Z' && c != ':'
  2512. && c != '-' && c != '+' && c != '.';
  2513. });
  2514. }
  2515. std::string::iterator find_end_of_time(std::string::iterator it,
  2516. std::string::iterator end)
  2517. {
  2518. return std::find_if(it, end, [](char c) {
  2519. return !is_number(c) && c != ':' && c != '.';
  2520. });
  2521. }
  2522. local_time read_time(std::string::iterator& it,
  2523. const std::string::iterator& end)
  2524. {
  2525. auto time_end = find_end_of_time(it, end);
  2526. auto eat = make_consumer(
  2527. it, time_end, [&]() { throw_parse_exception("Malformed time"); });
  2528. local_time ltime;
  2529. ltime.hour = eat.eat_digits(2);
  2530. eat(':');
  2531. ltime.minute = eat.eat_digits(2);
  2532. eat(':');
  2533. ltime.second = eat.eat_digits(2);
  2534. int power = 100000;
  2535. if (it != time_end && *it == '.')
  2536. {
  2537. ++it;
  2538. while (it != time_end && is_number(*it))
  2539. {
  2540. ltime.microsecond += power * (*it++ - '0');
  2541. power /= 10;
  2542. }
  2543. }
  2544. if (it != time_end)
  2545. throw_parse_exception("Malformed time");
  2546. return ltime;
  2547. }
  2548. std::shared_ptr<value<local_time>>
  2549. parse_time(std::string::iterator& it, const std::string::iterator& end)
  2550. {
  2551. return make_value(read_time(it, end));
  2552. }
  2553. std::shared_ptr<base> parse_date(std::string::iterator& it,
  2554. const std::string::iterator& end)
  2555. {
  2556. auto date_end = find_end_of_date(it, end);
  2557. auto eat = make_consumer(
  2558. it, date_end, [&]() { throw_parse_exception("Malformed date"); });
  2559. local_date ldate;
  2560. ldate.year = eat.eat_digits(4);
  2561. eat('-');
  2562. ldate.month = eat.eat_digits(2);
  2563. eat('-');
  2564. ldate.day = eat.eat_digits(2);
  2565. if (it == date_end)
  2566. return make_value(ldate);
  2567. eat.eat_or('T', ' ');
  2568. local_datetime ldt;
  2569. static_cast<local_date&>(ldt) = ldate;
  2570. static_cast<local_time&>(ldt) = read_time(it, date_end);
  2571. if (it == date_end)
  2572. return make_value(ldt);
  2573. offset_datetime dt;
  2574. static_cast<local_datetime&>(dt) = ldt;
  2575. int hoff = 0;
  2576. int moff = 0;
  2577. if (*it == '+' || *it == '-')
  2578. {
  2579. auto plus = *it == '+';
  2580. ++it;
  2581. hoff = eat.eat_digits(2);
  2582. dt.hour_offset = (plus) ? hoff : -hoff;
  2583. eat(':');
  2584. moff = eat.eat_digits(2);
  2585. dt.minute_offset = (plus) ? moff : -moff;
  2586. }
  2587. else if (*it == 'Z')
  2588. {
  2589. ++it;
  2590. }
  2591. if (it != date_end)
  2592. throw_parse_exception("Malformed date");
  2593. return make_value(dt);
  2594. }
  2595. std::shared_ptr<base> parse_array(std::string::iterator& it,
  2596. std::string::iterator& end)
  2597. {
  2598. // this gets ugly because of the "homogeneity" restriction:
  2599. // arrays can either be of only one type, or contain arrays
  2600. // (each of those arrays could be of different types, though)
  2601. //
  2602. // because of the latter portion, we don't really have a choice
  2603. // but to represent them as arrays of base values...
  2604. ++it;
  2605. // ugh---have to read the first value to determine array type...
  2606. skip_whitespace_and_comments(it, end);
  2607. // edge case---empty array
  2608. if (*it == ']')
  2609. {
  2610. ++it;
  2611. return make_array();
  2612. }
  2613. auto val_end = std::find_if(
  2614. it, end, [](char c) { return c == ',' || c == ']' || c == '#'; });
  2615. parse_type type = determine_value_type(it, val_end);
  2616. switch (type)
  2617. {
  2618. case parse_type::STRING:
  2619. return parse_value_array<std::string>(it, end);
  2620. case parse_type::LOCAL_TIME:
  2621. return parse_value_array<local_time>(it, end);
  2622. case parse_type::LOCAL_DATE:
  2623. return parse_value_array<local_date>(it, end);
  2624. case parse_type::LOCAL_DATETIME:
  2625. return parse_value_array<local_datetime>(it, end);
  2626. case parse_type::OFFSET_DATETIME:
  2627. return parse_value_array<offset_datetime>(it, end);
  2628. case parse_type::INT:
  2629. return parse_value_array<int64_t>(it, end);
  2630. case parse_type::FLOAT:
  2631. return parse_value_array<double>(it, end);
  2632. case parse_type::BOOL:
  2633. return parse_value_array<bool>(it, end);
  2634. case parse_type::ARRAY:
  2635. return parse_object_array<array>(&parser::parse_array, '[', it,
  2636. end);
  2637. case parse_type::INLINE_TABLE:
  2638. return parse_object_array<table_array>(
  2639. &parser::parse_inline_table, '{', it, end);
  2640. default:
  2641. throw_parse_exception("Unable to parse array");
  2642. }
  2643. }
  2644. template <class Value>
  2645. std::shared_ptr<array> parse_value_array(std::string::iterator& it,
  2646. std::string::iterator& end)
  2647. {
  2648. auto arr = make_array();
  2649. while (it != end && *it != ']')
  2650. {
  2651. auto val = parse_value(it, end);
  2652. if (auto v = val->as<Value>())
  2653. arr->get().push_back(val);
  2654. else
  2655. throw_parse_exception("Arrays must be homogeneous");
  2656. skip_whitespace_and_comments(it, end);
  2657. if (*it != ',')
  2658. break;
  2659. ++it;
  2660. skip_whitespace_and_comments(it, end);
  2661. }
  2662. if (it != end)
  2663. ++it;
  2664. return arr;
  2665. }
  2666. template <class Object, class Function>
  2667. std::shared_ptr<Object> parse_object_array(Function&& fun, char delim,
  2668. std::string::iterator& it,
  2669. std::string::iterator& end)
  2670. {
  2671. auto arr = detail::make_element<Object>();
  2672. while (it != end && *it != ']')
  2673. {
  2674. if (*it != delim)
  2675. throw_parse_exception("Unexpected character in array");
  2676. arr->get().push_back(((*this).*fun)(it, end));
  2677. skip_whitespace_and_comments(it, end);
  2678. if (it == end || *it != ',')
  2679. break;
  2680. ++it;
  2681. skip_whitespace_and_comments(it, end);
  2682. }
  2683. if (it == end || *it != ']')
  2684. throw_parse_exception("Unterminated array");
  2685. ++it;
  2686. return arr;
  2687. }
  2688. std::shared_ptr<table> parse_inline_table(std::string::iterator& it,
  2689. std::string::iterator& end)
  2690. {
  2691. auto tbl = make_table();
  2692. do
  2693. {
  2694. ++it;
  2695. if (it == end)
  2696. throw_parse_exception("Unterminated inline table");
  2697. consume_whitespace(it, end);
  2698. if (it != end && *it != '}')
  2699. {
  2700. parse_key_value(it, end, tbl.get());
  2701. consume_whitespace(it, end);
  2702. }
  2703. } while (*it == ',');
  2704. if (it == end || *it != '}')
  2705. throw_parse_exception("Unterminated inline table");
  2706. ++it;
  2707. consume_whitespace(it, end);
  2708. return tbl;
  2709. }
  2710. void skip_whitespace_and_comments(std::string::iterator& start,
  2711. std::string::iterator& end)
  2712. {
  2713. consume_whitespace(start, end);
  2714. while (start == end || *start == '#')
  2715. {
  2716. if (!detail::getline(input_, line_))
  2717. throw_parse_exception("Unclosed array");
  2718. line_number_++;
  2719. start = line_.begin();
  2720. end = line_.end();
  2721. consume_whitespace(start, end);
  2722. }
  2723. }
  2724. void consume_whitespace(std::string::iterator& it,
  2725. const std::string::iterator& end)
  2726. {
  2727. while (it != end && (*it == ' ' || *it == '\t'))
  2728. ++it;
  2729. }
  2730. void consume_backwards_whitespace(std::string::iterator& back,
  2731. const std::string::iterator& front)
  2732. {
  2733. while (back != front && (*back == ' ' || *back == '\t'))
  2734. --back;
  2735. }
  2736. void eol_or_comment(const std::string::iterator& it,
  2737. const std::string::iterator& end)
  2738. {
  2739. if (it != end && *it != '#')
  2740. throw_parse_exception("Unidentified trailing character '"
  2741. + std::string{*it}
  2742. + "'---did you forget a '#'?");
  2743. }
  2744. bool is_time(const std::string::iterator& it,
  2745. const std::string::iterator& end)
  2746. {
  2747. auto time_end = find_end_of_time(it, end);
  2748. auto len = std::distance(it, time_end);
  2749. if (len < 8)
  2750. return false;
  2751. if (it[2] != ':' || it[5] != ':')
  2752. return false;
  2753. if (len > 8)
  2754. return it[8] == '.' && len > 9;
  2755. return true;
  2756. }
  2757. option<parse_type> date_type(const std::string::iterator& it,
  2758. const std::string::iterator& end)
  2759. {
  2760. auto date_end = find_end_of_date(it, end);
  2761. auto len = std::distance(it, date_end);
  2762. if (len < 10)
  2763. return {};
  2764. if (it[4] != '-' || it[7] != '-')
  2765. return {};
  2766. if (len >= 19 && (it[10] == 'T' || it[10] == ' ')
  2767. && is_time(it + 11, date_end))
  2768. {
  2769. // datetime type
  2770. auto time_end = find_end_of_time(it + 11, date_end);
  2771. if (time_end == date_end)
  2772. return {parse_type::LOCAL_DATETIME};
  2773. else
  2774. return {parse_type::OFFSET_DATETIME};
  2775. }
  2776. else if (len == 10)
  2777. {
  2778. // just a regular date
  2779. return {parse_type::LOCAL_DATE};
  2780. }
  2781. return {};
  2782. }
  2783. std::istream& input_;
  2784. std::string line_;
  2785. std::size_t line_number_ = 0;
  2786. };
  2787. /**
  2788. * Utility function to parse a file as a TOML file. Returns the root table.
  2789. * Throws a parse_exception if the file cannot be opened.
  2790. */
  2791. inline std::shared_ptr<table> parse_file(const std::string& filename)
  2792. {
  2793. #if defined(BOOST_NOWIDE_FSTREAM_INCLUDED_HPP)
  2794. boost::nowide::ifstream file{filename.c_str()};
  2795. #elif defined(NOWIDE_FSTREAM_INCLUDED_HPP)
  2796. nowide::ifstream file{filename.c_str()};
  2797. #else
  2798. std::ifstream file{filename};
  2799. #endif
  2800. if (!file.is_open())
  2801. throw parse_exception{filename + " could not be opened for parsing"};
  2802. parser p{file};
  2803. return p.parse();
  2804. }
  2805. template <class... Ts>
  2806. struct value_accept;
  2807. template <>
  2808. struct value_accept<>
  2809. {
  2810. template <class Visitor, class... Args>
  2811. static void accept(const base&, Visitor&&, Args&&...)
  2812. {
  2813. // nothing
  2814. }
  2815. };
  2816. template <class T, class... Ts>
  2817. struct value_accept<T, Ts...>
  2818. {
  2819. template <class Visitor, class... Args>
  2820. static void accept(const base& b, Visitor&& visitor, Args&&... args)
  2821. {
  2822. if (auto v = b.as<T>())
  2823. {
  2824. visitor.visit(*v, std::forward<Args>(args)...);
  2825. }
  2826. else
  2827. {
  2828. value_accept<Ts...>::accept(b, std::forward<Visitor>(visitor),
  2829. std::forward<Args>(args)...);
  2830. }
  2831. }
  2832. };
  2833. /**
  2834. * base implementation of accept() that calls visitor.visit() on the concrete
  2835. * class.
  2836. */
  2837. template <class Visitor, class... Args>
  2838. void base::accept(Visitor&& visitor, Args&&... args) const
  2839. {
  2840. if (is_value())
  2841. {
  2842. using value_acceptor
  2843. = value_accept<std::string, int64_t, double, bool, local_date,
  2844. local_time, local_datetime, offset_datetime>;
  2845. value_acceptor::accept(*this, std::forward<Visitor>(visitor),
  2846. std::forward<Args>(args)...);
  2847. }
  2848. else if (is_table())
  2849. {
  2850. visitor.visit(static_cast<const table&>(*this),
  2851. std::forward<Args>(args)...);
  2852. }
  2853. else if (is_array())
  2854. {
  2855. visitor.visit(static_cast<const array&>(*this),
  2856. std::forward<Args>(args)...);
  2857. }
  2858. else if (is_table_array())
  2859. {
  2860. visitor.visit(static_cast<const table_array&>(*this),
  2861. std::forward<Args>(args)...);
  2862. }
  2863. }
  2864. /**
  2865. * Writer that can be passed to accept() functions of cpptoml objects and
  2866. * will output valid TOML to a stream.
  2867. */
  2868. class toml_writer
  2869. {
  2870. public:
  2871. /**
  2872. * Construct a toml_writer that will write to the given stream
  2873. */
  2874. toml_writer(std::ostream& s, const std::string& indent_space = "\t")
  2875. : stream_(s), indent_(indent_space), has_naked_endline_(false)
  2876. {
  2877. // nothing
  2878. }
  2879. public:
  2880. /**
  2881. * Output a base value of the TOML tree.
  2882. */
  2883. template <class T>
  2884. void visit(const value<T>& v, bool = false)
  2885. {
  2886. write(v);
  2887. }
  2888. /**
  2889. * Output a table element of the TOML tree
  2890. */
  2891. void visit(const table& t, bool in_array = false)
  2892. {
  2893. write_table_header(in_array);
  2894. std::vector<std::string> values;
  2895. std::vector<std::string> tables;
  2896. for (const auto& i : t)
  2897. {
  2898. if (i.second->is_table() || i.second->is_table_array())
  2899. {
  2900. tables.push_back(i.first);
  2901. }
  2902. else
  2903. {
  2904. values.push_back(i.first);
  2905. }
  2906. }
  2907. for (unsigned int i = 0; i < values.size(); ++i)
  2908. {
  2909. path_.push_back(values[i]);
  2910. if (i > 0)
  2911. endline();
  2912. write_table_item_header(*t.get(values[i]));
  2913. t.get(values[i])->accept(*this, false);
  2914. path_.pop_back();
  2915. }
  2916. for (unsigned int i = 0; i < tables.size(); ++i)
  2917. {
  2918. path_.push_back(tables[i]);
  2919. if (values.size() > 0 || i > 0)
  2920. endline();
  2921. write_table_item_header(*t.get(tables[i]));
  2922. t.get(tables[i])->accept(*this, false);
  2923. path_.pop_back();
  2924. }
  2925. endline();
  2926. }
  2927. /**
  2928. * Output an array element of the TOML tree
  2929. */
  2930. void visit(const array& a, bool = false)
  2931. {
  2932. write("[");
  2933. for (unsigned int i = 0; i < a.get().size(); ++i)
  2934. {
  2935. if (i > 0)
  2936. write(", ");
  2937. if (a.get()[i]->is_array())
  2938. {
  2939. a.get()[i]->as_array()->accept(*this, true);
  2940. }
  2941. else
  2942. {
  2943. a.get()[i]->accept(*this, true);
  2944. }
  2945. }
  2946. write("]");
  2947. }
  2948. /**
  2949. * Output a table_array element of the TOML tree
  2950. */
  2951. void visit(const table_array& t, bool = false)
  2952. {
  2953. for (unsigned int j = 0; j < t.get().size(); ++j)
  2954. {
  2955. if (j > 0)
  2956. endline();
  2957. t.get()[j]->accept(*this, true);
  2958. }
  2959. endline();
  2960. }
  2961. /**
  2962. * Escape a string for output.
  2963. */
  2964. static std::string escape_string(const std::string& str)
  2965. {
  2966. std::string res;
  2967. for (auto it = str.begin(); it != str.end(); ++it)
  2968. {
  2969. if (*it == '\b')
  2970. {
  2971. res += "\\b";
  2972. }
  2973. else if (*it == '\t')
  2974. {
  2975. res += "\\t";
  2976. }
  2977. else if (*it == '\n')
  2978. {
  2979. res += "\\n";
  2980. }
  2981. else if (*it == '\f')
  2982. {
  2983. res += "\\f";
  2984. }
  2985. else if (*it == '\r')
  2986. {
  2987. res += "\\r";
  2988. }
  2989. else if (*it == '"')
  2990. {
  2991. res += "\\\"";
  2992. }
  2993. else if (*it == '\\')
  2994. {
  2995. res += "\\\\";
  2996. }
  2997. else if (static_cast<uint32_t>(*it) <= UINT32_C(0x001f))
  2998. {
  2999. res += "\\u";
  3000. std::stringstream ss;
  3001. ss << std::hex << static_cast<uint32_t>(*it);
  3002. res += ss.str();
  3003. }
  3004. else
  3005. {
  3006. res += *it;
  3007. }
  3008. }
  3009. return res;
  3010. }
  3011. protected:
  3012. /**
  3013. * Write out a string.
  3014. */
  3015. void write(const value<std::string>& v)
  3016. {
  3017. write("\"");
  3018. write(escape_string(v.get()));
  3019. write("\"");
  3020. }
  3021. /**
  3022. * Write out a double.
  3023. */
  3024. void write(const value<double>& v)
  3025. {
  3026. std::stringstream ss;
  3027. ss << std::showpoint
  3028. << std::setprecision(std::numeric_limits<double>::max_digits10)
  3029. << v.get();
  3030. auto double_str = ss.str();
  3031. auto pos = double_str.find("e0");
  3032. if (pos != std::string::npos)
  3033. double_str.replace(pos, 2, "e");
  3034. pos = double_str.find("e-0");
  3035. if (pos != std::string::npos)
  3036. double_str.replace(pos, 3, "e-");
  3037. stream_ << double_str;
  3038. has_naked_endline_ = false;
  3039. }
  3040. /**
  3041. * Write out an integer, local_date, local_time, local_datetime, or
  3042. * offset_datetime.
  3043. */
  3044. template <class T>
  3045. typename std::enable_if<
  3046. is_one_of<T, int64_t, local_date, local_time, local_datetime,
  3047. offset_datetime>::value>::type
  3048. write(const value<T>& v)
  3049. {
  3050. write(v.get());
  3051. }
  3052. /**
  3053. * Write out a boolean.
  3054. */
  3055. void write(const value<bool>& v)
  3056. {
  3057. write((v.get() ? "true" : "false"));
  3058. }
  3059. /**
  3060. * Write out the header of a table.
  3061. */
  3062. void write_table_header(bool in_array = false)
  3063. {
  3064. if (!path_.empty())
  3065. {
  3066. indent();
  3067. write("[");
  3068. if (in_array)
  3069. {
  3070. write("[");
  3071. }
  3072. for (unsigned int i = 0; i < path_.size(); ++i)
  3073. {
  3074. if (i > 0)
  3075. {
  3076. write(".");
  3077. }
  3078. if (path_[i].find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcde"
  3079. "fghijklmnopqrstuvwxyz0123456789"
  3080. "_-")
  3081. == std::string::npos)
  3082. {
  3083. write(path_[i]);
  3084. }
  3085. else
  3086. {
  3087. write("\"");
  3088. write(escape_string(path_[i]));
  3089. write("\"");
  3090. }
  3091. }
  3092. if (in_array)
  3093. {
  3094. write("]");
  3095. }
  3096. write("]");
  3097. endline();
  3098. }
  3099. }
  3100. /**
  3101. * Write out the identifier for an item in a table.
  3102. */
  3103. void write_table_item_header(const base& b)
  3104. {
  3105. if (!b.is_table() && !b.is_table_array())
  3106. {
  3107. indent();
  3108. if (path_.back().find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcde"
  3109. "fghijklmnopqrstuvwxyz0123456789"
  3110. "_-")
  3111. == std::string::npos)
  3112. {
  3113. write(path_.back());
  3114. }
  3115. else
  3116. {
  3117. write("\"");
  3118. write(escape_string(path_.back()));
  3119. write("\"");
  3120. }
  3121. write(" = ");
  3122. }
  3123. }
  3124. private:
  3125. /**
  3126. * Indent the proper number of tabs given the size of
  3127. * the path.
  3128. */
  3129. void indent()
  3130. {
  3131. for (std::size_t i = 1; i < path_.size(); ++i)
  3132. write(indent_);
  3133. }
  3134. /**
  3135. * Write a value out to the stream.
  3136. */
  3137. template <class T>
  3138. void write(const T& v)
  3139. {
  3140. stream_ << v;
  3141. has_naked_endline_ = false;
  3142. }
  3143. /**
  3144. * Write an endline out to the stream
  3145. */
  3146. void endline()
  3147. {
  3148. if (!has_naked_endline_)
  3149. {
  3150. stream_ << "\n";
  3151. has_naked_endline_ = true;
  3152. }
  3153. }
  3154. private:
  3155. std::ostream& stream_;
  3156. const std::string indent_;
  3157. std::vector<std::string> path_;
  3158. bool has_naked_endline_;
  3159. };
  3160. inline std::ostream& operator<<(std::ostream& stream, const base& b)
  3161. {
  3162. toml_writer writer{stream};
  3163. b.accept(writer);
  3164. return stream;
  3165. }
  3166. template <class T>
  3167. std::ostream& operator<<(std::ostream& stream, const value<T>& v)
  3168. {
  3169. toml_writer writer{stream};
  3170. v.accept(writer);
  3171. return stream;
  3172. }
  3173. inline std::ostream& operator<<(std::ostream& stream, const table& t)
  3174. {
  3175. toml_writer writer{stream};
  3176. t.accept(writer);
  3177. return stream;
  3178. }
  3179. inline std::ostream& operator<<(std::ostream& stream, const table_array& t)
  3180. {
  3181. toml_writer writer{stream};
  3182. t.accept(writer);
  3183. return stream;
  3184. }
  3185. inline std::ostream& operator<<(std::ostream& stream, const array& a)
  3186. {
  3187. toml_writer writer{stream};
  3188. a.accept(writer);
  3189. return stream;
  3190. }
  3191. } // namespace cpptoml
  3192. #endif // CPPTOML_H