parser.rl 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003
  1. /*
  2. ** upb::json::Parser (upb_json_parser)
  3. **
  4. ** A parser that uses the Ragel State Machine Compiler to generate
  5. ** the finite automata.
  6. **
  7. ** Ragel only natively handles regular languages, but we can manually
  8. ** program it a bit to handle context-free languages like JSON, by using
  9. ** the "fcall" and "fret" constructs.
  10. **
  11. ** This parser can handle the basics, but needs several things to be fleshed
  12. ** out:
  13. **
  14. ** - handling of unicode escape sequences (including high surrogate pairs).
  15. ** - properly check and report errors for unknown fields, stack overflow,
  16. ** improper array nesting (or lack of nesting).
  17. ** - handling of base64 sequences with padding characters.
  18. ** - handling of push-back (non-success returns from sink functions).
  19. ** - handling of keys/escape-sequences/etc that span input buffers.
  20. */
  21. #include <ctype.h>
  22. #include <errno.h>
  23. #include <float.h>
  24. #include <math.h>
  25. #include <stdint.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <time.h>
  30. #include "upb/json/parser.h"
  31. #include "upb/pb/encoder.h"
  32. #include "upb/port_def.inc"
  33. #define UPB_JSON_MAX_DEPTH 64
  34. /* Type of value message */
  35. enum {
  36. VALUE_NULLVALUE = 0,
  37. VALUE_NUMBERVALUE = 1,
  38. VALUE_STRINGVALUE = 2,
  39. VALUE_BOOLVALUE = 3,
  40. VALUE_STRUCTVALUE = 4,
  41. VALUE_LISTVALUE = 5
  42. };
  43. /* Forward declare */
  44. static bool is_top_level(upb_json_parser *p);
  45. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type);
  46. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type);
  47. static bool is_number_wrapper_object(upb_json_parser *p);
  48. static bool does_number_wrapper_start(upb_json_parser *p);
  49. static bool does_number_wrapper_end(upb_json_parser *p);
  50. static bool is_string_wrapper_object(upb_json_parser *p);
  51. static bool does_string_wrapper_start(upb_json_parser *p);
  52. static bool does_string_wrapper_end(upb_json_parser *p);
  53. static bool does_fieldmask_start(upb_json_parser *p);
  54. static bool does_fieldmask_end(upb_json_parser *p);
  55. static void start_fieldmask_object(upb_json_parser *p);
  56. static void end_fieldmask_object(upb_json_parser *p);
  57. static void start_wrapper_object(upb_json_parser *p);
  58. static void end_wrapper_object(upb_json_parser *p);
  59. static void start_value_object(upb_json_parser *p, int value_type);
  60. static void end_value_object(upb_json_parser *p);
  61. static void start_listvalue_object(upb_json_parser *p);
  62. static void end_listvalue_object(upb_json_parser *p);
  63. static void start_structvalue_object(upb_json_parser *p);
  64. static void end_structvalue_object(upb_json_parser *p);
  65. static void start_object(upb_json_parser *p);
  66. static void end_object(upb_json_parser *p);
  67. static void start_any_object(upb_json_parser *p, const char *ptr);
  68. static bool end_any_object(upb_json_parser *p, const char *ptr);
  69. static bool start_subobject(upb_json_parser *p);
  70. static void end_subobject(upb_json_parser *p);
  71. static void start_member(upb_json_parser *p);
  72. static void end_member(upb_json_parser *p);
  73. static bool end_membername(upb_json_parser *p);
  74. static void start_any_member(upb_json_parser *p, const char *ptr);
  75. static void end_any_member(upb_json_parser *p, const char *ptr);
  76. static bool end_any_membername(upb_json_parser *p);
  77. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  78. const upb_bufhandle *handle);
  79. static bool end(void *closure, const void *hd);
  80. static const char eof_ch = 'e';
  81. /* stringsink */
  82. typedef struct {
  83. upb_byteshandler handler;
  84. upb_bytessink sink;
  85. char *ptr;
  86. size_t len, size;
  87. } upb_stringsink;
  88. static void *stringsink_start(void *_sink, const void *hd, size_t size_hint) {
  89. upb_stringsink *sink = _sink;
  90. sink->len = 0;
  91. UPB_UNUSED(hd);
  92. UPB_UNUSED(size_hint);
  93. return sink;
  94. }
  95. static size_t stringsink_string(void *_sink, const void *hd, const char *ptr,
  96. size_t len, const upb_bufhandle *handle) {
  97. upb_stringsink *sink = _sink;
  98. size_t new_size = sink->size;
  99. UPB_UNUSED(hd);
  100. UPB_UNUSED(handle);
  101. while (sink->len + len > new_size) {
  102. new_size *= 2;
  103. }
  104. if (new_size != sink->size) {
  105. sink->ptr = realloc(sink->ptr, new_size);
  106. sink->size = new_size;
  107. }
  108. memcpy(sink->ptr + sink->len, ptr, len);
  109. sink->len += len;
  110. return len;
  111. }
  112. void upb_stringsink_init(upb_stringsink *sink) {
  113. upb_byteshandler_init(&sink->handler);
  114. upb_byteshandler_setstartstr(&sink->handler, stringsink_start, NULL);
  115. upb_byteshandler_setstring(&sink->handler, stringsink_string, NULL);
  116. upb_bytessink_reset(&sink->sink, &sink->handler, sink);
  117. sink->size = 32;
  118. sink->ptr = malloc(sink->size);
  119. sink->len = 0;
  120. }
  121. void upb_stringsink_uninit(upb_stringsink *sink) { free(sink->ptr); }
  122. typedef struct {
  123. /* For encoding Any value field in binary format. */
  124. upb_handlercache *encoder_handlercache;
  125. upb_stringsink stringsink;
  126. /* For decoding Any value field in json format. */
  127. upb_json_codecache *parser_codecache;
  128. upb_sink sink;
  129. upb_json_parser *parser;
  130. /* Mark the range of uninterpreted values in json input before type url. */
  131. const char *before_type_url_start;
  132. const char *before_type_url_end;
  133. /* Mark the range of uninterpreted values in json input after type url. */
  134. const char *after_type_url_start;
  135. } upb_jsonparser_any_frame;
  136. typedef struct {
  137. upb_sink sink;
  138. /* The current message in which we're parsing, and the field whose value we're
  139. * expecting next. */
  140. const upb_msgdef *m;
  141. const upb_fielddef *f;
  142. /* The table mapping json name to fielddef for this message. */
  143. const upb_strtable *name_table;
  144. /* We are in a repeated-field context. We need this flag to decide whether to
  145. * handle the array as a normal repeated field or a
  146. * google.protobuf.ListValue/google.protobuf.Value. */
  147. bool is_repeated;
  148. /* We are in a repeated-field context, ready to emit mapentries as
  149. * submessages. This flag alters the start-of-object (open-brace) behavior to
  150. * begin a sequence of mapentry messages rather than a single submessage. */
  151. bool is_map;
  152. /* We are in a map-entry message context. This flag is set when parsing the
  153. * value field of a single map entry and indicates to all value-field parsers
  154. * (subobjects, strings, numbers, and bools) that the map-entry submessage
  155. * should end as soon as the value is parsed. */
  156. bool is_mapentry;
  157. /* If |is_map| or |is_mapentry| is true, |mapfield| refers to the parent
  158. * message's map field that we're currently parsing. This differs from |f|
  159. * because |f| is the field in the *current* message (i.e., the map-entry
  160. * message itself), not the parent's field that leads to this map. */
  161. const upb_fielddef *mapfield;
  162. /* We are in an Any message context. This flag is set when parsing the Any
  163. * message and indicates to all field parsers (subobjects, strings, numbers,
  164. * and bools) that the parsed field should be serialized as binary data or
  165. * cached (type url not found yet). */
  166. bool is_any;
  167. /* The type of packed message in Any. */
  168. upb_jsonparser_any_frame *any_frame;
  169. /* True if the field to be parsed is unknown. */
  170. bool is_unknown_field;
  171. } upb_jsonparser_frame;
  172. static void init_frame(upb_jsonparser_frame* frame) {
  173. frame->m = NULL;
  174. frame->f = NULL;
  175. frame->name_table = NULL;
  176. frame->is_repeated = false;
  177. frame->is_map = false;
  178. frame->is_mapentry = false;
  179. frame->mapfield = NULL;
  180. frame->is_any = false;
  181. frame->any_frame = NULL;
  182. frame->is_unknown_field = false;
  183. }
  184. struct upb_json_parser {
  185. upb_arena *arena;
  186. const upb_json_parsermethod *method;
  187. upb_bytessink input_;
  188. /* Stack to track the JSON scopes we are in. */
  189. upb_jsonparser_frame stack[UPB_JSON_MAX_DEPTH];
  190. upb_jsonparser_frame *top;
  191. upb_jsonparser_frame *limit;
  192. upb_status *status;
  193. /* Ragel's internal parsing stack for the parsing state machine. */
  194. int current_state;
  195. int parser_stack[UPB_JSON_MAX_DEPTH];
  196. int parser_top;
  197. /* The handle for the current buffer. */
  198. const upb_bufhandle *handle;
  199. /* Accumulate buffer. See details in parser.rl. */
  200. const char *accumulated;
  201. size_t accumulated_len;
  202. char *accumulate_buf;
  203. size_t accumulate_buf_size;
  204. /* Multi-part text data. See details in parser.rl. */
  205. int multipart_state;
  206. upb_selector_t string_selector;
  207. /* Input capture. See details in parser.rl. */
  208. const char *capture;
  209. /* Intermediate result of parsing a unicode escape sequence. */
  210. uint32_t digit;
  211. /* For resolve type url in Any. */
  212. const upb_symtab *symtab;
  213. /* Whether to proceed if unknown field is met. */
  214. bool ignore_json_unknown;
  215. /* Cache for parsing timestamp due to base and zone are handled in different
  216. * handlers. */
  217. struct tm tm;
  218. };
  219. static upb_jsonparser_frame* start_jsonparser_frame(upb_json_parser *p) {
  220. upb_jsonparser_frame *inner;
  221. inner = p->top + 1;
  222. init_frame(inner);
  223. return inner;
  224. }
  225. struct upb_json_codecache {
  226. upb_arena *arena;
  227. upb_inttable methods; /* upb_msgdef* -> upb_json_parsermethod* */
  228. };
  229. struct upb_json_parsermethod {
  230. const upb_json_codecache *cache;
  231. upb_byteshandler input_handler_;
  232. /* Maps json_name -> fielddef */
  233. upb_strtable name_table;
  234. };
  235. #define PARSER_CHECK_RETURN(x) if (!(x)) return false
  236. static upb_jsonparser_any_frame *json_parser_any_frame_new(
  237. upb_json_parser *p) {
  238. upb_jsonparser_any_frame *frame;
  239. frame = upb_arena_malloc(p->arena, sizeof(upb_jsonparser_any_frame));
  240. frame->encoder_handlercache = upb_pb_encoder_newcache();
  241. frame->parser_codecache = upb_json_codecache_new();
  242. frame->parser = NULL;
  243. frame->before_type_url_start = NULL;
  244. frame->before_type_url_end = NULL;
  245. frame->after_type_url_start = NULL;
  246. upb_stringsink_init(&frame->stringsink);
  247. return frame;
  248. }
  249. static void json_parser_any_frame_set_payload_type(
  250. upb_json_parser *p,
  251. upb_jsonparser_any_frame *frame,
  252. const upb_msgdef *payload_type) {
  253. const upb_handlers *h;
  254. const upb_json_parsermethod *parser_method;
  255. upb_pb_encoder *encoder;
  256. /* Initialize encoder. */
  257. h = upb_handlercache_get(frame->encoder_handlercache, payload_type);
  258. encoder = upb_pb_encoder_create(p->arena, h, frame->stringsink.sink);
  259. /* Initialize parser. */
  260. parser_method = upb_json_codecache_get(frame->parser_codecache, payload_type);
  261. upb_sink_reset(&frame->sink, h, encoder);
  262. frame->parser =
  263. upb_json_parser_create(p->arena, parser_method, p->symtab, frame->sink,
  264. p->status, p->ignore_json_unknown);
  265. }
  266. static void json_parser_any_frame_free(upb_jsonparser_any_frame *frame) {
  267. upb_handlercache_free(frame->encoder_handlercache);
  268. upb_json_codecache_free(frame->parser_codecache);
  269. upb_stringsink_uninit(&frame->stringsink);
  270. }
  271. static bool json_parser_any_frame_has_type_url(
  272. upb_jsonparser_any_frame *frame) {
  273. return frame->parser != NULL;
  274. }
  275. static bool json_parser_any_frame_has_value_before_type_url(
  276. upb_jsonparser_any_frame *frame) {
  277. return frame->before_type_url_start != frame->before_type_url_end;
  278. }
  279. static bool json_parser_any_frame_has_value_after_type_url(
  280. upb_jsonparser_any_frame *frame) {
  281. return frame->after_type_url_start != NULL;
  282. }
  283. static bool json_parser_any_frame_has_value(
  284. upb_jsonparser_any_frame *frame) {
  285. return json_parser_any_frame_has_value_before_type_url(frame) ||
  286. json_parser_any_frame_has_value_after_type_url(frame);
  287. }
  288. static void json_parser_any_frame_set_before_type_url_end(
  289. upb_jsonparser_any_frame *frame,
  290. const char *ptr) {
  291. if (frame->parser == NULL) {
  292. frame->before_type_url_end = ptr;
  293. }
  294. }
  295. static void json_parser_any_frame_set_after_type_url_start_once(
  296. upb_jsonparser_any_frame *frame,
  297. const char *ptr) {
  298. if (json_parser_any_frame_has_type_url(frame) &&
  299. frame->after_type_url_start == NULL) {
  300. frame->after_type_url_start = ptr;
  301. }
  302. }
  303. /* Used to signal that a capture has been suspended. */
  304. static char suspend_capture;
  305. static upb_selector_t getsel_for_handlertype(upb_json_parser *p,
  306. upb_handlertype_t type) {
  307. upb_selector_t sel;
  308. bool ok = upb_handlers_getselector(p->top->f, type, &sel);
  309. UPB_ASSUME(ok);
  310. return sel;
  311. }
  312. static upb_selector_t parser_getsel(upb_json_parser *p) {
  313. return getsel_for_handlertype(
  314. p, upb_handlers_getprimitivehandlertype(p->top->f));
  315. }
  316. static bool check_stack(upb_json_parser *p) {
  317. if ((p->top + 1) == p->limit) {
  318. upb_status_seterrmsg(p->status, "Nesting too deep");
  319. return false;
  320. }
  321. return true;
  322. }
  323. static void set_name_table(upb_json_parser *p, upb_jsonparser_frame *frame) {
  324. upb_value v;
  325. const upb_json_codecache *cache = p->method->cache;
  326. bool ok;
  327. const upb_json_parsermethod *method;
  328. ok = upb_inttable_lookupptr(&cache->methods, frame->m, &v);
  329. UPB_ASSUME(ok);
  330. method = upb_value_getconstptr(v);
  331. frame->name_table = &method->name_table;
  332. }
  333. /* There are GCC/Clang built-ins for overflow checking which we could start
  334. * using if there was any performance benefit to it. */
  335. static bool checked_add(size_t a, size_t b, size_t *c) {
  336. if (SIZE_MAX - a < b) return false;
  337. *c = a + b;
  338. return true;
  339. }
  340. static size_t saturating_multiply(size_t a, size_t b) {
  341. /* size_t is unsigned, so this is defined behavior even on overflow. */
  342. size_t ret = a * b;
  343. if (b != 0 && ret / b != a) {
  344. ret = SIZE_MAX;
  345. }
  346. return ret;
  347. }
  348. /* Base64 decoding ************************************************************/
  349. /* TODO(haberman): make this streaming. */
  350. static const signed char b64table[] = {
  351. -1, -1, -1, -1, -1, -1, -1, -1,
  352. -1, -1, -1, -1, -1, -1, -1, -1,
  353. -1, -1, -1, -1, -1, -1, -1, -1,
  354. -1, -1, -1, -1, -1, -1, -1, -1,
  355. -1, -1, -1, -1, -1, -1, -1, -1,
  356. -1, -1, -1, 62/*+*/, -1, -1, -1, 63/*/ */,
  357. 52/*0*/, 53/*1*/, 54/*2*/, 55/*3*/, 56/*4*/, 57/*5*/, 58/*6*/, 59/*7*/,
  358. 60/*8*/, 61/*9*/, -1, -1, -1, -1, -1, -1,
  359. -1, 0/*A*/, 1/*B*/, 2/*C*/, 3/*D*/, 4/*E*/, 5/*F*/, 6/*G*/,
  360. 07/*H*/, 8/*I*/, 9/*J*/, 10/*K*/, 11/*L*/, 12/*M*/, 13/*N*/, 14/*O*/,
  361. 15/*P*/, 16/*Q*/, 17/*R*/, 18/*S*/, 19/*T*/, 20/*U*/, 21/*V*/, 22/*W*/,
  362. 23/*X*/, 24/*Y*/, 25/*Z*/, -1, -1, -1, -1, -1,
  363. -1, 26/*a*/, 27/*b*/, 28/*c*/, 29/*d*/, 30/*e*/, 31/*f*/, 32/*g*/,
  364. 33/*h*/, 34/*i*/, 35/*j*/, 36/*k*/, 37/*l*/, 38/*m*/, 39/*n*/, 40/*o*/,
  365. 41/*p*/, 42/*q*/, 43/*r*/, 44/*s*/, 45/*t*/, 46/*u*/, 47/*v*/, 48/*w*/,
  366. 49/*x*/, 50/*y*/, 51/*z*/, -1, -1, -1, -1, -1,
  367. -1, -1, -1, -1, -1, -1, -1, -1,
  368. -1, -1, -1, -1, -1, -1, -1, -1,
  369. -1, -1, -1, -1, -1, -1, -1, -1,
  370. -1, -1, -1, -1, -1, -1, -1, -1,
  371. -1, -1, -1, -1, -1, -1, -1, -1,
  372. -1, -1, -1, -1, -1, -1, -1, -1,
  373. -1, -1, -1, -1, -1, -1, -1, -1,
  374. -1, -1, -1, -1, -1, -1, -1, -1,
  375. -1, -1, -1, -1, -1, -1, -1, -1,
  376. -1, -1, -1, -1, -1, -1, -1, -1,
  377. -1, -1, -1, -1, -1, -1, -1, -1,
  378. -1, -1, -1, -1, -1, -1, -1, -1,
  379. -1, -1, -1, -1, -1, -1, -1, -1,
  380. -1, -1, -1, -1, -1, -1, -1, -1,
  381. -1, -1, -1, -1, -1, -1, -1, -1,
  382. -1, -1, -1, -1, -1, -1, -1, -1
  383. };
  384. /* Returns the table value sign-extended to 32 bits. Knowing that the upper
  385. * bits will be 1 for unrecognized characters makes it easier to check for
  386. * this error condition later (see below). */
  387. int32_t b64lookup(unsigned char ch) { return b64table[ch]; }
  388. /* Returns true if the given character is not a valid base64 character or
  389. * padding. */
  390. bool nonbase64(unsigned char ch) { return b64lookup(ch) == -1 && ch != '='; }
  391. static bool base64_push(upb_json_parser *p, upb_selector_t sel, const char *ptr,
  392. size_t len) {
  393. const char *limit = ptr + len;
  394. for (; ptr < limit; ptr += 4) {
  395. uint32_t val;
  396. char output[3];
  397. if (limit - ptr < 4) {
  398. upb_status_seterrf(p->status,
  399. "Base64 input for bytes field not a multiple of 4: %s",
  400. upb_fielddef_name(p->top->f));
  401. return false;
  402. }
  403. val = b64lookup(ptr[0]) << 18 |
  404. b64lookup(ptr[1]) << 12 |
  405. b64lookup(ptr[2]) << 6 |
  406. b64lookup(ptr[3]);
  407. /* Test the upper bit; returns true if any of the characters returned -1. */
  408. if (val & 0x80000000) {
  409. goto otherchar;
  410. }
  411. output[0] = val >> 16;
  412. output[1] = (val >> 8) & 0xff;
  413. output[2] = val & 0xff;
  414. upb_sink_putstring(p->top->sink, sel, output, 3, NULL);
  415. }
  416. return true;
  417. otherchar:
  418. if (nonbase64(ptr[0]) || nonbase64(ptr[1]) || nonbase64(ptr[2]) ||
  419. nonbase64(ptr[3]) ) {
  420. upb_status_seterrf(p->status,
  421. "Non-base64 characters in bytes field: %s",
  422. upb_fielddef_name(p->top->f));
  423. return false;
  424. } if (ptr[2] == '=') {
  425. uint32_t val;
  426. char output;
  427. /* Last group contains only two input bytes, one output byte. */
  428. if (ptr[0] == '=' || ptr[1] == '=' || ptr[3] != '=') {
  429. goto badpadding;
  430. }
  431. val = b64lookup(ptr[0]) << 18 |
  432. b64lookup(ptr[1]) << 12;
  433. UPB_ASSERT(!(val & 0x80000000));
  434. output = val >> 16;
  435. upb_sink_putstring(p->top->sink, sel, &output, 1, NULL);
  436. return true;
  437. } else {
  438. uint32_t val;
  439. char output[2];
  440. /* Last group contains only three input bytes, two output bytes. */
  441. if (ptr[0] == '=' || ptr[1] == '=' || ptr[2] == '=') {
  442. goto badpadding;
  443. }
  444. val = b64lookup(ptr[0]) << 18 |
  445. b64lookup(ptr[1]) << 12 |
  446. b64lookup(ptr[2]) << 6;
  447. output[0] = val >> 16;
  448. output[1] = (val >> 8) & 0xff;
  449. upb_sink_putstring(p->top->sink, sel, output, 2, NULL);
  450. return true;
  451. }
  452. badpadding:
  453. upb_status_seterrf(p->status,
  454. "Incorrect base64 padding for field: %s (%.*s)",
  455. upb_fielddef_name(p->top->f),
  456. 4, ptr);
  457. return false;
  458. }
  459. /* Accumulate buffer **********************************************************/
  460. /* Functionality for accumulating a buffer.
  461. *
  462. * Some parts of the parser need an entire value as a contiguous string. For
  463. * example, to look up a member name in a hash table, or to turn a string into
  464. * a number, the relevant library routines need the input string to be in
  465. * contiguous memory, even if the value spanned two or more buffers in the
  466. * input. These routines handle that.
  467. *
  468. * In the common case we can just point to the input buffer to get this
  469. * contiguous string and avoid any actual copy. So we optimistically begin
  470. * this way. But there are a few cases where we must instead copy into a
  471. * separate buffer:
  472. *
  473. * 1. The string was not contiguous in the input (it spanned buffers).
  474. *
  475. * 2. The string included escape sequences that need to be interpreted to get
  476. * the true value in a contiguous buffer. */
  477. static void assert_accumulate_empty(upb_json_parser *p) {
  478. UPB_ASSERT(p->accumulated == NULL);
  479. UPB_ASSERT(p->accumulated_len == 0);
  480. }
  481. static void accumulate_clear(upb_json_parser *p) {
  482. p->accumulated = NULL;
  483. p->accumulated_len = 0;
  484. }
  485. /* Used internally by accumulate_append(). */
  486. static bool accumulate_realloc(upb_json_parser *p, size_t need) {
  487. void *mem;
  488. size_t old_size = p->accumulate_buf_size;
  489. size_t new_size = UPB_MAX(old_size, 128);
  490. while (new_size < need) {
  491. new_size = saturating_multiply(new_size, 2);
  492. }
  493. mem = upb_arena_realloc(p->arena, p->accumulate_buf, old_size, new_size);
  494. if (!mem) {
  495. upb_status_seterrmsg(p->status, "Out of memory allocating buffer.");
  496. return false;
  497. }
  498. p->accumulate_buf = mem;
  499. p->accumulate_buf_size = new_size;
  500. return true;
  501. }
  502. /* Logically appends the given data to the append buffer.
  503. * If "can_alias" is true, we will try to avoid actually copying, but the buffer
  504. * must be valid until the next accumulate_append() call (if any). */
  505. static bool accumulate_append(upb_json_parser *p, const char *buf, size_t len,
  506. bool can_alias) {
  507. size_t need;
  508. if (!p->accumulated && can_alias) {
  509. p->accumulated = buf;
  510. p->accumulated_len = len;
  511. return true;
  512. }
  513. if (!checked_add(p->accumulated_len, len, &need)) {
  514. upb_status_seterrmsg(p->status, "Integer overflow.");
  515. return false;
  516. }
  517. if (need > p->accumulate_buf_size && !accumulate_realloc(p, need)) {
  518. return false;
  519. }
  520. if (p->accumulated != p->accumulate_buf) {
  521. memcpy(p->accumulate_buf, p->accumulated, p->accumulated_len);
  522. p->accumulated = p->accumulate_buf;
  523. }
  524. memcpy(p->accumulate_buf + p->accumulated_len, buf, len);
  525. p->accumulated_len += len;
  526. return true;
  527. }
  528. /* Returns a pointer to the data accumulated since the last accumulate_clear()
  529. * call, and writes the length to *len. This with point either to the input
  530. * buffer or a temporary accumulate buffer. */
  531. static const char *accumulate_getptr(upb_json_parser *p, size_t *len) {
  532. UPB_ASSERT(p->accumulated);
  533. *len = p->accumulated_len;
  534. return p->accumulated;
  535. }
  536. /* Mult-part text data ********************************************************/
  537. /* When we have text data in the input, it can often come in multiple segments.
  538. * For example, there may be some raw string data followed by an escape
  539. * sequence. The two segments are processed with different logic. Also buffer
  540. * seams in the input can cause multiple segments.
  541. *
  542. * As we see segments, there are two main cases for how we want to process them:
  543. *
  544. * 1. we want to push the captured input directly to string handlers.
  545. *
  546. * 2. we need to accumulate all the parts into a contiguous buffer for further
  547. * processing (field name lookup, string->number conversion, etc). */
  548. /* This is the set of states for p->multipart_state. */
  549. enum {
  550. /* We are not currently processing multipart data. */
  551. MULTIPART_INACTIVE = 0,
  552. /* We are processing multipart data by accumulating it into a contiguous
  553. * buffer. */
  554. MULTIPART_ACCUMULATE = 1,
  555. /* We are processing multipart data by pushing each part directly to the
  556. * current string handlers. */
  557. MULTIPART_PUSHEAGERLY = 2
  558. };
  559. /* Start a multi-part text value where we accumulate the data for processing at
  560. * the end. */
  561. static void multipart_startaccum(upb_json_parser *p) {
  562. assert_accumulate_empty(p);
  563. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  564. p->multipart_state = MULTIPART_ACCUMULATE;
  565. }
  566. /* Start a multi-part text value where we immediately push text data to a string
  567. * value with the given selector. */
  568. static void multipart_start(upb_json_parser *p, upb_selector_t sel) {
  569. assert_accumulate_empty(p);
  570. UPB_ASSERT(p->multipart_state == MULTIPART_INACTIVE);
  571. p->multipart_state = MULTIPART_PUSHEAGERLY;
  572. p->string_selector = sel;
  573. }
  574. static bool multipart_text(upb_json_parser *p, const char *buf, size_t len,
  575. bool can_alias) {
  576. switch (p->multipart_state) {
  577. case MULTIPART_INACTIVE:
  578. upb_status_seterrmsg(
  579. p->status, "Internal error: unexpected state MULTIPART_INACTIVE");
  580. return false;
  581. case MULTIPART_ACCUMULATE:
  582. if (!accumulate_append(p, buf, len, can_alias)) {
  583. return false;
  584. }
  585. break;
  586. case MULTIPART_PUSHEAGERLY: {
  587. const upb_bufhandle *handle = can_alias ? p->handle : NULL;
  588. upb_sink_putstring(p->top->sink, p->string_selector, buf, len, handle);
  589. break;
  590. }
  591. }
  592. return true;
  593. }
  594. /* Note: this invalidates the accumulate buffer! Call only after reading its
  595. * contents. */
  596. static void multipart_end(upb_json_parser *p) {
  597. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  598. p->multipart_state = MULTIPART_INACTIVE;
  599. accumulate_clear(p);
  600. }
  601. /* Input capture **************************************************************/
  602. /* Functionality for capturing a region of the input as text. Gracefully
  603. * handles the case where a buffer seam occurs in the middle of the captured
  604. * region. */
  605. static void capture_begin(upb_json_parser *p, const char *ptr) {
  606. UPB_ASSERT(p->multipart_state != MULTIPART_INACTIVE);
  607. UPB_ASSERT(p->capture == NULL);
  608. p->capture = ptr;
  609. }
  610. static bool capture_end(upb_json_parser *p, const char *ptr) {
  611. UPB_ASSERT(p->capture);
  612. if (multipart_text(p, p->capture, ptr - p->capture, true)) {
  613. p->capture = NULL;
  614. return true;
  615. } else {
  616. return false;
  617. }
  618. }
  619. /* This is called at the end of each input buffer (ie. when we have hit a
  620. * buffer seam). If we are in the middle of capturing the input, this
  621. * processes the unprocessed capture region. */
  622. static void capture_suspend(upb_json_parser *p, const char **ptr) {
  623. if (!p->capture) return;
  624. if (multipart_text(p, p->capture, *ptr - p->capture, false)) {
  625. /* We use this as a signal that we were in the middle of capturing, and
  626. * that capturing should resume at the beginning of the next buffer.
  627. *
  628. * We can't use *ptr here, because we have no guarantee that this pointer
  629. * will be valid when we resume (if the underlying memory is freed, then
  630. * using the pointer at all, even to compare to NULL, is likely undefined
  631. * behavior). */
  632. p->capture = &suspend_capture;
  633. } else {
  634. /* Need to back up the pointer to the beginning of the capture, since
  635. * we were not able to actually preserve it. */
  636. *ptr = p->capture;
  637. }
  638. }
  639. static void capture_resume(upb_json_parser *p, const char *ptr) {
  640. if (p->capture) {
  641. UPB_ASSERT(p->capture == &suspend_capture);
  642. p->capture = ptr;
  643. }
  644. }
  645. /* Callbacks from the parser **************************************************/
  646. /* These are the functions called directly from the parser itself.
  647. * We define these in the same order as their declarations in the parser. */
  648. static char escape_char(char in) {
  649. switch (in) {
  650. case 'r': return '\r';
  651. case 't': return '\t';
  652. case 'n': return '\n';
  653. case 'f': return '\f';
  654. case 'b': return '\b';
  655. case '/': return '/';
  656. case '"': return '"';
  657. case '\\': return '\\';
  658. default:
  659. UPB_ASSERT(0);
  660. return 'x';
  661. }
  662. }
  663. static bool escape(upb_json_parser *p, const char *ptr) {
  664. char ch = escape_char(*ptr);
  665. return multipart_text(p, &ch, 1, false);
  666. }
  667. static void start_hex(upb_json_parser *p) {
  668. p->digit = 0;
  669. }
  670. static void hexdigit(upb_json_parser *p, const char *ptr) {
  671. char ch = *ptr;
  672. p->digit <<= 4;
  673. if (ch >= '0' && ch <= '9') {
  674. p->digit += (ch - '0');
  675. } else if (ch >= 'a' && ch <= 'f') {
  676. p->digit += ((ch - 'a') + 10);
  677. } else {
  678. UPB_ASSERT(ch >= 'A' && ch <= 'F');
  679. p->digit += ((ch - 'A') + 10);
  680. }
  681. }
  682. static bool end_hex(upb_json_parser *p) {
  683. uint32_t codepoint = p->digit;
  684. /* emit the codepoint as UTF-8. */
  685. char utf8[3]; /* support \u0000 -- \uFFFF -- need only three bytes. */
  686. int length = 0;
  687. if (codepoint <= 0x7F) {
  688. utf8[0] = codepoint;
  689. length = 1;
  690. } else if (codepoint <= 0x07FF) {
  691. utf8[1] = (codepoint & 0x3F) | 0x80;
  692. codepoint >>= 6;
  693. utf8[0] = (codepoint & 0x1F) | 0xC0;
  694. length = 2;
  695. } else /* codepoint <= 0xFFFF */ {
  696. utf8[2] = (codepoint & 0x3F) | 0x80;
  697. codepoint >>= 6;
  698. utf8[1] = (codepoint & 0x3F) | 0x80;
  699. codepoint >>= 6;
  700. utf8[0] = (codepoint & 0x0F) | 0xE0;
  701. length = 3;
  702. }
  703. /* TODO(haberman): Handle high surrogates: if codepoint is a high surrogate
  704. * we have to wait for the next escape to get the full code point). */
  705. return multipart_text(p, utf8, length, false);
  706. }
  707. static void start_text(upb_json_parser *p, const char *ptr) {
  708. capture_begin(p, ptr);
  709. }
  710. static bool end_text(upb_json_parser *p, const char *ptr) {
  711. return capture_end(p, ptr);
  712. }
  713. static bool start_number(upb_json_parser *p, const char *ptr) {
  714. if (is_top_level(p)) {
  715. if (is_number_wrapper_object(p)) {
  716. start_wrapper_object(p);
  717. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  718. start_value_object(p, VALUE_NUMBERVALUE);
  719. } else {
  720. return false;
  721. }
  722. } else if (does_number_wrapper_start(p)) {
  723. if (!start_subobject(p)) {
  724. return false;
  725. }
  726. start_wrapper_object(p);
  727. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  728. if (!start_subobject(p)) {
  729. return false;
  730. }
  731. start_value_object(p, VALUE_NUMBERVALUE);
  732. }
  733. multipart_startaccum(p);
  734. capture_begin(p, ptr);
  735. return true;
  736. }
  737. static bool parse_number(upb_json_parser *p, bool is_quoted);
  738. static bool end_number_nontop(upb_json_parser *p, const char *ptr) {
  739. if (!capture_end(p, ptr)) {
  740. return false;
  741. }
  742. if (p->top->f == NULL) {
  743. multipart_end(p);
  744. return true;
  745. }
  746. return parse_number(p, false);
  747. }
  748. static bool end_number(upb_json_parser *p, const char *ptr) {
  749. if (!end_number_nontop(p, ptr)) {
  750. return false;
  751. }
  752. if (does_number_wrapper_end(p)) {
  753. end_wrapper_object(p);
  754. if (!is_top_level(p)) {
  755. end_subobject(p);
  756. }
  757. return true;
  758. }
  759. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  760. end_value_object(p);
  761. if (!is_top_level(p)) {
  762. end_subobject(p);
  763. }
  764. return true;
  765. }
  766. return true;
  767. }
  768. /* |buf| is NULL-terminated. |buf| itself will never include quotes;
  769. * |is_quoted| tells us whether this text originally appeared inside quotes. */
  770. static bool parse_number_from_buffer(upb_json_parser *p, const char *buf,
  771. bool is_quoted) {
  772. size_t len = strlen(buf);
  773. const char *bufend = buf + len;
  774. char *end;
  775. upb_fieldtype_t type = upb_fielddef_type(p->top->f);
  776. double val;
  777. double dummy;
  778. double inf = UPB_INFINITY;
  779. errno = 0;
  780. if (len == 0 || buf[0] == ' ') {
  781. return false;
  782. }
  783. /* For integer types, first try parsing with integer-specific routines.
  784. * If these succeed, they will be more accurate for int64/uint64 than
  785. * strtod().
  786. */
  787. switch (type) {
  788. case UPB_TYPE_ENUM:
  789. case UPB_TYPE_INT32: {
  790. long val = strtol(buf, &end, 0);
  791. if (errno == ERANGE || end != bufend) {
  792. break;
  793. } else if (val > INT32_MAX || val < INT32_MIN) {
  794. return false;
  795. } else {
  796. upb_sink_putint32(p->top->sink, parser_getsel(p), val);
  797. return true;
  798. }
  799. }
  800. case UPB_TYPE_UINT32: {
  801. unsigned long val = strtoul(buf, &end, 0);
  802. if (end != bufend) {
  803. break;
  804. } else if (val > UINT32_MAX || errno == ERANGE) {
  805. return false;
  806. } else {
  807. upb_sink_putuint32(p->top->sink, parser_getsel(p), val);
  808. return true;
  809. }
  810. }
  811. /* XXX: We can't handle [u]int64 properly on 32-bit machines because
  812. * strto[u]ll isn't in C89. */
  813. case UPB_TYPE_INT64: {
  814. long val = strtol(buf, &end, 0);
  815. if (errno == ERANGE || end != bufend) {
  816. break;
  817. } else {
  818. upb_sink_putint64(p->top->sink, parser_getsel(p), val);
  819. return true;
  820. }
  821. }
  822. case UPB_TYPE_UINT64: {
  823. unsigned long val = strtoul(p->accumulated, &end, 0);
  824. if (end != bufend) {
  825. break;
  826. } else if (errno == ERANGE) {
  827. return false;
  828. } else {
  829. upb_sink_putuint64(p->top->sink, parser_getsel(p), val);
  830. return true;
  831. }
  832. }
  833. default:
  834. break;
  835. }
  836. if (type != UPB_TYPE_DOUBLE && type != UPB_TYPE_FLOAT && is_quoted) {
  837. /* Quoted numbers for integer types are not allowed to be in double form. */
  838. return false;
  839. }
  840. if (len == strlen("Infinity") && strcmp(buf, "Infinity") == 0) {
  841. /* C89 does not have an INFINITY macro. */
  842. val = inf;
  843. } else if (len == strlen("-Infinity") && strcmp(buf, "-Infinity") == 0) {
  844. val = -inf;
  845. } else {
  846. val = strtod(buf, &end);
  847. if (errno == ERANGE || end != bufend) {
  848. return false;
  849. }
  850. }
  851. switch (type) {
  852. #define CASE(capitaltype, smalltype, ctype, min, max) \
  853. case UPB_TYPE_ ## capitaltype: { \
  854. if (modf(val, &dummy) != 0 || val > max || val < min) { \
  855. return false; \
  856. } else { \
  857. upb_sink_put ## smalltype(p->top->sink, parser_getsel(p), \
  858. (ctype)val); \
  859. return true; \
  860. } \
  861. break; \
  862. }
  863. case UPB_TYPE_ENUM:
  864. CASE(INT32, int32, int32_t, INT32_MIN, INT32_MAX);
  865. CASE(INT64, int64, int64_t, INT64_MIN, INT64_MAX);
  866. CASE(UINT32, uint32, uint32_t, 0, UINT32_MAX);
  867. CASE(UINT64, uint64, uint64_t, 0, UINT64_MAX);
  868. #undef CASE
  869. case UPB_TYPE_DOUBLE:
  870. upb_sink_putdouble(p->top->sink, parser_getsel(p), val);
  871. return true;
  872. case UPB_TYPE_FLOAT:
  873. if ((val > FLT_MAX || val < -FLT_MAX) && val != inf && val != -inf) {
  874. return false;
  875. } else {
  876. upb_sink_putfloat(p->top->sink, parser_getsel(p), val);
  877. return true;
  878. }
  879. default:
  880. return false;
  881. }
  882. }
  883. static bool parse_number(upb_json_parser *p, bool is_quoted) {
  884. size_t len;
  885. const char *buf;
  886. /* strtol() and friends unfortunately do not support specifying the length of
  887. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  888. if (!multipart_text(p, "\0", 1, false)) {
  889. return false;
  890. }
  891. buf = accumulate_getptr(p, &len);
  892. if (parse_number_from_buffer(p, buf, is_quoted)) {
  893. multipart_end(p);
  894. return true;
  895. } else {
  896. upb_status_seterrf(p->status, "error parsing number: %s", buf);
  897. multipart_end(p);
  898. return false;
  899. }
  900. }
  901. static bool parser_putbool(upb_json_parser *p, bool val) {
  902. bool ok;
  903. if (p->top->f == NULL) {
  904. return true;
  905. }
  906. if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL) {
  907. upb_status_seterrf(p->status,
  908. "Boolean value specified for non-bool field: %s",
  909. upb_fielddef_name(p->top->f));
  910. return false;
  911. }
  912. ok = upb_sink_putbool(p->top->sink, parser_getsel(p), val);
  913. UPB_ASSERT(ok);
  914. return true;
  915. }
  916. static bool end_bool(upb_json_parser *p, bool val) {
  917. if (is_top_level(p)) {
  918. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  919. start_wrapper_object(p);
  920. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  921. start_value_object(p, VALUE_BOOLVALUE);
  922. } else {
  923. return false;
  924. }
  925. } else if (is_wellknown_field(p, UPB_WELLKNOWN_BOOLVALUE)) {
  926. if (!start_subobject(p)) {
  927. return false;
  928. }
  929. start_wrapper_object(p);
  930. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  931. if (!start_subobject(p)) {
  932. return false;
  933. }
  934. start_value_object(p, VALUE_BOOLVALUE);
  935. }
  936. if (p->top->is_unknown_field) {
  937. return true;
  938. }
  939. if (!parser_putbool(p, val)) {
  940. return false;
  941. }
  942. if (is_wellknown_msg(p, UPB_WELLKNOWN_BOOLVALUE)) {
  943. end_wrapper_object(p);
  944. if (!is_top_level(p)) {
  945. end_subobject(p);
  946. }
  947. return true;
  948. }
  949. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  950. end_value_object(p);
  951. if (!is_top_level(p)) {
  952. end_subobject(p);
  953. }
  954. return true;
  955. }
  956. return true;
  957. }
  958. static bool end_null(upb_json_parser *p) {
  959. const char *zero_ptr = "0";
  960. if (is_top_level(p)) {
  961. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  962. start_value_object(p, VALUE_NULLVALUE);
  963. } else {
  964. return true;
  965. }
  966. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  967. if (!start_subobject(p)) {
  968. return false;
  969. }
  970. start_value_object(p, VALUE_NULLVALUE);
  971. } else {
  972. return true;
  973. }
  974. /* Fill null_value field. */
  975. multipart_startaccum(p);
  976. capture_begin(p, zero_ptr);
  977. capture_end(p, zero_ptr + 1);
  978. parse_number(p, false);
  979. end_value_object(p);
  980. if (!is_top_level(p)) {
  981. end_subobject(p);
  982. }
  983. return true;
  984. }
  985. static bool start_any_stringval(upb_json_parser *p) {
  986. multipart_startaccum(p);
  987. return true;
  988. }
  989. static bool start_stringval(upb_json_parser *p) {
  990. if (is_top_level(p)) {
  991. if (is_string_wrapper_object(p) ||
  992. is_number_wrapper_object(p)) {
  993. start_wrapper_object(p);
  994. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  995. start_fieldmask_object(p);
  996. return true;
  997. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  998. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  999. start_object(p);
  1000. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  1001. start_value_object(p, VALUE_STRINGVALUE);
  1002. } else {
  1003. return false;
  1004. }
  1005. } else if (does_string_wrapper_start(p) ||
  1006. does_number_wrapper_start(p)) {
  1007. if (!start_subobject(p)) {
  1008. return false;
  1009. }
  1010. start_wrapper_object(p);
  1011. } else if (does_fieldmask_start(p)) {
  1012. if (!start_subobject(p)) {
  1013. return false;
  1014. }
  1015. start_fieldmask_object(p);
  1016. return true;
  1017. } else if (is_wellknown_field(p, UPB_WELLKNOWN_TIMESTAMP) ||
  1018. is_wellknown_field(p, UPB_WELLKNOWN_DURATION)) {
  1019. if (!start_subobject(p)) {
  1020. return false;
  1021. }
  1022. start_object(p);
  1023. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  1024. if (!start_subobject(p)) {
  1025. return false;
  1026. }
  1027. start_value_object(p, VALUE_STRINGVALUE);
  1028. }
  1029. if (p->top->f == NULL) {
  1030. multipart_startaccum(p);
  1031. return true;
  1032. }
  1033. if (p->top->is_any) {
  1034. return start_any_stringval(p);
  1035. }
  1036. if (upb_fielddef_isstring(p->top->f)) {
  1037. upb_jsonparser_frame *inner;
  1038. upb_selector_t sel;
  1039. if (!check_stack(p)) return false;
  1040. /* Start a new parser frame: parser frames correspond one-to-one with
  1041. * handler frames, and string events occur in a sub-frame. */
  1042. inner = start_jsonparser_frame(p);
  1043. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  1044. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  1045. inner->m = p->top->m;
  1046. inner->f = p->top->f;
  1047. p->top = inner;
  1048. if (upb_fielddef_type(p->top->f) == UPB_TYPE_STRING) {
  1049. /* For STRING fields we push data directly to the handlers as it is
  1050. * parsed. We don't do this yet for BYTES fields, because our base64
  1051. * decoder is not streaming.
  1052. *
  1053. * TODO(haberman): make base64 decoding streaming also. */
  1054. multipart_start(p, getsel_for_handlertype(p, UPB_HANDLER_STRING));
  1055. return true;
  1056. } else {
  1057. multipart_startaccum(p);
  1058. return true;
  1059. }
  1060. } else if (upb_fielddef_type(p->top->f) != UPB_TYPE_BOOL &&
  1061. upb_fielddef_type(p->top->f) != UPB_TYPE_MESSAGE) {
  1062. /* No need to push a frame -- numeric values in quotes remain in the
  1063. * current parser frame. These values must accmulate so we can convert
  1064. * them all at once at the end. */
  1065. multipart_startaccum(p);
  1066. return true;
  1067. } else {
  1068. upb_status_seterrf(p->status,
  1069. "String specified for bool or submessage field: %s",
  1070. upb_fielddef_name(p->top->f));
  1071. return false;
  1072. }
  1073. }
  1074. static bool end_any_stringval(upb_json_parser *p) {
  1075. size_t len;
  1076. const char *buf = accumulate_getptr(p, &len);
  1077. /* Set type_url */
  1078. upb_selector_t sel;
  1079. upb_jsonparser_frame *inner;
  1080. if (!check_stack(p)) return false;
  1081. inner = p->top + 1;
  1082. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  1083. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  1084. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  1085. upb_sink_putstring(inner->sink, sel, buf, len, NULL);
  1086. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  1087. upb_sink_endstr(inner->sink, sel);
  1088. multipart_end(p);
  1089. /* Resolve type url */
  1090. if (strncmp(buf, "type.googleapis.com/", 20) == 0 && len > 20) {
  1091. const upb_msgdef *payload_type = NULL;
  1092. buf += 20;
  1093. len -= 20;
  1094. payload_type = upb_symtab_lookupmsg2(p->symtab, buf, len);
  1095. if (payload_type == NULL) {
  1096. upb_status_seterrf(
  1097. p->status, "Cannot find packed type: %.*s\n", (int)len, buf);
  1098. return false;
  1099. }
  1100. json_parser_any_frame_set_payload_type(p, p->top->any_frame, payload_type);
  1101. return true;
  1102. } else {
  1103. upb_status_seterrf(
  1104. p->status, "Invalid type url: %.*s\n", (int)len, buf);
  1105. return false;
  1106. }
  1107. }
  1108. static bool end_stringval_nontop(upb_json_parser *p) {
  1109. bool ok = true;
  1110. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  1111. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION)) {
  1112. multipart_end(p);
  1113. return true;
  1114. }
  1115. if (p->top->f == NULL) {
  1116. multipart_end(p);
  1117. return true;
  1118. }
  1119. if (p->top->is_any) {
  1120. return end_any_stringval(p);
  1121. }
  1122. switch (upb_fielddef_type(p->top->f)) {
  1123. case UPB_TYPE_BYTES:
  1124. if (!base64_push(p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  1125. p->accumulated, p->accumulated_len)) {
  1126. return false;
  1127. }
  1128. /* Fall through. */
  1129. case UPB_TYPE_STRING: {
  1130. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  1131. upb_sink_endstr(p->top->sink, sel);
  1132. p->top--;
  1133. break;
  1134. }
  1135. case UPB_TYPE_ENUM: {
  1136. /* Resolve enum symbolic name to integer value. */
  1137. const upb_enumdef *enumdef = upb_fielddef_enumsubdef(p->top->f);
  1138. size_t len;
  1139. const char *buf = accumulate_getptr(p, &len);
  1140. int32_t int_val = 0;
  1141. ok = upb_enumdef_ntoi(enumdef, buf, len, &int_val);
  1142. if (ok) {
  1143. upb_selector_t sel = parser_getsel(p);
  1144. upb_sink_putint32(p->top->sink, sel, int_val);
  1145. } else {
  1146. upb_status_seterrf(p->status, "Enum value unknown: '%.*s'", len, buf);
  1147. }
  1148. break;
  1149. }
  1150. case UPB_TYPE_INT32:
  1151. case UPB_TYPE_INT64:
  1152. case UPB_TYPE_UINT32:
  1153. case UPB_TYPE_UINT64:
  1154. case UPB_TYPE_DOUBLE:
  1155. case UPB_TYPE_FLOAT:
  1156. ok = parse_number(p, true);
  1157. break;
  1158. default:
  1159. UPB_ASSERT(false);
  1160. upb_status_seterrmsg(p->status, "Internal error in JSON decoder");
  1161. ok = false;
  1162. break;
  1163. }
  1164. multipart_end(p);
  1165. return ok;
  1166. }
  1167. static bool end_stringval(upb_json_parser *p) {
  1168. /* FieldMask's stringvals have been ended when handling them. Only need to
  1169. * close FieldMask here.*/
  1170. if (does_fieldmask_end(p)) {
  1171. end_fieldmask_object(p);
  1172. if (!is_top_level(p)) {
  1173. end_subobject(p);
  1174. }
  1175. return true;
  1176. }
  1177. if (!end_stringval_nontop(p)) {
  1178. return false;
  1179. }
  1180. if (does_string_wrapper_end(p) ||
  1181. does_number_wrapper_end(p)) {
  1182. end_wrapper_object(p);
  1183. if (!is_top_level(p)) {
  1184. end_subobject(p);
  1185. }
  1186. return true;
  1187. }
  1188. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  1189. end_value_object(p);
  1190. if (!is_top_level(p)) {
  1191. end_subobject(p);
  1192. }
  1193. return true;
  1194. }
  1195. if (is_wellknown_msg(p, UPB_WELLKNOWN_TIMESTAMP) ||
  1196. is_wellknown_msg(p, UPB_WELLKNOWN_DURATION) ||
  1197. is_wellknown_msg(p, UPB_WELLKNOWN_FIELDMASK)) {
  1198. end_object(p);
  1199. if (!is_top_level(p)) {
  1200. end_subobject(p);
  1201. }
  1202. return true;
  1203. }
  1204. return true;
  1205. }
  1206. static void start_duration_base(upb_json_parser *p, const char *ptr) {
  1207. capture_begin(p, ptr);
  1208. }
  1209. static bool end_duration_base(upb_json_parser *p, const char *ptr) {
  1210. size_t len;
  1211. const char *buf;
  1212. char seconds_buf[14];
  1213. char nanos_buf[12];
  1214. char *end;
  1215. int64_t seconds = 0;
  1216. int32_t nanos = 0;
  1217. double val = 0.0;
  1218. const char *seconds_membername = "seconds";
  1219. const char *nanos_membername = "nanos";
  1220. size_t fraction_start;
  1221. if (!capture_end(p, ptr)) {
  1222. return false;
  1223. }
  1224. buf = accumulate_getptr(p, &len);
  1225. memset(seconds_buf, 0, 14);
  1226. memset(nanos_buf, 0, 12);
  1227. /* Find out base end. The maximus duration is 315576000000, which cannot be
  1228. * represented by double without losing precision. Thus, we need to handle
  1229. * fraction and base separately. */
  1230. for (fraction_start = 0; fraction_start < len && buf[fraction_start] != '.';
  1231. fraction_start++);
  1232. /* Parse base */
  1233. memcpy(seconds_buf, buf, fraction_start);
  1234. seconds = strtol(seconds_buf, &end, 10);
  1235. if (errno == ERANGE || end != seconds_buf + fraction_start) {
  1236. upb_status_seterrf(p->status, "error parsing duration: %s",
  1237. seconds_buf);
  1238. return false;
  1239. }
  1240. if (seconds > 315576000000) {
  1241. upb_status_seterrf(p->status, "error parsing duration: "
  1242. "maximum acceptable value is "
  1243. "315576000000");
  1244. return false;
  1245. }
  1246. if (seconds < -315576000000) {
  1247. upb_status_seterrf(p->status, "error parsing duration: "
  1248. "minimum acceptable value is "
  1249. "-315576000000");
  1250. return false;
  1251. }
  1252. /* Parse fraction */
  1253. nanos_buf[0] = '0';
  1254. memcpy(nanos_buf + 1, buf + fraction_start, len - fraction_start);
  1255. val = strtod(nanos_buf, &end);
  1256. if (errno == ERANGE || end != nanos_buf + len - fraction_start + 1) {
  1257. upb_status_seterrf(p->status, "error parsing duration: %s",
  1258. nanos_buf);
  1259. return false;
  1260. }
  1261. nanos = val * 1000000000;
  1262. if (seconds < 0) nanos = -nanos;
  1263. /* Clean up buffer */
  1264. multipart_end(p);
  1265. /* Set seconds */
  1266. start_member(p);
  1267. capture_begin(p, seconds_membername);
  1268. capture_end(p, seconds_membername + 7);
  1269. end_membername(p);
  1270. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  1271. end_member(p);
  1272. /* Set nanos */
  1273. start_member(p);
  1274. capture_begin(p, nanos_membername);
  1275. capture_end(p, nanos_membername + 5);
  1276. end_membername(p);
  1277. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  1278. end_member(p);
  1279. /* Continue previous arena */
  1280. multipart_startaccum(p);
  1281. return true;
  1282. }
  1283. static int parse_timestamp_number(upb_json_parser *p) {
  1284. size_t len;
  1285. const char *buf;
  1286. int val;
  1287. /* atoi() and friends unfortunately do not support specifying the length of
  1288. * the input string, so we need to force a copy into a NULL-terminated buffer. */
  1289. multipart_text(p, "\0", 1, false);
  1290. buf = accumulate_getptr(p, &len);
  1291. val = atoi(buf);
  1292. multipart_end(p);
  1293. multipart_startaccum(p);
  1294. return val;
  1295. }
  1296. static void start_year(upb_json_parser *p, const char *ptr) {
  1297. capture_begin(p, ptr);
  1298. }
  1299. static bool end_year(upb_json_parser *p, const char *ptr) {
  1300. if (!capture_end(p, ptr)) {
  1301. return false;
  1302. }
  1303. p->tm.tm_year = parse_timestamp_number(p) - 1900;
  1304. return true;
  1305. }
  1306. static void start_month(upb_json_parser *p, const char *ptr) {
  1307. capture_begin(p, ptr);
  1308. }
  1309. static bool end_month(upb_json_parser *p, const char *ptr) {
  1310. if (!capture_end(p, ptr)) {
  1311. return false;
  1312. }
  1313. p->tm.tm_mon = parse_timestamp_number(p) - 1;
  1314. return true;
  1315. }
  1316. static void start_day(upb_json_parser *p, const char *ptr) {
  1317. capture_begin(p, ptr);
  1318. }
  1319. static bool end_day(upb_json_parser *p, const char *ptr) {
  1320. if (!capture_end(p, ptr)) {
  1321. return false;
  1322. }
  1323. p->tm.tm_mday = parse_timestamp_number(p);
  1324. return true;
  1325. }
  1326. static void start_hour(upb_json_parser *p, const char *ptr) {
  1327. capture_begin(p, ptr);
  1328. }
  1329. static bool end_hour(upb_json_parser *p, const char *ptr) {
  1330. if (!capture_end(p, ptr)) {
  1331. return false;
  1332. }
  1333. p->tm.tm_hour = parse_timestamp_number(p);
  1334. return true;
  1335. }
  1336. static void start_minute(upb_json_parser *p, const char *ptr) {
  1337. capture_begin(p, ptr);
  1338. }
  1339. static bool end_minute(upb_json_parser *p, const char *ptr) {
  1340. if (!capture_end(p, ptr)) {
  1341. return false;
  1342. }
  1343. p->tm.tm_min = parse_timestamp_number(p);
  1344. return true;
  1345. }
  1346. static void start_second(upb_json_parser *p, const char *ptr) {
  1347. capture_begin(p, ptr);
  1348. }
  1349. static bool end_second(upb_json_parser *p, const char *ptr) {
  1350. if (!capture_end(p, ptr)) {
  1351. return false;
  1352. }
  1353. p->tm.tm_sec = parse_timestamp_number(p);
  1354. return true;
  1355. }
  1356. static void start_timestamp_base(upb_json_parser *p) {
  1357. memset(&p->tm, 0, sizeof(struct tm));
  1358. }
  1359. static void start_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  1360. capture_begin(p, ptr);
  1361. }
  1362. static bool end_timestamp_fraction(upb_json_parser *p, const char *ptr) {
  1363. size_t len;
  1364. const char *buf;
  1365. char nanos_buf[12];
  1366. char *end;
  1367. double val = 0.0;
  1368. int32_t nanos;
  1369. const char *nanos_membername = "nanos";
  1370. memset(nanos_buf, 0, 12);
  1371. if (!capture_end(p, ptr)) {
  1372. return false;
  1373. }
  1374. buf = accumulate_getptr(p, &len);
  1375. if (len > 10) {
  1376. upb_status_seterrf(p->status,
  1377. "error parsing timestamp: at most 9-digit fraction.");
  1378. return false;
  1379. }
  1380. /* Parse nanos */
  1381. nanos_buf[0] = '0';
  1382. memcpy(nanos_buf + 1, buf, len);
  1383. val = strtod(nanos_buf, &end);
  1384. if (errno == ERANGE || end != nanos_buf + len + 1) {
  1385. upb_status_seterrf(p->status, "error parsing timestamp nanos: %s",
  1386. nanos_buf);
  1387. return false;
  1388. }
  1389. nanos = val * 1000000000;
  1390. /* Clean up previous environment */
  1391. multipart_end(p);
  1392. /* Set nanos */
  1393. start_member(p);
  1394. capture_begin(p, nanos_membername);
  1395. capture_end(p, nanos_membername + 5);
  1396. end_membername(p);
  1397. upb_sink_putint32(p->top->sink, parser_getsel(p), nanos);
  1398. end_member(p);
  1399. /* Continue previous environment */
  1400. multipart_startaccum(p);
  1401. return true;
  1402. }
  1403. static void start_timestamp_zone(upb_json_parser *p, const char *ptr) {
  1404. capture_begin(p, ptr);
  1405. }
  1406. static int div_round_up2(int n, int d) {
  1407. return (n + d - 1) / d;
  1408. }
  1409. /* epoch_days(1970, 1, 1) == 1970-01-01 == 0. */
  1410. static int epoch_days(int year, int month, int day) {
  1411. static const uint16_t month_yday[12] = {0, 31, 59, 90, 120, 151,
  1412. 181, 212, 243, 273, 304, 334};
  1413. int febs_since_0 = month > 2 ? year + 1 : year;
  1414. int leap_days_since_0 = div_round_up2(febs_since_0, 4) -
  1415. div_round_up2(febs_since_0, 100) +
  1416. div_round_up2(febs_since_0, 400);
  1417. int days_since_0 =
  1418. 365 * year + month_yday[month - 1] + (day - 1) + leap_days_since_0;
  1419. /* Convert from 0-epoch (0001-01-01 BC) to Unix Epoch (1970-01-01 AD).
  1420. * Since the "BC" system does not have a year zero, 1 BC == year zero. */
  1421. return days_since_0 - 719528;
  1422. }
  1423. static int64_t upb_timegm(const struct tm *tp) {
  1424. int64_t ret = epoch_days(tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday);
  1425. ret = (ret * 24) + tp->tm_hour;
  1426. ret = (ret * 60) + tp->tm_min;
  1427. ret = (ret * 60) + tp->tm_sec;
  1428. return ret;
  1429. }
  1430. static bool end_timestamp_zone(upb_json_parser *p, const char *ptr) {
  1431. size_t len;
  1432. const char *buf;
  1433. int hours;
  1434. int64_t seconds;
  1435. const char *seconds_membername = "seconds";
  1436. if (!capture_end(p, ptr)) {
  1437. return false;
  1438. }
  1439. buf = accumulate_getptr(p, &len);
  1440. if (buf[0] != 'Z') {
  1441. if (sscanf(buf + 1, "%2d:00", &hours) != 1) {
  1442. upb_status_seterrf(p->status, "error parsing timestamp offset");
  1443. return false;
  1444. }
  1445. if (buf[0] == '+') {
  1446. hours = -hours;
  1447. }
  1448. p->tm.tm_hour += hours;
  1449. }
  1450. /* Normalize tm */
  1451. seconds = upb_timegm(&p->tm);
  1452. /* Check timestamp boundary */
  1453. if (seconds < -62135596800) {
  1454. upb_status_seterrf(p->status, "error parsing timestamp: "
  1455. "minimum acceptable value is "
  1456. "0001-01-01T00:00:00Z");
  1457. return false;
  1458. }
  1459. /* Clean up previous environment */
  1460. multipart_end(p);
  1461. /* Set seconds */
  1462. start_member(p);
  1463. capture_begin(p, seconds_membername);
  1464. capture_end(p, seconds_membername + 7);
  1465. end_membername(p);
  1466. upb_sink_putint64(p->top->sink, parser_getsel(p), seconds);
  1467. end_member(p);
  1468. /* Continue previous environment */
  1469. multipart_startaccum(p);
  1470. return true;
  1471. }
  1472. static void start_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  1473. capture_begin(p, ptr);
  1474. }
  1475. static bool end_fieldmask_path_text(upb_json_parser *p, const char *ptr) {
  1476. return capture_end(p, ptr);
  1477. }
  1478. static bool start_fieldmask_path(upb_json_parser *p) {
  1479. upb_jsonparser_frame *inner;
  1480. upb_selector_t sel;
  1481. if (!check_stack(p)) return false;
  1482. /* Start a new parser frame: parser frames correspond one-to-one with
  1483. * handler frames, and string events occur in a sub-frame. */
  1484. inner = start_jsonparser_frame(p);
  1485. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  1486. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  1487. inner->m = p->top->m;
  1488. inner->f = p->top->f;
  1489. p->top = inner;
  1490. multipart_startaccum(p);
  1491. return true;
  1492. }
  1493. static bool lower_camel_push(
  1494. upb_json_parser *p, upb_selector_t sel, const char *ptr, size_t len) {
  1495. const char *limit = ptr + len;
  1496. bool first = true;
  1497. for (;ptr < limit; ptr++) {
  1498. if (*ptr >= 'A' && *ptr <= 'Z' && !first) {
  1499. char lower = tolower(*ptr);
  1500. upb_sink_putstring(p->top->sink, sel, "_", 1, NULL);
  1501. upb_sink_putstring(p->top->sink, sel, &lower, 1, NULL);
  1502. } else {
  1503. upb_sink_putstring(p->top->sink, sel, ptr, 1, NULL);
  1504. }
  1505. first = false;
  1506. }
  1507. return true;
  1508. }
  1509. static bool end_fieldmask_path(upb_json_parser *p) {
  1510. upb_selector_t sel;
  1511. if (!lower_camel_push(
  1512. p, getsel_for_handlertype(p, UPB_HANDLER_STRING),
  1513. p->accumulated, p->accumulated_len)) {
  1514. return false;
  1515. }
  1516. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  1517. upb_sink_endstr(p->top->sink, sel);
  1518. p->top--;
  1519. multipart_end(p);
  1520. return true;
  1521. }
  1522. static void start_member(upb_json_parser *p) {
  1523. UPB_ASSERT(!p->top->f);
  1524. multipart_startaccum(p);
  1525. }
  1526. /* Helper: invoked during parse_mapentry() to emit the mapentry message's key
  1527. * field based on the current contents of the accumulate buffer. */
  1528. static bool parse_mapentry_key(upb_json_parser *p) {
  1529. size_t len;
  1530. const char *buf = accumulate_getptr(p, &len);
  1531. /* Emit the key field. We do a bit of ad-hoc parsing here because the
  1532. * parser state machine has already decided that this is a string field
  1533. * name, and we are reinterpreting it as some arbitrary key type. In
  1534. * particular, integer and bool keys are quoted, so we need to parse the
  1535. * quoted string contents here. */
  1536. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_KEY);
  1537. if (p->top->f == NULL) {
  1538. upb_status_seterrmsg(p->status, "mapentry message has no key");
  1539. return false;
  1540. }
  1541. switch (upb_fielddef_type(p->top->f)) {
  1542. case UPB_TYPE_INT32:
  1543. case UPB_TYPE_INT64:
  1544. case UPB_TYPE_UINT32:
  1545. case UPB_TYPE_UINT64:
  1546. /* Invoke end_number. The accum buffer has the number's text already. */
  1547. if (!parse_number(p, true)) {
  1548. return false;
  1549. }
  1550. break;
  1551. case UPB_TYPE_BOOL:
  1552. if (len == 4 && !strncmp(buf, "true", 4)) {
  1553. if (!parser_putbool(p, true)) {
  1554. return false;
  1555. }
  1556. } else if (len == 5 && !strncmp(buf, "false", 5)) {
  1557. if (!parser_putbool(p, false)) {
  1558. return false;
  1559. }
  1560. } else {
  1561. upb_status_seterrmsg(p->status,
  1562. "Map bool key not 'true' or 'false'");
  1563. return false;
  1564. }
  1565. multipart_end(p);
  1566. break;
  1567. case UPB_TYPE_STRING:
  1568. case UPB_TYPE_BYTES: {
  1569. upb_sink subsink;
  1570. upb_selector_t sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  1571. upb_sink_startstr(p->top->sink, sel, len, &subsink);
  1572. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  1573. upb_sink_putstring(subsink, sel, buf, len, NULL);
  1574. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  1575. upb_sink_endstr(subsink, sel);
  1576. multipart_end(p);
  1577. break;
  1578. }
  1579. default:
  1580. upb_status_seterrmsg(p->status, "Invalid field type for map key");
  1581. return false;
  1582. }
  1583. return true;
  1584. }
  1585. /* Helper: emit one map entry (as a submessage in the map field sequence). This
  1586. * is invoked from end_membername(), at the end of the map entry's key string,
  1587. * with the map key in the accumulate buffer. It parses the key from that
  1588. * buffer, emits the handler calls to start the mapentry submessage (setting up
  1589. * its subframe in the process), and sets up state in the subframe so that the
  1590. * value parser (invoked next) will emit the mapentry's value field and then
  1591. * end the mapentry message. */
  1592. static bool handle_mapentry(upb_json_parser *p) {
  1593. const upb_fielddef *mapfield;
  1594. const upb_msgdef *mapentrymsg;
  1595. upb_jsonparser_frame *inner;
  1596. upb_selector_t sel;
  1597. /* Map entry: p->top->sink is the seq frame, so we need to start a frame
  1598. * for the mapentry itself, and then set |f| in that frame so that the map
  1599. * value field is parsed, and also set a flag to end the frame after the
  1600. * map-entry value is parsed. */
  1601. if (!check_stack(p)) return false;
  1602. mapfield = p->top->mapfield;
  1603. mapentrymsg = upb_fielddef_msgsubdef(mapfield);
  1604. inner = start_jsonparser_frame(p);
  1605. p->top->f = mapfield;
  1606. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  1607. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  1608. inner->m = mapentrymsg;
  1609. inner->mapfield = mapfield;
  1610. /* Don't set this to true *yet* -- we reuse parsing handlers below to push
  1611. * the key field value to the sink, and these handlers will pop the frame
  1612. * if they see is_mapentry (when invoked by the parser state machine, they
  1613. * would have just seen the map-entry value, not key). */
  1614. inner->is_mapentry = false;
  1615. p->top = inner;
  1616. /* send STARTMSG in submsg frame. */
  1617. upb_sink_startmsg(p->top->sink);
  1618. parse_mapentry_key(p);
  1619. /* Set up the value field to receive the map-entry value. */
  1620. p->top->f = upb_msgdef_itof(p->top->m, UPB_MAPENTRY_VALUE);
  1621. p->top->is_mapentry = true; /* set up to pop frame after value is parsed. */
  1622. p->top->mapfield = mapfield;
  1623. if (p->top->f == NULL) {
  1624. upb_status_seterrmsg(p->status, "mapentry message has no value");
  1625. return false;
  1626. }
  1627. return true;
  1628. }
  1629. static bool end_membername(upb_json_parser *p) {
  1630. UPB_ASSERT(!p->top->f);
  1631. if (!p->top->m) {
  1632. p->top->is_unknown_field = true;
  1633. multipart_end(p);
  1634. return true;
  1635. }
  1636. if (p->top->is_any) {
  1637. return end_any_membername(p);
  1638. } else if (p->top->is_map) {
  1639. return handle_mapentry(p);
  1640. } else {
  1641. size_t len;
  1642. const char *buf = accumulate_getptr(p, &len);
  1643. upb_value v;
  1644. if (upb_strtable_lookup2(p->top->name_table, buf, len, &v)) {
  1645. p->top->f = upb_value_getconstptr(v);
  1646. multipart_end(p);
  1647. return true;
  1648. } else if (p->ignore_json_unknown) {
  1649. p->top->is_unknown_field = true;
  1650. multipart_end(p);
  1651. return true;
  1652. } else {
  1653. upb_status_seterrf(p->status, "No such field: %.*s\n", (int)len, buf);
  1654. return false;
  1655. }
  1656. }
  1657. }
  1658. static bool end_any_membername(upb_json_parser *p) {
  1659. size_t len;
  1660. const char *buf = accumulate_getptr(p, &len);
  1661. upb_value v;
  1662. if (len == 5 && strncmp(buf, "@type", len) == 0) {
  1663. upb_strtable_lookup2(p->top->name_table, "type_url", 8, &v);
  1664. p->top->f = upb_value_getconstptr(v);
  1665. multipart_end(p);
  1666. return true;
  1667. } else {
  1668. p->top->is_unknown_field = true;
  1669. multipart_end(p);
  1670. return true;
  1671. }
  1672. }
  1673. static void end_member(upb_json_parser *p) {
  1674. /* If we just parsed a map-entry value, end that frame too. */
  1675. if (p->top->is_mapentry) {
  1676. upb_selector_t sel;
  1677. bool ok;
  1678. const upb_fielddef *mapfield;
  1679. UPB_ASSERT(p->top > p->stack);
  1680. /* send ENDMSG on submsg. */
  1681. upb_sink_endmsg(p->top->sink, p->status);
  1682. mapfield = p->top->mapfield;
  1683. /* send ENDSUBMSG in repeated-field-of-mapentries frame. */
  1684. p->top--;
  1685. ok = upb_handlers_getselector(mapfield, UPB_HANDLER_ENDSUBMSG, &sel);
  1686. UPB_ASSUME(ok);
  1687. upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
  1688. }
  1689. p->top->f = NULL;
  1690. p->top->is_unknown_field = false;
  1691. }
  1692. static void start_any_member(upb_json_parser *p, const char *ptr) {
  1693. start_member(p);
  1694. json_parser_any_frame_set_after_type_url_start_once(p->top->any_frame, ptr);
  1695. }
  1696. static void end_any_member(upb_json_parser *p, const char *ptr) {
  1697. json_parser_any_frame_set_before_type_url_end(p->top->any_frame, ptr);
  1698. end_member(p);
  1699. }
  1700. static bool start_subobject(upb_json_parser *p) {
  1701. if (p->top->is_unknown_field) {
  1702. if (!check_stack(p)) return false;
  1703. p->top = start_jsonparser_frame(p);
  1704. return true;
  1705. }
  1706. if (upb_fielddef_ismap(p->top->f)) {
  1707. upb_jsonparser_frame *inner;
  1708. upb_selector_t sel;
  1709. /* Beginning of a map. Start a new parser frame in a repeated-field
  1710. * context. */
  1711. if (!check_stack(p)) return false;
  1712. inner = start_jsonparser_frame(p);
  1713. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  1714. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  1715. inner->m = upb_fielddef_msgsubdef(p->top->f);
  1716. inner->mapfield = p->top->f;
  1717. inner->is_map = true;
  1718. p->top = inner;
  1719. return true;
  1720. } else if (upb_fielddef_issubmsg(p->top->f)) {
  1721. upb_jsonparser_frame *inner;
  1722. upb_selector_t sel;
  1723. /* Beginning of a subobject. Start a new parser frame in the submsg
  1724. * context. */
  1725. if (!check_stack(p)) return false;
  1726. inner = start_jsonparser_frame(p);
  1727. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSUBMSG);
  1728. upb_sink_startsubmsg(p->top->sink, sel, &inner->sink);
  1729. inner->m = upb_fielddef_msgsubdef(p->top->f);
  1730. set_name_table(p, inner);
  1731. p->top = inner;
  1732. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  1733. p->top->is_any = true;
  1734. p->top->any_frame = json_parser_any_frame_new(p);
  1735. } else {
  1736. p->top->is_any = false;
  1737. p->top->any_frame = NULL;
  1738. }
  1739. return true;
  1740. } else {
  1741. upb_status_seterrf(p->status,
  1742. "Object specified for non-message/group field: %s",
  1743. upb_fielddef_name(p->top->f));
  1744. return false;
  1745. }
  1746. }
  1747. static bool start_subobject_full(upb_json_parser *p) {
  1748. if (is_top_level(p)) {
  1749. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  1750. start_value_object(p, VALUE_STRUCTVALUE);
  1751. if (!start_subobject(p)) return false;
  1752. start_structvalue_object(p);
  1753. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  1754. start_structvalue_object(p);
  1755. } else {
  1756. return true;
  1757. }
  1758. } else if (is_wellknown_field(p, UPB_WELLKNOWN_STRUCT)) {
  1759. if (!start_subobject(p)) return false;
  1760. start_structvalue_object(p);
  1761. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE)) {
  1762. if (!start_subobject(p)) return false;
  1763. start_value_object(p, VALUE_STRUCTVALUE);
  1764. if (!start_subobject(p)) return false;
  1765. start_structvalue_object(p);
  1766. }
  1767. return start_subobject(p);
  1768. }
  1769. static void end_subobject(upb_json_parser *p) {
  1770. if (is_top_level(p)) {
  1771. return;
  1772. }
  1773. if (p->top->is_map) {
  1774. upb_selector_t sel;
  1775. p->top--;
  1776. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  1777. upb_sink_endseq(p->top->sink, sel);
  1778. } else {
  1779. upb_selector_t sel;
  1780. bool is_unknown = p->top->m == NULL;
  1781. p->top--;
  1782. if (!is_unknown) {
  1783. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSUBMSG);
  1784. upb_sink_endsubmsg(p->top->sink, (p->top + 1)->sink, sel);
  1785. }
  1786. }
  1787. }
  1788. static void end_subobject_full(upb_json_parser *p) {
  1789. end_subobject(p);
  1790. if (is_wellknown_msg(p, UPB_WELLKNOWN_STRUCT)) {
  1791. end_structvalue_object(p);
  1792. if (!is_top_level(p)) {
  1793. end_subobject(p);
  1794. }
  1795. }
  1796. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  1797. end_value_object(p);
  1798. if (!is_top_level(p)) {
  1799. end_subobject(p);
  1800. }
  1801. }
  1802. }
  1803. static bool start_array(upb_json_parser *p) {
  1804. upb_jsonparser_frame *inner;
  1805. upb_selector_t sel;
  1806. if (is_top_level(p)) {
  1807. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  1808. start_value_object(p, VALUE_LISTVALUE);
  1809. if (!start_subobject(p)) return false;
  1810. start_listvalue_object(p);
  1811. } else if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  1812. start_listvalue_object(p);
  1813. } else {
  1814. return false;
  1815. }
  1816. } else if (is_wellknown_field(p, UPB_WELLKNOWN_LISTVALUE) &&
  1817. (!upb_fielddef_isseq(p->top->f) ||
  1818. p->top->is_repeated)) {
  1819. if (!start_subobject(p)) return false;
  1820. start_listvalue_object(p);
  1821. } else if (is_wellknown_field(p, UPB_WELLKNOWN_VALUE) &&
  1822. (!upb_fielddef_isseq(p->top->f) ||
  1823. p->top->is_repeated)) {
  1824. if (!start_subobject(p)) return false;
  1825. start_value_object(p, VALUE_LISTVALUE);
  1826. if (!start_subobject(p)) return false;
  1827. start_listvalue_object(p);
  1828. }
  1829. if (p->top->is_unknown_field) {
  1830. inner = start_jsonparser_frame(p);
  1831. inner->is_unknown_field = true;
  1832. p->top = inner;
  1833. return true;
  1834. }
  1835. if (!upb_fielddef_isseq(p->top->f)) {
  1836. upb_status_seterrf(p->status,
  1837. "Array specified for non-repeated field: %s",
  1838. upb_fielddef_name(p->top->f));
  1839. return false;
  1840. }
  1841. if (!check_stack(p)) return false;
  1842. inner = start_jsonparser_frame(p);
  1843. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSEQ);
  1844. upb_sink_startseq(p->top->sink, sel, &inner->sink);
  1845. inner->m = p->top->m;
  1846. inner->f = p->top->f;
  1847. inner->is_repeated = true;
  1848. p->top = inner;
  1849. return true;
  1850. }
  1851. static void end_array(upb_json_parser *p) {
  1852. upb_selector_t sel;
  1853. UPB_ASSERT(p->top > p->stack);
  1854. p->top--;
  1855. if (p->top->is_unknown_field) {
  1856. return;
  1857. }
  1858. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSEQ);
  1859. upb_sink_endseq(p->top->sink, sel);
  1860. if (is_wellknown_msg(p, UPB_WELLKNOWN_LISTVALUE)) {
  1861. end_listvalue_object(p);
  1862. if (!is_top_level(p)) {
  1863. end_subobject(p);
  1864. }
  1865. }
  1866. if (is_wellknown_msg(p, UPB_WELLKNOWN_VALUE)) {
  1867. end_value_object(p);
  1868. if (!is_top_level(p)) {
  1869. end_subobject(p);
  1870. }
  1871. }
  1872. }
  1873. static void start_object(upb_json_parser *p) {
  1874. if (!p->top->is_map && p->top->m != NULL) {
  1875. upb_sink_startmsg(p->top->sink);
  1876. }
  1877. }
  1878. static void end_object(upb_json_parser *p) {
  1879. if (!p->top->is_map && p->top->m != NULL) {
  1880. upb_sink_endmsg(p->top->sink, p->status);
  1881. }
  1882. }
  1883. static void start_any_object(upb_json_parser *p, const char *ptr) {
  1884. start_object(p);
  1885. p->top->any_frame->before_type_url_start = ptr;
  1886. p->top->any_frame->before_type_url_end = ptr;
  1887. }
  1888. static bool end_any_object(upb_json_parser *p, const char *ptr) {
  1889. const char *value_membername = "value";
  1890. bool is_well_known_packed = false;
  1891. const char *packed_end = ptr + 1;
  1892. upb_selector_t sel;
  1893. upb_jsonparser_frame *inner;
  1894. if (json_parser_any_frame_has_value(p->top->any_frame) &&
  1895. !json_parser_any_frame_has_type_url(p->top->any_frame)) {
  1896. upb_status_seterrmsg(p->status, "No valid type url");
  1897. return false;
  1898. }
  1899. /* Well known types data is represented as value field. */
  1900. if (upb_msgdef_wellknowntype(p->top->any_frame->parser->top->m) !=
  1901. UPB_WELLKNOWN_UNSPECIFIED) {
  1902. is_well_known_packed = true;
  1903. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  1904. p->top->any_frame->before_type_url_start =
  1905. memchr(p->top->any_frame->before_type_url_start, ':',
  1906. p->top->any_frame->before_type_url_end -
  1907. p->top->any_frame->before_type_url_start);
  1908. if (p->top->any_frame->before_type_url_start == NULL) {
  1909. upb_status_seterrmsg(p->status, "invalid data for well known type.");
  1910. return false;
  1911. }
  1912. p->top->any_frame->before_type_url_start++;
  1913. }
  1914. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  1915. p->top->any_frame->after_type_url_start =
  1916. memchr(p->top->any_frame->after_type_url_start, ':',
  1917. (ptr + 1) -
  1918. p->top->any_frame->after_type_url_start);
  1919. if (p->top->any_frame->after_type_url_start == NULL) {
  1920. upb_status_seterrmsg(p->status, "Invalid data for well known type.");
  1921. return false;
  1922. }
  1923. p->top->any_frame->after_type_url_start++;
  1924. packed_end = ptr;
  1925. }
  1926. }
  1927. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame)) {
  1928. if (!parse(p->top->any_frame->parser, NULL,
  1929. p->top->any_frame->before_type_url_start,
  1930. p->top->any_frame->before_type_url_end -
  1931. p->top->any_frame->before_type_url_start, NULL)) {
  1932. return false;
  1933. }
  1934. } else {
  1935. if (!is_well_known_packed) {
  1936. if (!parse(p->top->any_frame->parser, NULL, "{", 1, NULL)) {
  1937. return false;
  1938. }
  1939. }
  1940. }
  1941. if (json_parser_any_frame_has_value_before_type_url(p->top->any_frame) &&
  1942. json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  1943. if (!parse(p->top->any_frame->parser, NULL, ",", 1, NULL)) {
  1944. return false;
  1945. }
  1946. }
  1947. if (json_parser_any_frame_has_value_after_type_url(p->top->any_frame)) {
  1948. if (!parse(p->top->any_frame->parser, NULL,
  1949. p->top->any_frame->after_type_url_start,
  1950. packed_end - p->top->any_frame->after_type_url_start, NULL)) {
  1951. return false;
  1952. }
  1953. } else {
  1954. if (!is_well_known_packed) {
  1955. if (!parse(p->top->any_frame->parser, NULL, "}", 1, NULL)) {
  1956. return false;
  1957. }
  1958. }
  1959. }
  1960. if (!end(p->top->any_frame->parser, NULL)) {
  1961. return false;
  1962. }
  1963. p->top->is_any = false;
  1964. /* Set value */
  1965. start_member(p);
  1966. capture_begin(p, value_membername);
  1967. capture_end(p, value_membername + 5);
  1968. end_membername(p);
  1969. if (!check_stack(p)) return false;
  1970. inner = p->top + 1;
  1971. sel = getsel_for_handlertype(p, UPB_HANDLER_STARTSTR);
  1972. upb_sink_startstr(p->top->sink, sel, 0, &inner->sink);
  1973. sel = getsel_for_handlertype(p, UPB_HANDLER_STRING);
  1974. upb_sink_putstring(inner->sink, sel, p->top->any_frame->stringsink.ptr,
  1975. p->top->any_frame->stringsink.len, NULL);
  1976. sel = getsel_for_handlertype(p, UPB_HANDLER_ENDSTR);
  1977. upb_sink_endstr(inner->sink, sel);
  1978. end_member(p);
  1979. end_object(p);
  1980. /* Deallocate any parse frame. */
  1981. json_parser_any_frame_free(p->top->any_frame);
  1982. return true;
  1983. }
  1984. static bool is_string_wrapper(const upb_msgdef *m) {
  1985. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  1986. return type == UPB_WELLKNOWN_STRINGVALUE ||
  1987. type == UPB_WELLKNOWN_BYTESVALUE;
  1988. }
  1989. static bool is_fieldmask(const upb_msgdef *m) {
  1990. upb_wellknowntype_t type = upb_msgdef_wellknowntype(m);
  1991. return type == UPB_WELLKNOWN_FIELDMASK;
  1992. }
  1993. static void start_fieldmask_object(upb_json_parser *p) {
  1994. const char *membername = "paths";
  1995. start_object(p);
  1996. /* Set up context for parsing value */
  1997. start_member(p);
  1998. capture_begin(p, membername);
  1999. capture_end(p, membername + 5);
  2000. end_membername(p);
  2001. start_array(p);
  2002. }
  2003. static void end_fieldmask_object(upb_json_parser *p) {
  2004. end_array(p);
  2005. end_member(p);
  2006. end_object(p);
  2007. }
  2008. static void start_wrapper_object(upb_json_parser *p) {
  2009. const char *membername = "value";
  2010. start_object(p);
  2011. /* Set up context for parsing value */
  2012. start_member(p);
  2013. capture_begin(p, membername);
  2014. capture_end(p, membername + 5);
  2015. end_membername(p);
  2016. }
  2017. static void end_wrapper_object(upb_json_parser *p) {
  2018. end_member(p);
  2019. end_object(p);
  2020. }
  2021. static void start_value_object(upb_json_parser *p, int value_type) {
  2022. const char *nullmember = "null_value";
  2023. const char *numbermember = "number_value";
  2024. const char *stringmember = "string_value";
  2025. const char *boolmember = "bool_value";
  2026. const char *structmember = "struct_value";
  2027. const char *listmember = "list_value";
  2028. const char *membername = "";
  2029. switch (value_type) {
  2030. case VALUE_NULLVALUE:
  2031. membername = nullmember;
  2032. break;
  2033. case VALUE_NUMBERVALUE:
  2034. membername = numbermember;
  2035. break;
  2036. case VALUE_STRINGVALUE:
  2037. membername = stringmember;
  2038. break;
  2039. case VALUE_BOOLVALUE:
  2040. membername = boolmember;
  2041. break;
  2042. case VALUE_STRUCTVALUE:
  2043. membername = structmember;
  2044. break;
  2045. case VALUE_LISTVALUE:
  2046. membername = listmember;
  2047. break;
  2048. }
  2049. start_object(p);
  2050. /* Set up context for parsing value */
  2051. start_member(p);
  2052. capture_begin(p, membername);
  2053. capture_end(p, membername + strlen(membername));
  2054. end_membername(p);
  2055. }
  2056. static void end_value_object(upb_json_parser *p) {
  2057. end_member(p);
  2058. end_object(p);
  2059. }
  2060. static void start_listvalue_object(upb_json_parser *p) {
  2061. const char *membername = "values";
  2062. start_object(p);
  2063. /* Set up context for parsing value */
  2064. start_member(p);
  2065. capture_begin(p, membername);
  2066. capture_end(p, membername + strlen(membername));
  2067. end_membername(p);
  2068. }
  2069. static void end_listvalue_object(upb_json_parser *p) {
  2070. end_member(p);
  2071. end_object(p);
  2072. }
  2073. static void start_structvalue_object(upb_json_parser *p) {
  2074. const char *membername = "fields";
  2075. start_object(p);
  2076. /* Set up context for parsing value */
  2077. start_member(p);
  2078. capture_begin(p, membername);
  2079. capture_end(p, membername + strlen(membername));
  2080. end_membername(p);
  2081. }
  2082. static void end_structvalue_object(upb_json_parser *p) {
  2083. end_member(p);
  2084. end_object(p);
  2085. }
  2086. static bool is_top_level(upb_json_parser *p) {
  2087. return p->top == p->stack && p->top->f == NULL && !p->top->is_unknown_field;
  2088. }
  2089. static bool is_wellknown_msg(upb_json_parser *p, upb_wellknowntype_t type) {
  2090. return p->top->m != NULL && upb_msgdef_wellknowntype(p->top->m) == type;
  2091. }
  2092. static bool is_wellknown_field(upb_json_parser *p, upb_wellknowntype_t type) {
  2093. return p->top->f != NULL &&
  2094. upb_fielddef_issubmsg(p->top->f) &&
  2095. (upb_msgdef_wellknowntype(upb_fielddef_msgsubdef(p->top->f))
  2096. == type);
  2097. }
  2098. static bool does_number_wrapper_start(upb_json_parser *p) {
  2099. return p->top->f != NULL &&
  2100. upb_fielddef_issubmsg(p->top->f) &&
  2101. upb_msgdef_isnumberwrapper(upb_fielddef_msgsubdef(p->top->f));
  2102. }
  2103. static bool does_number_wrapper_end(upb_json_parser *p) {
  2104. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  2105. }
  2106. static bool is_number_wrapper_object(upb_json_parser *p) {
  2107. return p->top->m != NULL && upb_msgdef_isnumberwrapper(p->top->m);
  2108. }
  2109. static bool does_string_wrapper_start(upb_json_parser *p) {
  2110. return p->top->f != NULL &&
  2111. upb_fielddef_issubmsg(p->top->f) &&
  2112. is_string_wrapper(upb_fielddef_msgsubdef(p->top->f));
  2113. }
  2114. static bool does_string_wrapper_end(upb_json_parser *p) {
  2115. return p->top->m != NULL && is_string_wrapper(p->top->m);
  2116. }
  2117. static bool is_string_wrapper_object(upb_json_parser *p) {
  2118. return p->top->m != NULL && is_string_wrapper(p->top->m);
  2119. }
  2120. static bool does_fieldmask_start(upb_json_parser *p) {
  2121. return p->top->f != NULL &&
  2122. upb_fielddef_issubmsg(p->top->f) &&
  2123. is_fieldmask(upb_fielddef_msgsubdef(p->top->f));
  2124. }
  2125. static bool does_fieldmask_end(upb_json_parser *p) {
  2126. return p->top->m != NULL && is_fieldmask(p->top->m);
  2127. }
  2128. #define CHECK_RETURN_TOP(x) if (!(x)) goto error
  2129. /* The actual parser **********************************************************/
  2130. /* What follows is the Ragel parser itself. The language is specified in Ragel
  2131. * and the actions call our C functions above.
  2132. *
  2133. * Ragel has an extensive set of functionality, and we use only a small part of
  2134. * it. There are many action types but we only use a few:
  2135. *
  2136. * ">" -- transition into a machine
  2137. * "%" -- transition out of a machine
  2138. * "@" -- transition into a final state of a machine.
  2139. *
  2140. * "@" transitions are tricky because a machine can transition into a final
  2141. * state repeatedly. But in some cases we know this can't happen, for example
  2142. * a string which is delimited by a final '"' can only transition into its
  2143. * final state once, when the closing '"' is seen. */
  2144. %%{
  2145. machine json;
  2146. ws = space*;
  2147. integer = "0" | /[1-9]/ /[0-9]/*;
  2148. decimal = "." /[0-9]/+;
  2149. exponent = /[eE]/ /[+\-]/? /[0-9]/+;
  2150. number_machine :=
  2151. ("-"? integer decimal? exponent?)
  2152. %/{ fhold; fret; }
  2153. <: any
  2154. >{ fhold; fret; }
  2155. ;
  2156. number = /[0-9\-]/ >{ fhold; fcall number_machine; };
  2157. text =
  2158. /[^\\"]/+
  2159. >{ start_text(parser, p); }
  2160. %{ CHECK_RETURN_TOP(end_text(parser, p)); }
  2161. ;
  2162. unicode_char =
  2163. "\\u"
  2164. /[0-9A-Fa-f]/{4}
  2165. >{ start_hex(parser); }
  2166. ${ hexdigit(parser, p); }
  2167. %{ CHECK_RETURN_TOP(end_hex(parser)); }
  2168. ;
  2169. escape_char =
  2170. "\\"
  2171. /[rtbfn"\/\\]/
  2172. >{ CHECK_RETURN_TOP(escape(parser, p)); }
  2173. ;
  2174. string_machine :=
  2175. (text | unicode_char | escape_char)**
  2176. '"'
  2177. @{ fhold; fret; }
  2178. ;
  2179. year =
  2180. (digit digit digit digit)
  2181. >{ start_year(parser, p); }
  2182. %{ CHECK_RETURN_TOP(end_year(parser, p)); }
  2183. ;
  2184. month =
  2185. (digit digit)
  2186. >{ start_month(parser, p); }
  2187. %{ CHECK_RETURN_TOP(end_month(parser, p)); }
  2188. ;
  2189. day =
  2190. (digit digit)
  2191. >{ start_day(parser, p); }
  2192. %{ CHECK_RETURN_TOP(end_day(parser, p)); }
  2193. ;
  2194. hour =
  2195. (digit digit)
  2196. >{ start_hour(parser, p); }
  2197. %{ CHECK_RETURN_TOP(end_hour(parser, p)); }
  2198. ;
  2199. minute =
  2200. (digit digit)
  2201. >{ start_minute(parser, p); }
  2202. %{ CHECK_RETURN_TOP(end_minute(parser, p)); }
  2203. ;
  2204. second =
  2205. (digit digit)
  2206. >{ start_second(parser, p); }
  2207. %{ CHECK_RETURN_TOP(end_second(parser, p)); }
  2208. ;
  2209. duration_machine :=
  2210. ("-"? integer decimal?)
  2211. >{ start_duration_base(parser, p); }
  2212. %{ CHECK_RETURN_TOP(end_duration_base(parser, p)); }
  2213. 's"'
  2214. @{ fhold; fret; }
  2215. ;
  2216. timestamp_machine :=
  2217. (year "-" month "-" day "T" hour ":" minute ":" second)
  2218. >{ start_timestamp_base(parser); }
  2219. ("." digit+)?
  2220. >{ start_timestamp_fraction(parser, p); }
  2221. %{ CHECK_RETURN_TOP(end_timestamp_fraction(parser, p)); }
  2222. ([+\-] digit digit ":00" | "Z")
  2223. >{ start_timestamp_zone(parser, p); }
  2224. %{ CHECK_RETURN_TOP(end_timestamp_zone(parser, p)); }
  2225. '"'
  2226. @{ fhold; fret; }
  2227. ;
  2228. fieldmask_path_text =
  2229. /[^",]/+
  2230. >{ start_fieldmask_path_text(parser, p); }
  2231. %{ end_fieldmask_path_text(parser, p); }
  2232. ;
  2233. fieldmask_path =
  2234. fieldmask_path_text
  2235. >{ start_fieldmask_path(parser); }
  2236. %{ end_fieldmask_path(parser); }
  2237. ;
  2238. fieldmask_machine :=
  2239. (fieldmask_path ("," fieldmask_path)*)?
  2240. '"'
  2241. @{ fhold; fret; }
  2242. ;
  2243. string =
  2244. '"'
  2245. @{
  2246. if (is_wellknown_msg(parser, UPB_WELLKNOWN_TIMESTAMP)) {
  2247. fcall timestamp_machine;
  2248. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_DURATION)) {
  2249. fcall duration_machine;
  2250. } else if (is_wellknown_msg(parser, UPB_WELLKNOWN_FIELDMASK)) {
  2251. fcall fieldmask_machine;
  2252. } else {
  2253. fcall string_machine;
  2254. }
  2255. }
  2256. '"';
  2257. value2 = ^(space | "]" | "}") >{ fhold; fcall value_machine; } ;
  2258. member =
  2259. ws
  2260. string
  2261. >{
  2262. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  2263. start_any_member(parser, p);
  2264. } else {
  2265. start_member(parser);
  2266. }
  2267. }
  2268. @{ CHECK_RETURN_TOP(end_membername(parser)); }
  2269. ws ":" ws
  2270. value2
  2271. %{
  2272. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  2273. end_any_member(parser, p);
  2274. } else {
  2275. end_member(parser);
  2276. }
  2277. }
  2278. ws;
  2279. object =
  2280. ("{" ws)
  2281. >{
  2282. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  2283. start_any_object(parser, p);
  2284. } else {
  2285. start_object(parser);
  2286. }
  2287. }
  2288. (member ("," member)*)?
  2289. "}"
  2290. >{
  2291. if (is_wellknown_msg(parser, UPB_WELLKNOWN_ANY)) {
  2292. CHECK_RETURN_TOP(end_any_object(parser, p));
  2293. } else {
  2294. end_object(parser);
  2295. }
  2296. }
  2297. ;
  2298. element = ws value2 ws;
  2299. array =
  2300. "["
  2301. >{ CHECK_RETURN_TOP(start_array(parser)); }
  2302. ws
  2303. (element ("," element)*)?
  2304. "]"
  2305. >{ end_array(parser); }
  2306. ;
  2307. value =
  2308. number
  2309. >{ CHECK_RETURN_TOP(start_number(parser, p)); }
  2310. %{ CHECK_RETURN_TOP(end_number(parser, p)); }
  2311. | string
  2312. >{ CHECK_RETURN_TOP(start_stringval(parser)); }
  2313. @{ CHECK_RETURN_TOP(end_stringval(parser)); }
  2314. | "true"
  2315. %{ CHECK_RETURN_TOP(end_bool(parser, true)); }
  2316. | "false"
  2317. %{ CHECK_RETURN_TOP(end_bool(parser, false)); }
  2318. | "null"
  2319. %{ CHECK_RETURN_TOP(end_null(parser)); }
  2320. | object
  2321. >{ CHECK_RETURN_TOP(start_subobject_full(parser)); }
  2322. %{ end_subobject_full(parser); }
  2323. | array;
  2324. value_machine :=
  2325. value
  2326. <: any >{ fhold; fret; } ;
  2327. main := ws value ws;
  2328. }%%
  2329. %% write data noerror nofinal;
  2330. size_t parse(void *closure, const void *hd, const char *buf, size_t size,
  2331. const upb_bufhandle *handle) {
  2332. upb_json_parser *parser = closure;
  2333. /* Variables used by Ragel's generated code. */
  2334. int cs = parser->current_state;
  2335. int *stack = parser->parser_stack;
  2336. int top = parser->parser_top;
  2337. const char *p = buf;
  2338. const char *pe = buf + size;
  2339. const char *eof = &eof_ch;
  2340. parser->handle = handle;
  2341. UPB_UNUSED(hd);
  2342. UPB_UNUSED(handle);
  2343. capture_resume(parser, buf);
  2344. %% write exec;
  2345. if (p != pe) {
  2346. upb_status_seterrf(parser->status, "Parse error at '%.*s'\n", pe - p, p);
  2347. } else {
  2348. capture_suspend(parser, &p);
  2349. }
  2350. error:
  2351. /* Save parsing state back to parser. */
  2352. parser->current_state = cs;
  2353. parser->parser_top = top;
  2354. return p - buf;
  2355. }
  2356. static bool end(void *closure, const void *hd) {
  2357. upb_json_parser *parser = closure;
  2358. /* Prevent compile warning on unused static constants. */
  2359. UPB_UNUSED(json_start);
  2360. UPB_UNUSED(json_en_duration_machine);
  2361. UPB_UNUSED(json_en_fieldmask_machine);
  2362. UPB_UNUSED(json_en_number_machine);
  2363. UPB_UNUSED(json_en_string_machine);
  2364. UPB_UNUSED(json_en_timestamp_machine);
  2365. UPB_UNUSED(json_en_value_machine);
  2366. UPB_UNUSED(json_en_main);
  2367. parse(parser, hd, &eof_ch, 0, NULL);
  2368. return parser->current_state >= %%{ write first_final; }%%;
  2369. }
  2370. static void json_parser_reset(upb_json_parser *p) {
  2371. int cs;
  2372. int top;
  2373. p->top = p->stack;
  2374. init_frame(p->top);
  2375. /* Emit Ragel initialization of the parser. */
  2376. %% write init;
  2377. p->current_state = cs;
  2378. p->parser_top = top;
  2379. accumulate_clear(p);
  2380. p->multipart_state = MULTIPART_INACTIVE;
  2381. p->capture = NULL;
  2382. p->accumulated = NULL;
  2383. }
  2384. static upb_json_parsermethod *parsermethod_new(upb_json_codecache *c,
  2385. const upb_msgdef *md) {
  2386. upb_msg_field_iter i;
  2387. upb_alloc *alloc = upb_arena_alloc(c->arena);
  2388. upb_json_parsermethod *m = upb_malloc(alloc, sizeof(*m));
  2389. m->cache = c;
  2390. upb_byteshandler_init(&m->input_handler_);
  2391. upb_byteshandler_setstring(&m->input_handler_, parse, m);
  2392. upb_byteshandler_setendstr(&m->input_handler_, end, m);
  2393. upb_strtable_init2(&m->name_table, UPB_CTYPE_CONSTPTR, alloc);
  2394. /* Build name_table */
  2395. for(upb_msg_field_begin(&i, md);
  2396. !upb_msg_field_done(&i);
  2397. upb_msg_field_next(&i)) {
  2398. const upb_fielddef *f = upb_msg_iter_field(&i);
  2399. upb_value v = upb_value_constptr(f);
  2400. char *buf;
  2401. /* Add an entry for the JSON name. */
  2402. size_t len = upb_fielddef_getjsonname(f, NULL, 0);
  2403. buf = upb_malloc(alloc, len);
  2404. upb_fielddef_getjsonname(f, buf, len);
  2405. upb_strtable_insert3(&m->name_table, buf, strlen(buf), v, alloc);
  2406. if (strcmp(buf, upb_fielddef_name(f)) != 0) {
  2407. /* Since the JSON name is different from the regular field name, add an
  2408. * entry for the raw name (compliant proto3 JSON parsers must accept
  2409. * both). */
  2410. const char *name = upb_fielddef_name(f);
  2411. upb_strtable_insert3(&m->name_table, name, strlen(name), v, alloc);
  2412. }
  2413. }
  2414. return m;
  2415. }
  2416. /* Public API *****************************************************************/
  2417. upb_json_parser *upb_json_parser_create(upb_arena *arena,
  2418. const upb_json_parsermethod *method,
  2419. const upb_symtab* symtab,
  2420. upb_sink output,
  2421. upb_status *status,
  2422. bool ignore_json_unknown) {
  2423. #ifndef NDEBUG
  2424. const size_t size_before = upb_arena_bytesallocated(arena);
  2425. #endif
  2426. upb_json_parser *p = upb_arena_malloc(arena, sizeof(upb_json_parser));
  2427. if (!p) return false;
  2428. p->arena = arena;
  2429. p->method = method;
  2430. p->status = status;
  2431. p->limit = p->stack + UPB_JSON_MAX_DEPTH;
  2432. p->accumulate_buf = NULL;
  2433. p->accumulate_buf_size = 0;
  2434. upb_bytessink_reset(&p->input_, &method->input_handler_, p);
  2435. json_parser_reset(p);
  2436. p->top->sink = output;
  2437. p->top->m = upb_handlers_msgdef(output.handlers);
  2438. if (is_wellknown_msg(p, UPB_WELLKNOWN_ANY)) {
  2439. p->top->is_any = true;
  2440. p->top->any_frame = json_parser_any_frame_new(p);
  2441. } else {
  2442. p->top->is_any = false;
  2443. p->top->any_frame = NULL;
  2444. }
  2445. set_name_table(p, p->top);
  2446. p->symtab = symtab;
  2447. p->ignore_json_unknown = ignore_json_unknown;
  2448. /* If this fails, uncomment and increase the value in parser.h. */
  2449. /* fprintf(stderr, "%zd\n", upb_arena_bytesallocated(arena) - size_before); */
  2450. UPB_ASSERT_DEBUGVAR(upb_arena_bytesallocated(arena) - size_before <=
  2451. UPB_JSON_PARSER_SIZE);
  2452. return p;
  2453. }
  2454. upb_bytessink upb_json_parser_input(upb_json_parser *p) {
  2455. return p->input_;
  2456. }
  2457. const upb_byteshandler *upb_json_parsermethod_inputhandler(
  2458. const upb_json_parsermethod *m) {
  2459. return &m->input_handler_;
  2460. }
  2461. upb_json_codecache *upb_json_codecache_new(void) {
  2462. upb_alloc *alloc;
  2463. upb_json_codecache *c;
  2464. c = upb_gmalloc(sizeof(*c));
  2465. c->arena = upb_arena_new();
  2466. alloc = upb_arena_alloc(c->arena);
  2467. upb_inttable_init2(&c->methods, UPB_CTYPE_CONSTPTR, alloc);
  2468. return c;
  2469. }
  2470. void upb_json_codecache_free(upb_json_codecache *c) {
  2471. upb_arena_free(c->arena);
  2472. upb_gfree(c);
  2473. }
  2474. const upb_json_parsermethod *upb_json_codecache_get(upb_json_codecache *c,
  2475. const upb_msgdef *md) {
  2476. upb_json_parsermethod *m;
  2477. upb_value v;
  2478. upb_msg_field_iter i;
  2479. upb_alloc *alloc = upb_arena_alloc(c->arena);
  2480. if (upb_inttable_lookupptr(&c->methods, md, &v)) {
  2481. return upb_value_getconstptr(v);
  2482. }
  2483. m = parsermethod_new(c, md);
  2484. v = upb_value_constptr(m);
  2485. if (!m) return NULL;
  2486. if (!upb_inttable_insertptr2(&c->methods, md, v, alloc)) return NULL;
  2487. /* Populate parser methods for all submessages, so the name tables will
  2488. * be available during parsing. */
  2489. for(upb_msg_field_begin(&i, md);
  2490. !upb_msg_field_done(&i);
  2491. upb_msg_field_next(&i)) {
  2492. upb_fielddef *f = upb_msg_iter_field(&i);
  2493. if (upb_fielddef_issubmsg(f)) {
  2494. const upb_msgdef *subdef = upb_fielddef_msgsubdef(f);
  2495. const upb_json_parsermethod *sub_method =
  2496. upb_json_codecache_get(c, subdef);
  2497. if (!sub_method) return NULL;
  2498. }
  2499. }
  2500. return m;
  2501. }