t_cpp_generator.cc 173 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. *
  19. * Contains some contributions under the Thrift Software License.
  20. * Please see doc/old-thrift-license.txt in the Thrift distribution for
  21. * details.
  22. */
  23. #include <cassert>
  24. #include <fstream>
  25. #include <iomanip>
  26. #include <iostream>
  27. #include <limits>
  28. #include <sstream>
  29. #include <string>
  30. #include <vector>
  31. #include <sys/stat.h>
  32. #include "thrift/platform.h"
  33. #include "thrift/generate/t_oop_generator.h"
  34. using std::map;
  35. using std::ofstream;
  36. using std::ostream;
  37. using std::string;
  38. using std::vector;
  39. static const string endl = "\n"; // avoid ostream << std::endl flushes
  40. /**
  41. * C++ code generator. This is legitimacy incarnate.
  42. *
  43. */
  44. class t_cpp_generator : public t_oop_generator {
  45. public:
  46. t_cpp_generator(t_program* program,
  47. const std::map<std::string, std::string>& parsed_options,
  48. const std::string& option_string)
  49. : t_oop_generator(program) {
  50. (void)option_string;
  51. std::map<std::string, std::string>::const_iterator iter;
  52. gen_pure_enums_ = false;
  53. use_include_prefix_ = false;
  54. gen_cob_style_ = false;
  55. gen_no_client_completion_ = false;
  56. gen_no_default_operators_ = false;
  57. gen_templates_ = false;
  58. gen_templates_only_ = false;
  59. gen_moveable_ = false;
  60. gen_no_ostream_operators_ = false;
  61. gen_no_skeleton_ = false;
  62. for( iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) {
  63. if( iter->first.compare("pure_enums") == 0) {
  64. gen_pure_enums_ = true;
  65. } else if( iter->first.compare("include_prefix") == 0) {
  66. use_include_prefix_ = true;
  67. } else if( iter->first.compare("cob_style") == 0) {
  68. gen_cob_style_ = true;
  69. } else if( iter->first.compare("no_client_completion") == 0) {
  70. gen_no_client_completion_ = true;
  71. } else if( iter->first.compare("no_default_operators") == 0) {
  72. gen_no_default_operators_ = true;
  73. } else if( iter->first.compare("templates") == 0) {
  74. gen_templates_ = true;
  75. gen_templates_only_ = (iter->second == "only");
  76. } else if( iter->first.compare("moveable_types") == 0) {
  77. gen_moveable_ = true;
  78. } else if ( iter->first.compare("no_ostream_operators") == 0) {
  79. gen_no_ostream_operators_ = true;
  80. } else if ( iter->first.compare("no_skeleton") == 0) {
  81. gen_no_skeleton_ = true;
  82. } else {
  83. throw "unknown option cpp:" + iter->first;
  84. }
  85. }
  86. out_dir_base_ = "gen-cpp";
  87. }
  88. /**
  89. * Init and close methods
  90. */
  91. void init_generator();
  92. void close_generator();
  93. void generate_consts(std::vector<t_const*> consts);
  94. /**
  95. * Program-level generation functions
  96. */
  97. void generate_typedef(t_typedef* ttypedef);
  98. void generate_enum(t_enum* tenum);
  99. void generate_enum_ostream_operator_decl(std::ostream& out, t_enum* tenum);
  100. void generate_enum_ostream_operator(std::ostream& out, t_enum* tenum);
  101. void generate_forward_declaration(t_struct* tstruct);
  102. void generate_struct(t_struct* tstruct) { generate_cpp_struct(tstruct, false); }
  103. void generate_xception(t_struct* txception) { generate_cpp_struct(txception, true); }
  104. void generate_cpp_struct(t_struct* tstruct, bool is_exception);
  105. void generate_service(t_service* tservice);
  106. void print_const_value(std::ostream& out, std::string name, t_type* type, t_const_value* value);
  107. std::string render_const_value(std::ostream& out,
  108. std::string name,
  109. t_type* type,
  110. t_const_value* value);
  111. void generate_struct_declaration(std::ostream& out,
  112. t_struct* tstruct,
  113. bool is_exception = false,
  114. bool pointers = false,
  115. bool read = true,
  116. bool write = true,
  117. bool swap = false,
  118. bool is_user_struct = false);
  119. void generate_struct_definition(std::ostream& out,
  120. std::ostream& force_cpp_out,
  121. t_struct* tstruct,
  122. bool setters = true,
  123. bool is_user_struct = false);
  124. void generate_copy_constructor(std::ostream& out, t_struct* tstruct, bool is_exception);
  125. void generate_move_constructor(std::ostream& out, t_struct* tstruct, bool is_exception);
  126. void generate_constructor_helper(std::ostream& out,
  127. t_struct* tstruct,
  128. bool is_excpetion,
  129. bool is_move);
  130. void generate_assignment_operator(std::ostream& out, t_struct* tstruct);
  131. void generate_move_assignment_operator(std::ostream& out, t_struct* tstruct);
  132. void generate_assignment_helper(std::ostream& out, t_struct* tstruct, bool is_move);
  133. void generate_struct_reader(std::ostream& out, t_struct* tstruct, bool pointers = false);
  134. void generate_struct_writer(std::ostream& out, t_struct* tstruct, bool pointers = false);
  135. void generate_struct_result_writer(std::ostream& out, t_struct* tstruct, bool pointers = false);
  136. void generate_struct_swap(std::ostream& out, t_struct* tstruct);
  137. void generate_struct_print_method(std::ostream& out, t_struct* tstruct);
  138. void generate_exception_what_method(std::ostream& out, t_struct* tstruct);
  139. /**
  140. * Service-level generation functions
  141. */
  142. void generate_service_interface(t_service* tservice, string style);
  143. void generate_service_interface_factory(t_service* tservice, string style);
  144. void generate_service_null(t_service* tservice, string style);
  145. void generate_service_multiface(t_service* tservice);
  146. void generate_service_helpers(t_service* tservice);
  147. void generate_service_client(t_service* tservice, string style);
  148. void generate_service_processor(t_service* tservice, string style);
  149. void generate_service_skeleton(t_service* tservice);
  150. void generate_process_function(t_service* tservice,
  151. t_function* tfunction,
  152. string style,
  153. bool specialized = false);
  154. void generate_function_helpers(t_service* tservice, t_function* tfunction);
  155. void generate_service_async_skeleton(t_service* tservice);
  156. /**
  157. * Serialization constructs
  158. */
  159. void generate_deserialize_field(std::ostream& out,
  160. t_field* tfield,
  161. std::string prefix = "",
  162. std::string suffix = "");
  163. void generate_deserialize_struct(std::ostream& out,
  164. t_struct* tstruct,
  165. std::string prefix = "",
  166. bool pointer = false);
  167. void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = "");
  168. void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = "");
  169. void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = "");
  170. void generate_deserialize_list_element(std::ostream& out,
  171. t_list* tlist,
  172. std::string prefix,
  173. bool push_back,
  174. std::string index);
  175. void generate_serialize_field(std::ostream& out,
  176. t_field* tfield,
  177. std::string prefix = "",
  178. std::string suffix = "");
  179. void generate_serialize_struct(std::ostream& out,
  180. t_struct* tstruct,
  181. std::string prefix = "",
  182. bool pointer = false);
  183. void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = "");
  184. void generate_serialize_map_element(std::ostream& out, t_map* tmap, std::string iter);
  185. void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter);
  186. void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter);
  187. void generate_function_call(ostream& out,
  188. t_function* tfunction,
  189. string target,
  190. string iface,
  191. string arg_prefix);
  192. /*
  193. * Helper rendering functions
  194. */
  195. std::string namespace_prefix(std::string ns);
  196. std::string namespace_open(std::string ns);
  197. std::string namespace_close(std::string ns);
  198. std::string type_name(t_type* ttype, bool in_typedef = false, bool arg = false);
  199. std::string base_type_name(t_base_type::t_base tbase);
  200. std::string declare_field(t_field* tfield,
  201. bool init = false,
  202. bool pointer = false,
  203. bool constant = false,
  204. bool reference = false);
  205. std::string function_signature(t_function* tfunction,
  206. std::string style,
  207. std::string prefix = "",
  208. bool name_params = true);
  209. std::string cob_function_signature(t_function* tfunction,
  210. std::string prefix = "",
  211. bool name_params = true);
  212. std::string argument_list(t_struct* tstruct, bool name_params = true, bool start_comma = false);
  213. std::string type_to_enum(t_type* ttype);
  214. void generate_enum_constant_list(std::ostream& f,
  215. const vector<t_enum_value*>& constants,
  216. const char* prefix,
  217. const char* suffix,
  218. bool include_values);
  219. void generate_struct_ostream_operator_decl(std::ostream& f, t_struct* tstruct);
  220. void generate_struct_ostream_operator(std::ostream& f, t_struct* tstruct);
  221. void generate_struct_print_method_decl(std::ostream& f, t_struct* tstruct);
  222. void generate_exception_what_method_decl(std::ostream& f,
  223. t_struct* tstruct,
  224. bool external = false);
  225. bool is_reference(t_field* tfield) { return tfield->get_reference(); }
  226. bool is_complex_type(t_type* ttype) {
  227. ttype = get_true_type(ttype);
  228. return ttype->is_container() || ttype->is_struct() || ttype->is_xception()
  229. || (ttype->is_base_type()
  230. && (((t_base_type*)ttype)->get_base() == t_base_type::TYPE_STRING));
  231. }
  232. void set_use_include_prefix(bool use_include_prefix) { use_include_prefix_ = use_include_prefix; }
  233. /**
  234. * The compiler option "no_thrift_ostream_impl" can be used to prevent
  235. * the compiler from emitting implementations for operator <<. In this
  236. * case the consuming application must provide any needed to build.
  237. *
  238. * To disable this on a per structure bases, one can alternatively set
  239. * the annotation "cpp.customostream" to prevent thrift from emitting an
  240. * operator << (std::ostream&).
  241. *
  242. * See AnnotationTest for validation of this annotation feature.
  243. */
  244. bool has_custom_ostream(t_type* ttype) const {
  245. return (gen_no_ostream_operators_) ||
  246. (ttype->annotations_.find("cpp.customostream") != ttype->annotations_.end());
  247. }
  248. private:
  249. /**
  250. * Returns the include prefix to use for a file generated by program, or the
  251. * empty string if no include prefix should be used.
  252. */
  253. std::string get_include_prefix(const t_program& program) const;
  254. /**
  255. * True if we should generate pure enums for Thrift enums, instead of wrapper classes.
  256. */
  257. bool gen_pure_enums_;
  258. /**
  259. * True if we should generate templatized reader/writer methods.
  260. */
  261. bool gen_templates_;
  262. /**
  263. * True iff we should generate process function pointers for only templatized
  264. * reader/writer methods.
  265. */
  266. bool gen_templates_only_;
  267. /**
  268. * True if we should generate move constructors & assignment operators.
  269. */
  270. bool gen_moveable_;
  271. /**
  272. * True if we should generate ostream definitions
  273. */
  274. bool gen_no_ostream_operators_;
  275. /**
  276. * True iff we should use a path prefix in our #include statements for other
  277. * thrift-generated header files.
  278. */
  279. bool use_include_prefix_;
  280. /**
  281. * True if we should generate "Continuation OBject"-style classes as well.
  282. */
  283. bool gen_cob_style_;
  284. /**
  285. * True if we should omit calls to completion__() in CobClient class.
  286. */
  287. bool gen_no_client_completion_;
  288. /**
  289. * True if we should omit generating the default opeartors ==, != and <.
  290. */
  291. bool gen_no_default_operators_;
  292. /**
  293. * True if we should generate skeleton.
  294. */
  295. bool gen_no_skeleton_;
  296. /**
  297. * Strings for namespace, computed once up front then used directly
  298. */
  299. std::string ns_open_;
  300. std::string ns_close_;
  301. /**
  302. * File streams, stored here to avoid passing them as parameters to every
  303. * function.
  304. */
  305. ofstream_with_content_based_conditional_update f_types_;
  306. ofstream_with_content_based_conditional_update f_types_impl_;
  307. ofstream_with_content_based_conditional_update f_types_tcc_;
  308. ofstream_with_content_based_conditional_update f_header_;
  309. ofstream_with_content_based_conditional_update f_service_;
  310. ofstream_with_content_based_conditional_update f_service_tcc_;
  311. // The ProcessorGenerator is used to generate parts of the code,
  312. // so it needs access to many of our protected members and methods.
  313. //
  314. // TODO: The code really should be cleaned up so that helper methods for
  315. // writing to the output files are separate from the generator classes
  316. // themselves.
  317. friend class ProcessorGenerator;
  318. };
  319. /**
  320. * Prepares for file generation by opening up the necessary file output
  321. * streams.
  322. */
  323. void t_cpp_generator::init_generator() {
  324. // Make output directory
  325. MKDIR(get_out_dir().c_str());
  326. // Make output file
  327. string f_types_name = get_out_dir() + program_name_ + "_types.h";
  328. f_types_.open(f_types_name);
  329. string f_types_impl_name = get_out_dir() + program_name_ + "_types.cpp";
  330. f_types_impl_.open(f_types_impl_name.c_str());
  331. if (gen_templates_) {
  332. // If we don't open the stream, it appears to just discard data,
  333. // which is fine.
  334. string f_types_tcc_name = get_out_dir() + program_name_ + "_types.tcc";
  335. f_types_tcc_.open(f_types_tcc_name.c_str());
  336. }
  337. // Print header
  338. f_types_ << autogen_comment();
  339. f_types_impl_ << autogen_comment();
  340. f_types_tcc_ << autogen_comment();
  341. // Start ifndef
  342. f_types_ << "#ifndef " << program_name_ << "_TYPES_H" << endl << "#define " << program_name_
  343. << "_TYPES_H" << endl << endl;
  344. f_types_tcc_ << "#ifndef " << program_name_ << "_TYPES_TCC" << endl << "#define " << program_name_
  345. << "_TYPES_TCC" << endl << endl;
  346. // Include base types
  347. f_types_ << "#include <iosfwd>" << endl
  348. << endl
  349. << "#include <thrift/Thrift.h>" << endl
  350. << "#include <thrift/TApplicationException.h>" << endl
  351. << "#include <thrift/TBase.h>" << endl
  352. << "#include <thrift/protocol/TProtocol.h>" << endl
  353. << "#include <thrift/transport/TTransport.h>" << endl
  354. << endl;
  355. // Include C++xx compatibility header
  356. f_types_ << "#include <thrift/stdcxx.h>" << endl;
  357. // Include other Thrift includes
  358. const vector<t_program*>& includes = program_->get_includes();
  359. for (size_t i = 0; i < includes.size(); ++i) {
  360. f_types_ << "#include \"" << get_include_prefix(*(includes[i])) << includes[i]->get_name()
  361. << "_types.h\"" << endl;
  362. // XXX(simpkins): If gen_templates_ is enabled, we currently assume all
  363. // included files were also generated with templates enabled.
  364. f_types_tcc_ << "#include \"" << get_include_prefix(*(includes[i])) << includes[i]->get_name()
  365. << "_types.tcc\"" << endl;
  366. }
  367. f_types_ << endl;
  368. // Include custom headers
  369. const vector<string>& cpp_includes = program_->get_cpp_includes();
  370. for (size_t i = 0; i < cpp_includes.size(); ++i) {
  371. if (cpp_includes[i][0] == '<') {
  372. f_types_ << "#include " << cpp_includes[i] << endl;
  373. } else {
  374. f_types_ << "#include \"" << cpp_includes[i] << "\"" << endl;
  375. }
  376. }
  377. f_types_ << endl;
  378. // Include the types file
  379. f_types_impl_ << "#include \"" << get_include_prefix(*get_program()) << program_name_
  380. << "_types.h\"" << endl << endl;
  381. f_types_tcc_ << "#include \"" << get_include_prefix(*get_program()) << program_name_
  382. << "_types.h\"" << endl << endl;
  383. // The swap() code needs <algorithm> for std::swap()
  384. f_types_impl_ << "#include <algorithm>" << endl;
  385. // for operator<<
  386. f_types_impl_ << "#include <ostream>" << endl << endl;
  387. f_types_impl_ << "#include <thrift/TToString.h>" << endl << endl;
  388. // Open namespace
  389. ns_open_ = namespace_open(program_->get_namespace("cpp"));
  390. ns_close_ = namespace_close(program_->get_namespace("cpp"));
  391. f_types_ << ns_open_ << endl << endl;
  392. f_types_impl_ << ns_open_ << endl << endl;
  393. f_types_tcc_ << ns_open_ << endl << endl;
  394. }
  395. /**
  396. * Closes the output files.
  397. */
  398. void t_cpp_generator::close_generator() {
  399. // Close namespace
  400. f_types_ << ns_close_ << endl << endl;
  401. f_types_impl_ << ns_close_ << endl;
  402. f_types_tcc_ << ns_close_ << endl << endl;
  403. // Include the types.tcc file from the types header file,
  404. // so clients don't have to explicitly include the tcc file.
  405. // TODO(simpkins): Make this a separate option.
  406. if (gen_templates_) {
  407. f_types_ << "#include \"" << get_include_prefix(*get_program()) << program_name_
  408. << "_types.tcc\"" << endl << endl;
  409. }
  410. // Close ifndef
  411. f_types_ << "#endif" << endl;
  412. f_types_tcc_ << "#endif" << endl;
  413. // Close output file
  414. f_types_.close();
  415. f_types_impl_.close();
  416. f_types_tcc_.close();
  417. }
  418. /**
  419. * Generates a typedef. This is just a simple 1-liner in C++
  420. *
  421. * @param ttypedef The type definition
  422. */
  423. void t_cpp_generator::generate_typedef(t_typedef* ttypedef) {
  424. f_types_ << indent() << "typedef " << type_name(ttypedef->get_type(), true) << " "
  425. << ttypedef->get_symbolic() << ";" << endl << endl;
  426. }
  427. void t_cpp_generator::generate_enum_constant_list(std::ostream& f,
  428. const vector<t_enum_value*>& constants,
  429. const char* prefix,
  430. const char* suffix,
  431. bool include_values) {
  432. f << " {" << endl;
  433. indent_up();
  434. vector<t_enum_value*>::const_iterator c_iter;
  435. bool first = true;
  436. for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
  437. if (first) {
  438. first = false;
  439. } else {
  440. f << "," << endl;
  441. }
  442. indent(f) << prefix << (*c_iter)->get_name() << suffix;
  443. if (include_values) {
  444. f << " = " << (*c_iter)->get_value();
  445. }
  446. }
  447. f << endl;
  448. indent_down();
  449. indent(f) << "};" << endl;
  450. }
  451. /**
  452. * Generates code for an enumerated type. In C++, this is essentially the same
  453. * as the thrift definition itself, using the enum keyword in C++.
  454. *
  455. * @param tenum The enumeration
  456. */
  457. void t_cpp_generator::generate_enum(t_enum* tenum) {
  458. vector<t_enum_value*> constants = tenum->get_constants();
  459. std::string enum_name = tenum->get_name();
  460. if (!gen_pure_enums_) {
  461. enum_name = "type";
  462. f_types_ << indent() << "struct " << tenum->get_name() << " {" << endl;
  463. indent_up();
  464. }
  465. f_types_ << indent() << "enum " << enum_name;
  466. generate_enum_constant_list(f_types_, constants, "", "", true);
  467. if (!gen_pure_enums_) {
  468. indent_down();
  469. f_types_ << "};" << endl;
  470. }
  471. f_types_ << endl;
  472. /**
  473. Generate a character array of enum names for debugging purposes.
  474. */
  475. std::string prefix = "";
  476. if (!gen_pure_enums_) {
  477. prefix = tenum->get_name() + "::";
  478. }
  479. f_types_impl_ << indent() << "int _k" << tenum->get_name() << "Values[] =";
  480. generate_enum_constant_list(f_types_impl_, constants, prefix.c_str(), "", false);
  481. f_types_impl_ << indent() << "const char* _k" << tenum->get_name() << "Names[] =";
  482. generate_enum_constant_list(f_types_impl_, constants, "\"", "\"", false);
  483. f_types_ << indent() << "extern const std::map<int, const char*> _" << tenum->get_name()
  484. << "_VALUES_TO_NAMES;" << endl << endl;
  485. f_types_impl_ << indent() << "const std::map<int, const char*> _" << tenum->get_name()
  486. << "_VALUES_TO_NAMES(::apache::thrift::TEnumIterator(" << constants.size() << ", _k"
  487. << tenum->get_name() << "Values"
  488. << ", _k" << tenum->get_name() << "Names), "
  489. << "::apache::thrift::TEnumIterator(-1, NULL, NULL));" << endl << endl;
  490. generate_enum_ostream_operator_decl(f_types_, tenum);
  491. generate_enum_ostream_operator(f_types_impl_, tenum);
  492. }
  493. void t_cpp_generator::generate_enum_ostream_operator_decl(std::ostream& out, t_enum* tenum) {
  494. out << "std::ostream& operator<<(std::ostream& out, const ";
  495. if (gen_pure_enums_) {
  496. out << tenum->get_name();
  497. } else {
  498. out << tenum->get_name() << "::type&";
  499. }
  500. out << " val);" << endl;
  501. out << endl;
  502. }
  503. void t_cpp_generator::generate_enum_ostream_operator(std::ostream& out, t_enum* tenum) {
  504. // If we've been told the consuming application will provide an ostream
  505. // operator definition then we only make a declaration:
  506. if (!has_custom_ostream(tenum)) {
  507. out << "std::ostream& operator<<(std::ostream& out, const ";
  508. if (gen_pure_enums_) {
  509. out << tenum->get_name();
  510. } else {
  511. out << tenum->get_name() << "::type&";
  512. }
  513. out << " val) ";
  514. scope_up(out);
  515. out << indent() << "std::map<int, const char*>::const_iterator it = _"
  516. << tenum->get_name() << "_VALUES_TO_NAMES.find(val);" << endl;
  517. out << indent() << "if (it != _" << tenum->get_name() << "_VALUES_TO_NAMES.end()) {" << endl;
  518. indent_up();
  519. out << indent() << "out << it->second;" << endl;
  520. indent_down();
  521. out << indent() << "} else {" << endl;
  522. indent_up();
  523. out << indent() << "out << static_cast<int>(val);" << endl;
  524. indent_down();
  525. out << indent() << "}" << endl;
  526. out << indent() << "return out;" << endl;
  527. scope_down(out);
  528. out << endl;
  529. }
  530. }
  531. /**
  532. * Generates a class that holds all the constants.
  533. */
  534. void t_cpp_generator::generate_consts(std::vector<t_const*> consts) {
  535. string f_consts_name = get_out_dir() + program_name_ + "_constants.h";
  536. ofstream_with_content_based_conditional_update f_consts;
  537. f_consts.open(f_consts_name);
  538. string f_consts_impl_name = get_out_dir() + program_name_ + "_constants.cpp";
  539. ofstream_with_content_based_conditional_update f_consts_impl;
  540. f_consts_impl.open(f_consts_impl_name);
  541. // Print header
  542. f_consts << autogen_comment();
  543. f_consts_impl << autogen_comment();
  544. // Start ifndef
  545. f_consts << "#ifndef " << program_name_ << "_CONSTANTS_H" << endl << "#define " << program_name_
  546. << "_CONSTANTS_H" << endl << endl << "#include \"" << get_include_prefix(*get_program())
  547. << program_name_ << "_types.h\"" << endl << endl << ns_open_ << endl << endl;
  548. f_consts_impl << "#include \"" << get_include_prefix(*get_program()) << program_name_
  549. << "_constants.h\"" << endl << endl << ns_open_ << endl << endl;
  550. f_consts << "class " << program_name_ << "Constants {" << endl << " public:" << endl << " "
  551. << program_name_ << "Constants();" << endl << endl;
  552. indent_up();
  553. vector<t_const*>::iterator c_iter;
  554. for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
  555. string name = (*c_iter)->get_name();
  556. t_type* type = (*c_iter)->get_type();
  557. f_consts << indent() << type_name(type) << " " << name << ";" << endl;
  558. }
  559. indent_down();
  560. f_consts << "};" << endl;
  561. f_consts_impl << "const " << program_name_ << "Constants g_" << program_name_ << "_constants;"
  562. << endl << endl << program_name_ << "Constants::" << program_name_
  563. << "Constants() {" << endl;
  564. indent_up();
  565. for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
  566. print_const_value(f_consts_impl,
  567. (*c_iter)->get_name(),
  568. (*c_iter)->get_type(),
  569. (*c_iter)->get_value());
  570. }
  571. indent_down();
  572. indent(f_consts_impl) << "}" << endl;
  573. f_consts << endl << "extern const " << program_name_ << "Constants g_" << program_name_
  574. << "_constants;" << endl << endl << ns_close_ << endl << endl << "#endif" << endl;
  575. f_consts.close();
  576. f_consts_impl << endl << ns_close_ << endl << endl;
  577. f_consts_impl.close();
  578. }
  579. /**
  580. * Prints the value of a constant with the given type. Note that type checking
  581. * is NOT performed in this function as it is always run beforehand using the
  582. * validate_types method in main.cc
  583. */
  584. void t_cpp_generator::print_const_value(ostream& out,
  585. string name,
  586. t_type* type,
  587. t_const_value* value) {
  588. type = get_true_type(type);
  589. if (type->is_base_type()) {
  590. string v2 = render_const_value(out, name, type, value);
  591. indent(out) << name << " = " << v2 << ";" << endl << endl;
  592. } else if (type->is_enum()) {
  593. indent(out) << name << " = (" << type_name(type) << ")" << value->get_integer() << ";" << endl
  594. << endl;
  595. } else if (type->is_struct() || type->is_xception()) {
  596. const vector<t_field*>& fields = ((t_struct*)type)->get_members();
  597. vector<t_field*>::const_iterator f_iter;
  598. const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
  599. map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
  600. bool is_nonrequired_field = false;
  601. for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
  602. t_type* field_type = NULL;
  603. is_nonrequired_field = false;
  604. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  605. if ((*f_iter)->get_name() == v_iter->first->get_string()) {
  606. field_type = (*f_iter)->get_type();
  607. is_nonrequired_field = (*f_iter)->get_req() != t_field::T_REQUIRED;
  608. }
  609. }
  610. if (field_type == NULL) {
  611. throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
  612. }
  613. string val = render_const_value(out, name, field_type, v_iter->second);
  614. indent(out) << name << "." << v_iter->first->get_string() << " = " << val << ";" << endl;
  615. if (is_nonrequired_field) {
  616. indent(out) << name << ".__isset." << v_iter->first->get_string() << " = true;" << endl;
  617. }
  618. }
  619. out << endl;
  620. } else if (type->is_map()) {
  621. t_type* ktype = ((t_map*)type)->get_key_type();
  622. t_type* vtype = ((t_map*)type)->get_val_type();
  623. const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
  624. map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
  625. for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
  626. string key = render_const_value(out, name, ktype, v_iter->first);
  627. string val = render_const_value(out, name, vtype, v_iter->second);
  628. indent(out) << name << ".insert(std::make_pair(" << key << ", " << val << "));" << endl;
  629. }
  630. out << endl;
  631. } else if (type->is_list()) {
  632. t_type* etype = ((t_list*)type)->get_elem_type();
  633. const vector<t_const_value*>& val = value->get_list();
  634. vector<t_const_value*>::const_iterator v_iter;
  635. for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
  636. string val = render_const_value(out, name, etype, *v_iter);
  637. indent(out) << name << ".push_back(" << val << ");" << endl;
  638. }
  639. out << endl;
  640. } else if (type->is_set()) {
  641. t_type* etype = ((t_set*)type)->get_elem_type();
  642. const vector<t_const_value*>& val = value->get_list();
  643. vector<t_const_value*>::const_iterator v_iter;
  644. for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
  645. string val = render_const_value(out, name, etype, *v_iter);
  646. indent(out) << name << ".insert(" << val << ");" << endl;
  647. }
  648. out << endl;
  649. } else {
  650. throw "INVALID TYPE IN print_const_value: " + type->get_name();
  651. }
  652. }
  653. /**
  654. *
  655. */
  656. string t_cpp_generator::render_const_value(ostream& out,
  657. string name,
  658. t_type* type,
  659. t_const_value* value) {
  660. (void)name;
  661. std::ostringstream render;
  662. if (type->is_base_type()) {
  663. t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
  664. switch (tbase) {
  665. case t_base_type::TYPE_STRING:
  666. render << '"' << get_escaped_string(value) << '"';
  667. break;
  668. case t_base_type::TYPE_BOOL:
  669. render << ((value->get_integer() > 0) ? "true" : "false");
  670. break;
  671. case t_base_type::TYPE_I8:
  672. case t_base_type::TYPE_I16:
  673. case t_base_type::TYPE_I32:
  674. render << value->get_integer();
  675. break;
  676. case t_base_type::TYPE_I64:
  677. render << value->get_integer() << "LL";
  678. break;
  679. case t_base_type::TYPE_DOUBLE:
  680. if (value->get_type() == t_const_value::CV_INTEGER) {
  681. render << "static_cast<double>(" << value->get_integer() << ")";
  682. } else {
  683. render << emit_double_as_string(value->get_double());
  684. }
  685. break;
  686. default:
  687. throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
  688. }
  689. } else if (type->is_enum()) {
  690. render << "(" << type_name(type) << ")" << value->get_integer();
  691. } else {
  692. string t = tmp("tmp");
  693. indent(out) << type_name(type) << " " << t << ";" << endl;
  694. print_const_value(out, t, type, value);
  695. render << t;
  696. }
  697. return render.str();
  698. }
  699. void t_cpp_generator::generate_forward_declaration(t_struct* tstruct) {
  700. // Forward declare struct def
  701. f_types_ << indent() << "class " << tstruct->get_name() << ";" << endl << endl;
  702. }
  703. /**
  704. * Generates a struct definition for a thrift data type. This is a class
  705. * with data members and a read/write() function, plus a mirroring isset
  706. * inner class.
  707. *
  708. * @param tstruct The struct definition
  709. */
  710. void t_cpp_generator::generate_cpp_struct(t_struct* tstruct, bool is_exception) {
  711. generate_struct_declaration(f_types_, tstruct, is_exception, false, true, true, true, true);
  712. generate_struct_definition(f_types_impl_, f_types_impl_, tstruct, true, true);
  713. std::ostream& out = (gen_templates_ ? f_types_tcc_ : f_types_impl_);
  714. generate_struct_reader(out, tstruct);
  715. generate_struct_writer(out, tstruct);
  716. generate_struct_swap(f_types_impl_, tstruct);
  717. generate_copy_constructor(f_types_impl_, tstruct, is_exception);
  718. if (gen_moveable_) {
  719. generate_move_constructor(f_types_impl_, tstruct, is_exception);
  720. }
  721. generate_assignment_operator(f_types_impl_, tstruct);
  722. if (gen_moveable_) {
  723. generate_move_assignment_operator(f_types_impl_, tstruct);
  724. }
  725. if (!has_custom_ostream(tstruct)) {
  726. generate_struct_print_method(f_types_impl_, tstruct);
  727. }
  728. if (is_exception) {
  729. generate_exception_what_method(f_types_impl_, tstruct);
  730. }
  731. }
  732. void t_cpp_generator::generate_copy_constructor(ostream& out,
  733. t_struct* tstruct,
  734. bool is_exception) {
  735. generate_constructor_helper(out, tstruct, is_exception, /*is_move=*/false);
  736. }
  737. void t_cpp_generator::generate_move_constructor(ostream& out,
  738. t_struct* tstruct,
  739. bool is_exception) {
  740. generate_constructor_helper(out, tstruct, is_exception, /*is_move=*/true);
  741. }
  742. namespace {
  743. // Helper to convert a variable to rvalue, if move is enabled
  744. std::string maybeMove(std::string const& other, bool move) {
  745. if (move) {
  746. return "std::move(" + other + ")";
  747. }
  748. return other;
  749. }
  750. }
  751. void t_cpp_generator::generate_constructor_helper(ostream& out,
  752. t_struct* tstruct,
  753. bool is_exception,
  754. bool is_move) {
  755. std::string tmp_name = tmp("other");
  756. indent(out) << tstruct->get_name() << "::" << tstruct->get_name();
  757. if (is_move) {
  758. out << "( " << tstruct->get_name() << "&& ";
  759. } else {
  760. out << "(const " << tstruct->get_name() << "& ";
  761. }
  762. out << tmp_name << ") ";
  763. if (is_exception)
  764. out << ": TException() ";
  765. out << "{" << endl;
  766. indent_up();
  767. const vector<t_field*>& members = tstruct->get_members();
  768. // eliminate compiler unused warning
  769. if (members.empty())
  770. indent(out) << "(void) " << tmp_name << ";" << endl;
  771. vector<t_field*>::const_iterator f_iter;
  772. bool has_nonrequired_fields = false;
  773. for (f_iter = members.begin(); f_iter != members.end(); ++f_iter) {
  774. if ((*f_iter)->get_req() != t_field::T_REQUIRED)
  775. has_nonrequired_fields = true;
  776. indent(out) << (*f_iter)->get_name() << " = "
  777. << maybeMove(tmp_name + "." + (*f_iter)->get_name(), is_move) << ";" << endl;
  778. }
  779. if (has_nonrequired_fields) {
  780. indent(out) << "__isset = " << maybeMove(tmp_name + ".__isset", is_move) << ";" << endl;
  781. }
  782. indent_down();
  783. indent(out) << "}" << endl;
  784. }
  785. void t_cpp_generator::generate_assignment_operator(ostream& out, t_struct* tstruct) {
  786. generate_assignment_helper(out, tstruct, /*is_move=*/false);
  787. }
  788. void t_cpp_generator::generate_move_assignment_operator(ostream& out, t_struct* tstruct) {
  789. generate_assignment_helper(out, tstruct, /*is_move=*/true);
  790. }
  791. void t_cpp_generator::generate_assignment_helper(ostream& out, t_struct* tstruct, bool is_move) {
  792. std::string tmp_name = tmp("other");
  793. indent(out) << tstruct->get_name() << "& " << tstruct->get_name() << "::operator=(";
  794. if (is_move) {
  795. out << tstruct->get_name() << "&& ";
  796. } else {
  797. out << "const " << tstruct->get_name() << "& ";
  798. }
  799. out << tmp_name << ") {" << endl;
  800. indent_up();
  801. const vector<t_field*>& members = tstruct->get_members();
  802. // eliminate compiler unused warning
  803. if (members.empty())
  804. indent(out) << "(void) " << tmp_name << ";" << endl;
  805. vector<t_field*>::const_iterator f_iter;
  806. bool has_nonrequired_fields = false;
  807. for (f_iter = members.begin(); f_iter != members.end(); ++f_iter) {
  808. if ((*f_iter)->get_req() != t_field::T_REQUIRED)
  809. has_nonrequired_fields = true;
  810. indent(out) << (*f_iter)->get_name() << " = "
  811. << maybeMove(tmp_name + "." + (*f_iter)->get_name(), is_move) << ";" << endl;
  812. }
  813. if (has_nonrequired_fields) {
  814. indent(out) << "__isset = " << maybeMove(tmp_name + ".__isset", is_move) << ";" << endl;
  815. }
  816. indent(out) << "return *this;" << endl;
  817. indent_down();
  818. indent(out) << "}" << endl;
  819. }
  820. /**
  821. * Writes the struct declaration into the header file
  822. *
  823. * @param out Output stream
  824. * @param tstruct The struct
  825. */
  826. void t_cpp_generator::generate_struct_declaration(ostream& out,
  827. t_struct* tstruct,
  828. bool is_exception,
  829. bool pointers,
  830. bool read,
  831. bool write,
  832. bool swap,
  833. bool is_user_struct) {
  834. string extends = "";
  835. if (is_exception) {
  836. extends = " : public ::apache::thrift::TException";
  837. } else {
  838. if (is_user_struct && !gen_templates_) {
  839. extends = " : public virtual ::apache::thrift::TBase";
  840. }
  841. }
  842. // Get members
  843. vector<t_field*>::const_iterator m_iter;
  844. const vector<t_field*>& members = tstruct->get_members();
  845. // Write the isset structure declaration outside the class. This makes
  846. // the generated code amenable to processing by SWIG.
  847. // We only declare the struct if it gets used in the class.
  848. // Isset struct has boolean fields, but only for non-required fields.
  849. bool has_nonrequired_fields = false;
  850. for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
  851. if ((*m_iter)->get_req() != t_field::T_REQUIRED)
  852. has_nonrequired_fields = true;
  853. }
  854. if (has_nonrequired_fields && (!pointers || read)) {
  855. out << indent() << "typedef struct _" << tstruct->get_name() << "__isset {" << endl;
  856. indent_up();
  857. indent(out) << "_" << tstruct->get_name() << "__isset() ";
  858. bool first = true;
  859. for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
  860. if ((*m_iter)->get_req() == t_field::T_REQUIRED) {
  861. continue;
  862. }
  863. string isSet = ((*m_iter)->get_value() != NULL) ? "true" : "false";
  864. if (first) {
  865. first = false;
  866. out << ": " << (*m_iter)->get_name() << "(" << isSet << ")";
  867. } else {
  868. out << ", " << (*m_iter)->get_name() << "(" << isSet << ")";
  869. }
  870. }
  871. out << " {}" << endl;
  872. for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
  873. if ((*m_iter)->get_req() != t_field::T_REQUIRED) {
  874. indent(out) << "bool " << (*m_iter)->get_name() << " :1;" << endl;
  875. }
  876. }
  877. indent_down();
  878. indent(out) << "} _" << tstruct->get_name() << "__isset;" << endl;
  879. }
  880. out << endl;
  881. // Open struct def
  882. out << indent() << "class " << tstruct->get_name() << extends << " {" << endl << indent()
  883. << " public:" << endl << endl;
  884. indent_up();
  885. if (!pointers) {
  886. // Copy constructor
  887. indent(out) << tstruct->get_name() << "(const " << tstruct->get_name() << "&);" << endl;
  888. // Move constructor
  889. if (gen_moveable_) {
  890. indent(out) << tstruct->get_name() << "(" << tstruct->get_name() << "&&);" << endl;
  891. }
  892. // Assignment Operator
  893. indent(out) << tstruct->get_name() << "& operator=(const " << tstruct->get_name() << "&);"
  894. << endl;
  895. // Move assignment operator
  896. if (gen_moveable_) {
  897. indent(out) << tstruct->get_name() << "& operator=(" << tstruct->get_name() << "&&);" << endl;
  898. }
  899. // Default constructor
  900. indent(out) << tstruct->get_name() << "()";
  901. bool init_ctor = false;
  902. for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
  903. t_type* t = get_true_type((*m_iter)->get_type());
  904. if (t->is_base_type() || t->is_enum() || is_reference(*m_iter)) {
  905. string dval;
  906. if (t->is_enum()) {
  907. dval += "(" + type_name(t) + ")";
  908. }
  909. dval += (t->is_string() || is_reference(*m_iter)) ? "" : "0";
  910. t_const_value* cv = (*m_iter)->get_value();
  911. if (cv != NULL) {
  912. dval = render_const_value(out, (*m_iter)->get_name(), t, cv);
  913. }
  914. if (!init_ctor) {
  915. init_ctor = true;
  916. out << " : ";
  917. out << (*m_iter)->get_name() << "(" << dval << ")";
  918. } else {
  919. out << ", " << (*m_iter)->get_name() << "(" << dval << ")";
  920. }
  921. }
  922. }
  923. out << " {" << endl;
  924. indent_up();
  925. // TODO(dreiss): When everything else in Thrift is perfect,
  926. // do more of these in the initializer list.
  927. for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
  928. t_type* t = get_true_type((*m_iter)->get_type());
  929. if (!t->is_base_type()) {
  930. t_const_value* cv = (*m_iter)->get_value();
  931. if (cv != NULL) {
  932. print_const_value(out, (*m_iter)->get_name(), t, cv);
  933. }
  934. }
  935. }
  936. scope_down(out);
  937. }
  938. if (tstruct->annotations_.find("final") == tstruct->annotations_.end()) {
  939. out << endl << indent() << "virtual ~" << tstruct->get_name() << "() throw();" << endl;
  940. }
  941. // Declare all fields
  942. for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
  943. indent(out) << declare_field(*m_iter,
  944. false,
  945. (pointers && !(*m_iter)->get_type()->is_xception()),
  946. !read) << endl;
  947. }
  948. // Add the __isset data member if we need it, using the definition from above
  949. if (has_nonrequired_fields && (!pointers || read)) {
  950. out << endl << indent() << "_" << tstruct->get_name() << "__isset __isset;" << endl;
  951. }
  952. // Create a setter function for each field
  953. for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
  954. if (pointers) {
  955. continue;
  956. }
  957. if (is_reference((*m_iter))) {
  958. out << endl << indent() << "void __set_" << (*m_iter)->get_name() << "(::apache::thrift::stdcxx::shared_ptr<"
  959. << type_name((*m_iter)->get_type(), false, false) << ">";
  960. out << " val);" << endl;
  961. } else {
  962. out << endl << indent() << "void __set_" << (*m_iter)->get_name() << "("
  963. << type_name((*m_iter)->get_type(), false, true);
  964. out << " val);" << endl;
  965. }
  966. }
  967. out << endl;
  968. if (!pointers) {
  969. // Should we generate default operators?
  970. if (!gen_no_default_operators_) {
  971. // Generate an equality testing operator. Make it inline since the compiler
  972. // will do a better job than we would when deciding whether to inline it.
  973. out << indent() << "bool operator == (const " << tstruct->get_name() << " & "
  974. << (members.size() > 0 ? "rhs" : "/* rhs */") << ") const" << endl;
  975. scope_up(out);
  976. for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
  977. // Most existing Thrift code does not use isset or optional/required,
  978. // so we treat "default" fields as required.
  979. if ((*m_iter)->get_req() != t_field::T_OPTIONAL) {
  980. out << indent() << "if (!(" << (*m_iter)->get_name() << " == rhs."
  981. << (*m_iter)->get_name() << "))" << endl << indent() << " return false;" << endl;
  982. } else {
  983. out << indent() << "if (__isset." << (*m_iter)->get_name() << " != rhs.__isset."
  984. << (*m_iter)->get_name() << ")" << endl << indent() << " return false;" << endl
  985. << indent() << "else if (__isset." << (*m_iter)->get_name() << " && !("
  986. << (*m_iter)->get_name() << " == rhs." << (*m_iter)->get_name() << "))" << endl
  987. << indent() << " return false;" << endl;
  988. }
  989. }
  990. indent(out) << "return true;" << endl;
  991. scope_down(out);
  992. out << indent() << "bool operator != (const " << tstruct->get_name() << " &rhs) const {"
  993. << endl << indent() << " return !(*this == rhs);" << endl << indent() << "}" << endl
  994. << endl;
  995. // Generate the declaration of a less-than operator. This must be
  996. // implemented by the application developer if they wish to use it. (They
  997. // will get a link error if they try to use it without an implementation.)
  998. out << indent() << "bool operator < (const " << tstruct->get_name() << " & ) const;" << endl
  999. << endl;
  1000. }
  1001. }
  1002. if (read) {
  1003. if (gen_templates_) {
  1004. out << indent() << "template <class Protocol_>" << endl << indent()
  1005. << "uint32_t read(Protocol_* iprot);" << endl;
  1006. } else {
  1007. out << indent() << "uint32_t read("
  1008. << "::apache::thrift::protocol::TProtocol* iprot);" << endl;
  1009. }
  1010. }
  1011. if (write) {
  1012. if (gen_templates_) {
  1013. out << indent() << "template <class Protocol_>" << endl << indent()
  1014. << "uint32_t write(Protocol_* oprot) const;" << endl;
  1015. } else {
  1016. out << indent() << "uint32_t write("
  1017. << "::apache::thrift::protocol::TProtocol* oprot) const;" << endl;
  1018. }
  1019. }
  1020. out << endl;
  1021. if (is_user_struct && !has_custom_ostream(tstruct)) {
  1022. out << indent() << "virtual ";
  1023. generate_struct_print_method_decl(out, NULL);
  1024. out << ";" << endl;
  1025. }
  1026. // std::exception::what()
  1027. if (is_exception) {
  1028. out << indent() << "mutable std::string thriftTExceptionMessageHolder_;" << endl;
  1029. out << indent();
  1030. generate_exception_what_method_decl(out, tstruct, false);
  1031. out << ";" << endl;
  1032. }
  1033. indent_down();
  1034. indent(out) << "};" << endl << endl;
  1035. if (swap) {
  1036. // Generate a namespace-scope swap() function
  1037. out << indent() << "void swap(" << tstruct->get_name() << " &a, " << tstruct->get_name()
  1038. << " &b);" << endl << endl;
  1039. }
  1040. if (is_user_struct) {
  1041. generate_struct_ostream_operator_decl(out, tstruct);
  1042. }
  1043. }
  1044. void t_cpp_generator::generate_struct_definition(ostream& out,
  1045. ostream& force_cpp_out,
  1046. t_struct* tstruct,
  1047. bool setters,
  1048. bool is_user_struct) {
  1049. // Get members
  1050. vector<t_field*>::const_iterator m_iter;
  1051. const vector<t_field*>& members = tstruct->get_members();
  1052. // Destructor
  1053. if (tstruct->annotations_.find("final") == tstruct->annotations_.end()) {
  1054. force_cpp_out << endl << indent() << tstruct->get_name() << "::~" << tstruct->get_name()
  1055. << "() throw() {" << endl;
  1056. indent_up();
  1057. indent_down();
  1058. force_cpp_out << indent() << "}" << endl << endl;
  1059. }
  1060. // Create a setter function for each field
  1061. if (setters) {
  1062. for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
  1063. if (is_reference((*m_iter))) {
  1064. std::string type = type_name((*m_iter)->get_type());
  1065. out << endl << indent() << "void " << tstruct->get_name() << "::__set_"
  1066. << (*m_iter)->get_name() << "(::apache::thrift::stdcxx::shared_ptr<"
  1067. << type_name((*m_iter)->get_type(), false, false) << ">";
  1068. out << " val) {" << endl;
  1069. } else {
  1070. out << endl << indent() << "void " << tstruct->get_name() << "::__set_"
  1071. << (*m_iter)->get_name() << "(" << type_name((*m_iter)->get_type(), false, true);
  1072. out << " val) {" << endl;
  1073. }
  1074. indent_up();
  1075. out << indent() << "this->" << (*m_iter)->get_name() << " = val;" << endl;
  1076. indent_down();
  1077. // assume all fields are required except optional fields.
  1078. // for optional fields change __isset.name to true
  1079. bool is_optional = (*m_iter)->get_req() == t_field::T_OPTIONAL;
  1080. if (is_optional) {
  1081. out << indent() << indent() << "__isset." << (*m_iter)->get_name() << " = true;" << endl;
  1082. }
  1083. out << indent() << "}" << endl;
  1084. }
  1085. }
  1086. if (is_user_struct) {
  1087. generate_struct_ostream_operator(out, tstruct);
  1088. }
  1089. out << endl;
  1090. }
  1091. /**
  1092. * Makes a helper function to gen a struct reader.
  1093. *
  1094. * @param out Stream to write to
  1095. * @param tstruct The struct
  1096. */
  1097. void t_cpp_generator::generate_struct_reader(ostream& out, t_struct* tstruct, bool pointers) {
  1098. if (gen_templates_) {
  1099. out << indent() << "template <class Protocol_>" << endl << indent() << "uint32_t "
  1100. << tstruct->get_name() << "::read(Protocol_* iprot) {" << endl;
  1101. } else {
  1102. indent(out) << "uint32_t " << tstruct->get_name()
  1103. << "::read(::apache::thrift::protocol::TProtocol* iprot) {" << endl;
  1104. }
  1105. indent_up();
  1106. const vector<t_field*>& fields = tstruct->get_members();
  1107. vector<t_field*>::const_iterator f_iter;
  1108. // Declare stack tmp variables
  1109. out << endl
  1110. << indent() << "::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);" << endl
  1111. << indent() << "uint32_t xfer = 0;" << endl
  1112. << indent() << "std::string fname;" << endl
  1113. << indent() << "::apache::thrift::protocol::TType ftype;" << endl
  1114. << indent() << "int16_t fid;" << endl
  1115. << endl
  1116. << indent() << "xfer += iprot->readStructBegin(fname);" << endl
  1117. << endl
  1118. << indent() << "using ::apache::thrift::protocol::TProtocolException;" << endl
  1119. << endl;
  1120. // Required variables aren't in __isset, so we need tmp vars to check them.
  1121. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  1122. if ((*f_iter)->get_req() == t_field::T_REQUIRED)
  1123. indent(out) << "bool isset_" << (*f_iter)->get_name() << " = false;" << endl;
  1124. }
  1125. out << endl;
  1126. // Loop over reading in fields
  1127. indent(out) << "while (true)" << endl;
  1128. scope_up(out);
  1129. // Read beginning field marker
  1130. indent(out) << "xfer += iprot->readFieldBegin(fname, ftype, fid);" << endl;
  1131. // Check for field STOP marker
  1132. out << indent() << "if (ftype == ::apache::thrift::protocol::T_STOP) {" << endl << indent()
  1133. << " break;" << endl << indent() << "}" << endl;
  1134. if (fields.empty()) {
  1135. out << indent() << "xfer += iprot->skip(ftype);" << endl;
  1136. } else {
  1137. // Switch statement on the field we are reading
  1138. indent(out) << "switch (fid)" << endl;
  1139. scope_up(out);
  1140. // Generate deserialization code for known cases
  1141. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  1142. indent(out) << "case " << (*f_iter)->get_key() << ":" << endl;
  1143. indent_up();
  1144. indent(out) << "if (ftype == " << type_to_enum((*f_iter)->get_type()) << ") {" << endl;
  1145. indent_up();
  1146. const char* isset_prefix = ((*f_iter)->get_req() != t_field::T_REQUIRED) ? "this->__isset."
  1147. : "isset_";
  1148. #if 0
  1149. // This code throws an exception if the same field is encountered twice.
  1150. // We've decided to leave it out for performance reasons.
  1151. // TODO(dreiss): Generate this code and "if" it out to make it easier
  1152. // for people recompiling thrift to include it.
  1153. out <<
  1154. indent() << "if (" << isset_prefix << (*f_iter)->get_name() << ")" << endl <<
  1155. indent() << " throw TProtocolException(TProtocolException::INVALID_DATA);" << endl;
  1156. #endif
  1157. if (pointers && !(*f_iter)->get_type()->is_xception()) {
  1158. generate_deserialize_field(out, *f_iter, "(*(this->", "))");
  1159. } else {
  1160. generate_deserialize_field(out, *f_iter, "this->");
  1161. }
  1162. out << indent() << isset_prefix << (*f_iter)->get_name() << " = true;" << endl;
  1163. indent_down();
  1164. out << indent() << "} else {" << endl << indent() << " xfer += iprot->skip(ftype);" << endl
  1165. <<
  1166. // TODO(dreiss): Make this an option when thrift structs
  1167. // have a common base class.
  1168. // indent() << " throw TProtocolException(TProtocolException::INVALID_DATA);" << endl <<
  1169. indent() << "}" << endl << indent() << "break;" << endl;
  1170. indent_down();
  1171. }
  1172. // In the default case we skip the field
  1173. out << indent() << "default:" << endl << indent() << " xfer += iprot->skip(ftype);" << endl
  1174. << indent() << " break;" << endl;
  1175. scope_down(out);
  1176. } //!fields.empty()
  1177. // Read field end marker
  1178. indent(out) << "xfer += iprot->readFieldEnd();" << endl;
  1179. scope_down(out);
  1180. out << endl << indent() << "xfer += iprot->readStructEnd();" << endl;
  1181. // Throw if any required fields are missing.
  1182. // We do this after reading the struct end so that
  1183. // there might possibly be a chance of continuing.
  1184. out << endl;
  1185. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  1186. if ((*f_iter)->get_req() == t_field::T_REQUIRED)
  1187. out << indent() << "if (!isset_" << (*f_iter)->get_name() << ')' << endl << indent()
  1188. << " throw TProtocolException(TProtocolException::INVALID_DATA);" << endl;
  1189. }
  1190. indent(out) << "return xfer;" << endl;
  1191. indent_down();
  1192. indent(out) << "}" << endl << endl;
  1193. }
  1194. /**
  1195. * Generates the write function.
  1196. *
  1197. * @param out Stream to write to
  1198. * @param tstruct The struct
  1199. */
  1200. void t_cpp_generator::generate_struct_writer(ostream& out, t_struct* tstruct, bool pointers) {
  1201. string name = tstruct->get_name();
  1202. const vector<t_field*>& fields = tstruct->get_sorted_members();
  1203. vector<t_field*>::const_iterator f_iter;
  1204. if (gen_templates_) {
  1205. out << indent() << "template <class Protocol_>" << endl << indent() << "uint32_t "
  1206. << tstruct->get_name() << "::write(Protocol_* oprot) const {" << endl;
  1207. } else {
  1208. indent(out) << "uint32_t " << tstruct->get_name()
  1209. << "::write(::apache::thrift::protocol::TProtocol* oprot) const {" << endl;
  1210. }
  1211. indent_up();
  1212. out << indent() << "uint32_t xfer = 0;" << endl;
  1213. indent(out) << "::apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);" << endl;
  1214. indent(out) << "xfer += oprot->writeStructBegin(\"" << name << "\");" << endl;
  1215. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  1216. bool check_if_set = (*f_iter)->get_req() == t_field::T_OPTIONAL
  1217. || (*f_iter)->get_type()->is_xception();
  1218. if (check_if_set) {
  1219. out << endl << indent() << "if (this->__isset." << (*f_iter)->get_name() << ") {" << endl;
  1220. indent_up();
  1221. } else {
  1222. out << endl;
  1223. }
  1224. // Write field header
  1225. out << indent() << "xfer += oprot->writeFieldBegin("
  1226. << "\"" << (*f_iter)->get_name() << "\", " << type_to_enum((*f_iter)->get_type()) << ", "
  1227. << (*f_iter)->get_key() << ");" << endl;
  1228. // Write field contents
  1229. if (pointers && !(*f_iter)->get_type()->is_xception()) {
  1230. generate_serialize_field(out, *f_iter, "(*(this->", "))");
  1231. } else {
  1232. generate_serialize_field(out, *f_iter, "this->");
  1233. }
  1234. // Write field closer
  1235. indent(out) << "xfer += oprot->writeFieldEnd();" << endl;
  1236. if (check_if_set) {
  1237. indent_down();
  1238. indent(out) << '}';
  1239. }
  1240. }
  1241. out << endl;
  1242. // Write the struct map
  1243. out << indent() << "xfer += oprot->writeFieldStop();" << endl << indent()
  1244. << "xfer += oprot->writeStructEnd();" << endl << indent()
  1245. << "return xfer;" << endl;
  1246. indent_down();
  1247. indent(out) << "}" << endl << endl;
  1248. }
  1249. /**
  1250. * Struct writer for result of a function, which can have only one of its
  1251. * fields set and does a conditional if else look up into the __isset field
  1252. * of the struct.
  1253. *
  1254. * @param out Output stream
  1255. * @param tstruct The result struct
  1256. */
  1257. void t_cpp_generator::generate_struct_result_writer(ostream& out,
  1258. t_struct* tstruct,
  1259. bool pointers) {
  1260. string name = tstruct->get_name();
  1261. const vector<t_field*>& fields = tstruct->get_sorted_members();
  1262. vector<t_field*>::const_iterator f_iter;
  1263. if (gen_templates_) {
  1264. out << indent() << "template <class Protocol_>" << endl << indent() << "uint32_t "
  1265. << tstruct->get_name() << "::write(Protocol_* oprot) const {" << endl;
  1266. } else {
  1267. indent(out) << "uint32_t " << tstruct->get_name()
  1268. << "::write(::apache::thrift::protocol::TProtocol* oprot) const {" << endl;
  1269. }
  1270. indent_up();
  1271. out << endl << indent() << "uint32_t xfer = 0;" << endl << endl;
  1272. indent(out) << "xfer += oprot->writeStructBegin(\"" << name << "\");" << endl;
  1273. bool first = true;
  1274. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  1275. if (first) {
  1276. first = false;
  1277. out << endl << indent() << "if ";
  1278. } else {
  1279. out << " else if ";
  1280. }
  1281. out << "(this->__isset." << (*f_iter)->get_name() << ") {" << endl;
  1282. indent_up();
  1283. // Write field header
  1284. out << indent() << "xfer += oprot->writeFieldBegin("
  1285. << "\"" << (*f_iter)->get_name() << "\", " << type_to_enum((*f_iter)->get_type()) << ", "
  1286. << (*f_iter)->get_key() << ");" << endl;
  1287. // Write field contents
  1288. if (pointers) {
  1289. generate_serialize_field(out, *f_iter, "(*(this->", "))");
  1290. } else {
  1291. generate_serialize_field(out, *f_iter, "this->");
  1292. }
  1293. // Write field closer
  1294. indent(out) << "xfer += oprot->writeFieldEnd();" << endl;
  1295. indent_down();
  1296. indent(out) << "}";
  1297. }
  1298. // Write the struct map
  1299. out << endl << indent() << "xfer += oprot->writeFieldStop();" << endl << indent()
  1300. << "xfer += oprot->writeStructEnd();" << endl << indent() << "return xfer;" << endl;
  1301. indent_down();
  1302. indent(out) << "}" << endl << endl;
  1303. }
  1304. /**
  1305. * Generates the swap function.
  1306. *
  1307. * @param out Stream to write to
  1308. * @param tstruct The struct
  1309. */
  1310. void t_cpp_generator::generate_struct_swap(ostream& out, t_struct* tstruct) {
  1311. out << indent() << "void swap(" << tstruct->get_name() << " &a, " << tstruct->get_name()
  1312. << " &b) {" << endl;
  1313. indent_up();
  1314. // Let argument-dependent name lookup find the correct swap() function to
  1315. // use based on the argument types. If none is found in the arguments'
  1316. // namespaces, fall back to ::std::swap().
  1317. out << indent() << "using ::std::swap;" << endl;
  1318. bool has_nonrequired_fields = false;
  1319. const vector<t_field*>& fields = tstruct->get_members();
  1320. for (vector<t_field*>::const_iterator f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  1321. t_field* tfield = *f_iter;
  1322. if (tfield->get_req() != t_field::T_REQUIRED) {
  1323. has_nonrequired_fields = true;
  1324. }
  1325. out << indent() << "swap(a." << tfield->get_name() << ", b." << tfield->get_name() << ");"
  1326. << endl;
  1327. }
  1328. if (has_nonrequired_fields) {
  1329. out << indent() << "swap(a.__isset, b.__isset);" << endl;
  1330. }
  1331. // handle empty structs
  1332. if (fields.size() == 0) {
  1333. out << indent() << "(void) a;" << endl;
  1334. out << indent() << "(void) b;" << endl;
  1335. }
  1336. scope_down(out);
  1337. out << endl;
  1338. }
  1339. void t_cpp_generator::generate_struct_ostream_operator_decl(std::ostream& out, t_struct* tstruct) {
  1340. out << "std::ostream& operator<<(std::ostream& out, const "
  1341. << tstruct->get_name()
  1342. << "& obj);" << endl;
  1343. out << endl;
  1344. }
  1345. void t_cpp_generator::generate_struct_ostream_operator(std::ostream& out, t_struct* tstruct) {
  1346. if (!has_custom_ostream(tstruct)) {
  1347. // thrift defines this behavior
  1348. out << "std::ostream& operator<<(std::ostream& out, const "
  1349. << tstruct->get_name()
  1350. << "& obj)" << endl;
  1351. scope_up(out);
  1352. out << indent() << "obj.printTo(out);" << endl
  1353. << indent() << "return out;" << endl;
  1354. scope_down(out);
  1355. out << endl;
  1356. }
  1357. }
  1358. void t_cpp_generator::generate_struct_print_method_decl(std::ostream& out, t_struct* tstruct) {
  1359. out << "void ";
  1360. if (tstruct) {
  1361. out << tstruct->get_name() << "::";
  1362. }
  1363. out << "printTo(std::ostream& out) const";
  1364. }
  1365. void t_cpp_generator::generate_exception_what_method_decl(std::ostream& out,
  1366. t_struct* tstruct,
  1367. bool external) {
  1368. out << "const char* ";
  1369. if (external) {
  1370. out << tstruct->get_name() << "::";
  1371. }
  1372. out << "what() const throw()";
  1373. }
  1374. namespace struct_ostream_operator_generator {
  1375. void generate_required_field_value(std::ostream& out, const t_field* field) {
  1376. out << " << to_string(" << field->get_name() << ")";
  1377. }
  1378. void generate_optional_field_value(std::ostream& out, const t_field* field) {
  1379. out << "; (__isset." << field->get_name() << " ? (out";
  1380. generate_required_field_value(out, field);
  1381. out << ") : (out << \"<null>\"))";
  1382. }
  1383. void generate_field_value(std::ostream& out, const t_field* field) {
  1384. if (field->get_req() == t_field::T_OPTIONAL)
  1385. generate_optional_field_value(out, field);
  1386. else
  1387. generate_required_field_value(out, field);
  1388. }
  1389. void generate_field_name(std::ostream& out, const t_field* field) {
  1390. out << "\"" << field->get_name() << "=\"";
  1391. }
  1392. void generate_field(std::ostream& out, const t_field* field) {
  1393. generate_field_name(out, field);
  1394. generate_field_value(out, field);
  1395. }
  1396. void generate_fields(std::ostream& out,
  1397. const vector<t_field*>& fields,
  1398. const std::string& indent) {
  1399. const vector<t_field*>::const_iterator beg = fields.begin();
  1400. const vector<t_field*>::const_iterator end = fields.end();
  1401. for (vector<t_field*>::const_iterator it = beg; it != end; ++it) {
  1402. out << indent << "out << ";
  1403. if (it != beg) {
  1404. out << "\", \" << ";
  1405. }
  1406. generate_field(out, *it);
  1407. out << ";" << endl;
  1408. }
  1409. }
  1410. }
  1411. /**
  1412. * Generates operator<<
  1413. */
  1414. void t_cpp_generator::generate_struct_print_method(std::ostream& out, t_struct* tstruct) {
  1415. out << indent();
  1416. generate_struct_print_method_decl(out, tstruct);
  1417. out << " {" << endl;
  1418. indent_up();
  1419. out << indent() << "using ::apache::thrift::to_string;" << endl;
  1420. out << indent() << "out << \"" << tstruct->get_name() << "(\";" << endl;
  1421. struct_ostream_operator_generator::generate_fields(out, tstruct->get_members(), indent());
  1422. out << indent() << "out << \")\";" << endl;
  1423. indent_down();
  1424. out << "}" << endl << endl;
  1425. }
  1426. /**
  1427. * Generates what() method for exceptions
  1428. */
  1429. void t_cpp_generator::generate_exception_what_method(std::ostream& out, t_struct* tstruct) {
  1430. out << indent();
  1431. generate_exception_what_method_decl(out, tstruct, true);
  1432. out << " {" << endl;
  1433. indent_up();
  1434. out << indent() << "try {" << endl;
  1435. indent_up();
  1436. out << indent() << "std::stringstream ss;" << endl;
  1437. out << indent() << "ss << \"TException - service has thrown: \" << *this;" << endl;
  1438. out << indent() << "this->thriftTExceptionMessageHolder_ = ss.str();" << endl;
  1439. out << indent() << "return this->thriftTExceptionMessageHolder_.c_str();" << endl;
  1440. indent_down();
  1441. out << indent() << "} catch (const std::exception&) {" << endl;
  1442. indent_up();
  1443. out << indent() << "return \"TException - service has thrown: " << tstruct->get_name() << "\";"
  1444. << endl;
  1445. indent_down();
  1446. out << indent() << "}" << endl;
  1447. indent_down();
  1448. out << "}" << endl << endl;
  1449. }
  1450. /**
  1451. * Generates a thrift service. In C++, this comprises an entirely separate
  1452. * header and source file. The header file defines the methods and includes
  1453. * the data types defined in the main header file, and the implementation
  1454. * file contains implementations of the basic printer and default interfaces.
  1455. *
  1456. * @param tservice The service definition
  1457. */
  1458. void t_cpp_generator::generate_service(t_service* tservice) {
  1459. string svcname = tservice->get_name();
  1460. // Make output files
  1461. string f_header_name = get_out_dir() + svcname + ".h";
  1462. f_header_.open(f_header_name.c_str());
  1463. // Print header file includes
  1464. f_header_ << autogen_comment();
  1465. f_header_ << "#ifndef " << svcname << "_H" << endl << "#define " << svcname << "_H" << endl
  1466. << endl;
  1467. if (gen_cob_style_) {
  1468. f_header_ << "#include <thrift/transport/TBufferTransports.h>" << endl << // TMemoryBuffer
  1469. "#include <thrift/stdcxx.h>" << endl
  1470. << "namespace apache { namespace thrift { namespace async {" << endl
  1471. << "class TAsyncChannel;" << endl << "}}}" << endl;
  1472. }
  1473. f_header_ << "#include <thrift/TDispatchProcessor.h>" << endl;
  1474. if (gen_cob_style_) {
  1475. f_header_ << "#include <thrift/async/TAsyncDispatchProcessor.h>" << endl;
  1476. }
  1477. f_header_ << "#include <thrift/async/TConcurrentClientSyncInfo.h>" << endl;
  1478. f_header_ << "#include \"" << get_include_prefix(*get_program()) << program_name_ << "_types.h\""
  1479. << endl;
  1480. t_service* extends_service = tservice->get_extends();
  1481. if (extends_service != NULL) {
  1482. f_header_ << "#include \"" << get_include_prefix(*(extends_service->get_program()))
  1483. << extends_service->get_name() << ".h\"" << endl;
  1484. }
  1485. f_header_ << endl << ns_open_ << endl << endl;
  1486. f_header_ << "#ifdef _MSC_VER\n"
  1487. " #pragma warning( push )\n"
  1488. " #pragma warning (disable : 4250 ) //inheriting methods via dominance \n"
  1489. "#endif\n\n";
  1490. // Service implementation file includes
  1491. string f_service_name = get_out_dir() + svcname + ".cpp";
  1492. f_service_.open(f_service_name.c_str());
  1493. f_service_ << autogen_comment();
  1494. f_service_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\"" << endl;
  1495. if (gen_cob_style_) {
  1496. f_service_ << "#include \"thrift/async/TAsyncChannel.h\"" << endl;
  1497. }
  1498. if (gen_templates_) {
  1499. f_service_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".tcc\""
  1500. << endl;
  1501. string f_service_tcc_name = get_out_dir() + svcname + ".tcc";
  1502. f_service_tcc_.open(f_service_tcc_name.c_str());
  1503. f_service_tcc_ << autogen_comment();
  1504. f_service_tcc_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\""
  1505. << endl;
  1506. f_service_tcc_ << "#ifndef " << svcname << "_TCC" << endl << "#define " << svcname << "_TCC"
  1507. << endl << endl;
  1508. if (gen_cob_style_) {
  1509. f_service_tcc_ << "#include \"thrift/async/TAsyncChannel.h\"" << endl;
  1510. }
  1511. }
  1512. f_service_ << endl << ns_open_ << endl << endl;
  1513. f_service_tcc_ << endl << ns_open_ << endl << endl;
  1514. // Generate all the components
  1515. generate_service_interface(tservice, "");
  1516. generate_service_interface_factory(tservice, "");
  1517. generate_service_null(tservice, "");
  1518. generate_service_helpers(tservice);
  1519. generate_service_client(tservice, "");
  1520. generate_service_processor(tservice, "");
  1521. generate_service_multiface(tservice);
  1522. generate_service_client(tservice, "Concurrent");
  1523. // Generate skeleton
  1524. if (!gen_no_skeleton_) {
  1525. generate_service_skeleton(tservice);
  1526. }
  1527. // Generate all the cob components
  1528. if (gen_cob_style_) {
  1529. generate_service_interface(tservice, "CobCl");
  1530. generate_service_interface(tservice, "CobSv");
  1531. generate_service_interface_factory(tservice, "CobSv");
  1532. generate_service_null(tservice, "CobSv");
  1533. generate_service_client(tservice, "Cob");
  1534. generate_service_processor(tservice, "Cob");
  1535. if (!gen_no_skeleton_) {
  1536. generate_service_async_skeleton(tservice);
  1537. }
  1538. }
  1539. f_header_ << "#ifdef _MSC_VER\n"
  1540. " #pragma warning( pop )\n"
  1541. "#endif\n\n";
  1542. // Close the namespace
  1543. f_service_ << ns_close_ << endl << endl;
  1544. f_service_tcc_ << ns_close_ << endl << endl;
  1545. f_header_ << ns_close_ << endl << endl;
  1546. // TODO(simpkins): Make this a separate option
  1547. if (gen_templates_) {
  1548. f_header_ << "#include \"" << get_include_prefix(*get_program()) << svcname << ".tcc\"" << endl
  1549. << "#include \"" << get_include_prefix(*get_program()) << program_name_
  1550. << "_types.tcc\"" << endl << endl;
  1551. }
  1552. f_header_ << "#endif" << endl;
  1553. f_service_tcc_ << "#endif" << endl;
  1554. // Close the files
  1555. f_service_tcc_.close();
  1556. f_service_.close();
  1557. f_header_.close();
  1558. }
  1559. /**
  1560. * Generates helper functions for a service. Basically, this generates types
  1561. * for all the arguments and results to functions.
  1562. *
  1563. * @param tservice The service to generate a header definition for
  1564. */
  1565. void t_cpp_generator::generate_service_helpers(t_service* tservice) {
  1566. vector<t_function*> functions = tservice->get_functions();
  1567. vector<t_function*>::iterator f_iter;
  1568. std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);
  1569. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  1570. t_struct* ts = (*f_iter)->get_arglist();
  1571. string name_orig = ts->get_name();
  1572. // TODO(dreiss): Why is this stuff not in generate_function_helpers?
  1573. ts->set_name(tservice->get_name() + "_" + (*f_iter)->get_name() + "_args");
  1574. generate_struct_declaration(f_header_, ts, false);
  1575. generate_struct_definition(out, f_service_, ts, false);
  1576. generate_struct_reader(out, ts);
  1577. generate_struct_writer(out, ts);
  1578. ts->set_name(tservice->get_name() + "_" + (*f_iter)->get_name() + "_pargs");
  1579. generate_struct_declaration(f_header_, ts, false, true, false, true);
  1580. generate_struct_definition(out, f_service_, ts, false);
  1581. generate_struct_writer(out, ts, true);
  1582. ts->set_name(name_orig);
  1583. generate_function_helpers(tservice, *f_iter);
  1584. }
  1585. }
  1586. /**
  1587. * Generates a service interface definition.
  1588. *
  1589. * @param tservice The service to generate a header definition for
  1590. */
  1591. void t_cpp_generator::generate_service_interface(t_service* tservice, string style) {
  1592. string service_if_name = service_name_ + style + "If";
  1593. if (style == "CobCl") {
  1594. // Forward declare the client.
  1595. string client_name = service_name_ + "CobClient";
  1596. if (gen_templates_) {
  1597. client_name += "T";
  1598. service_if_name += "T";
  1599. indent(f_header_) << "template <class Protocol_>" << endl;
  1600. }
  1601. indent(f_header_) << "class " << client_name << ";" << endl << endl;
  1602. }
  1603. string extends = "";
  1604. if (tservice->get_extends() != NULL) {
  1605. extends = " : virtual public " + type_name(tservice->get_extends()) + style + "If";
  1606. if (style == "CobCl" && gen_templates_) {
  1607. // TODO(simpkins): If gen_templates_ is enabled, we currently assume all
  1608. // parent services were also generated with templates enabled.
  1609. extends += "T<Protocol_>";
  1610. }
  1611. }
  1612. if (style == "CobCl" && gen_templates_) {
  1613. f_header_ << "template <class Protocol_>" << endl;
  1614. }
  1615. f_header_ << "class " << service_if_name << extends << " {" << endl << " public:" << endl;
  1616. indent_up();
  1617. f_header_ << indent() << "virtual ~" << service_if_name << "() {}" << endl;
  1618. vector<t_function*> functions = tservice->get_functions();
  1619. vector<t_function*>::iterator f_iter;
  1620. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  1621. if ((*f_iter)->has_doc())
  1622. f_header_ << endl;
  1623. generate_java_doc(f_header_, *f_iter);
  1624. f_header_ << indent() << "virtual " << function_signature(*f_iter, style) << " = 0;" << endl;
  1625. }
  1626. indent_down();
  1627. f_header_ << "};" << endl << endl;
  1628. if (style == "CobCl" && gen_templates_) {
  1629. // generate a backwards-compatible typedef for clients that do not
  1630. // know about the new template-style code
  1631. f_header_ << "typedef " << service_if_name << "< ::apache::thrift::protocol::TProtocol> "
  1632. << service_name_ << style << "If;" << endl << endl;
  1633. }
  1634. }
  1635. /**
  1636. * Generates a service interface factory.
  1637. *
  1638. * @param tservice The service to generate an interface factory for.
  1639. */
  1640. void t_cpp_generator::generate_service_interface_factory(t_service* tservice, string style) {
  1641. string service_if_name = service_name_ + style + "If";
  1642. // Figure out the name of the upper-most parent class.
  1643. // Getting everything to work out properly with inheritance is annoying.
  1644. // Here's what we're doing for now:
  1645. //
  1646. // - All handlers implement getHandler(), but subclasses use covariant return
  1647. // types to return their specific service interface class type. We have to
  1648. // use raw pointers because of this; shared_ptr<> can't be used for
  1649. // covariant return types.
  1650. //
  1651. // - Since we're not using shared_ptr<>, we also provide a releaseHandler()
  1652. // function that must be called to release a pointer to a handler obtained
  1653. // via getHandler().
  1654. //
  1655. // releaseHandler() always accepts a pointer to the upper-most parent class
  1656. // type. This is necessary since the parent versions of releaseHandler()
  1657. // may accept any of the parent types, not just the most specific subclass
  1658. // type. Implementations can use dynamic_cast to cast the pointer to the
  1659. // subclass type if desired.
  1660. t_service* base_service = tservice;
  1661. while (base_service->get_extends() != NULL) {
  1662. base_service = base_service->get_extends();
  1663. }
  1664. string base_if_name = type_name(base_service) + style + "If";
  1665. // Generate the abstract factory class
  1666. string factory_name = service_if_name + "Factory";
  1667. string extends;
  1668. if (tservice->get_extends() != NULL) {
  1669. extends = " : virtual public " + type_name(tservice->get_extends()) + style + "IfFactory";
  1670. }
  1671. f_header_ << "class " << factory_name << extends << " {" << endl << " public:" << endl;
  1672. indent_up();
  1673. f_header_ << indent() << "typedef " << service_if_name << " Handler;" << endl << endl << indent()
  1674. << "virtual ~" << factory_name << "() {}" << endl << endl << indent() << "virtual "
  1675. << service_if_name << "* getHandler("
  1676. << "const ::apache::thrift::TConnectionInfo& connInfo) = 0;" << endl << indent()
  1677. << "virtual void releaseHandler(" << base_if_name << "* /* handler */) = 0;" << endl;
  1678. indent_down();
  1679. f_header_ << "};" << endl << endl;
  1680. // Generate the singleton factory class
  1681. string singleton_factory_name = service_if_name + "SingletonFactory";
  1682. f_header_ << "class " << singleton_factory_name << " : virtual public " << factory_name << " {"
  1683. << endl << " public:" << endl;
  1684. indent_up();
  1685. f_header_ << indent() << singleton_factory_name << "(const ::apache::thrift::stdcxx::shared_ptr<" << service_if_name
  1686. << ">& iface) : iface_(iface) {}" << endl << indent() << "virtual ~"
  1687. << singleton_factory_name << "() {}" << endl << endl << indent() << "virtual "
  1688. << service_if_name << "* getHandler("
  1689. << "const ::apache::thrift::TConnectionInfo&) {" << endl << indent()
  1690. << " return iface_.get();" << endl << indent() << "}" << endl << indent()
  1691. << "virtual void releaseHandler(" << base_if_name << "* /* handler */) {}" << endl;
  1692. f_header_ << endl << " protected:" << endl << indent() << "::apache::thrift::stdcxx::shared_ptr<" << service_if_name
  1693. << "> iface_;" << endl;
  1694. indent_down();
  1695. f_header_ << "};" << endl << endl;
  1696. }
  1697. /**
  1698. * Generates a null implementation of the service.
  1699. *
  1700. * @param tservice The service to generate a header definition for
  1701. */
  1702. void t_cpp_generator::generate_service_null(t_service* tservice, string style) {
  1703. string extends = "";
  1704. if (tservice->get_extends() != NULL) {
  1705. extends = " , virtual public " + type_name(tservice->get_extends()) + style + "Null";
  1706. }
  1707. f_header_ << "class " << service_name_ << style << "Null : virtual public " << service_name_
  1708. << style << "If" << extends << " {" << endl << " public:" << endl;
  1709. indent_up();
  1710. f_header_ << indent() << "virtual ~" << service_name_ << style << "Null() {}" << endl;
  1711. vector<t_function*> functions = tservice->get_functions();
  1712. vector<t_function*>::iterator f_iter;
  1713. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  1714. f_header_ << indent() << function_signature(*f_iter, style, "", false) << " {" << endl;
  1715. indent_up();
  1716. t_type* returntype = (*f_iter)->get_returntype();
  1717. t_field returnfield(returntype, "_return");
  1718. if (style == "") {
  1719. if (returntype->is_void() || is_complex_type(returntype)) {
  1720. f_header_ << indent() << "return;" << endl;
  1721. } else {
  1722. f_header_ << indent() << declare_field(&returnfield, true) << endl << indent()
  1723. << "return _return;" << endl;
  1724. }
  1725. } else if (style == "CobSv") {
  1726. if (returntype->is_void()) {
  1727. f_header_ << indent() << "return cob();" << endl;
  1728. } else {
  1729. t_field returnfield(returntype, "_return");
  1730. f_header_ << indent() << declare_field(&returnfield, true) << endl << indent()
  1731. << "return cob(_return);" << endl;
  1732. }
  1733. } else {
  1734. throw "UNKNOWN STYLE";
  1735. }
  1736. indent_down();
  1737. f_header_ << indent() << "}" << endl;
  1738. }
  1739. indent_down();
  1740. f_header_ << "};" << endl << endl;
  1741. }
  1742. void t_cpp_generator::generate_function_call(ostream& out,
  1743. t_function* tfunction,
  1744. string target,
  1745. string iface,
  1746. string arg_prefix) {
  1747. bool first = true;
  1748. t_type* ret_type = get_true_type(tfunction->get_returntype());
  1749. out << indent();
  1750. if (!tfunction->is_oneway() && !ret_type->is_void()) {
  1751. if (is_complex_type(ret_type)) {
  1752. first = false;
  1753. out << iface << "->" << tfunction->get_name() << "(" << target;
  1754. } else {
  1755. out << target << " = " << iface << "->" << tfunction->get_name() << "(";
  1756. }
  1757. } else {
  1758. out << iface << "->" << tfunction->get_name() << "(";
  1759. }
  1760. const std::vector<t_field*>& fields = tfunction->get_arglist()->get_members();
  1761. vector<t_field*>::const_iterator f_iter;
  1762. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  1763. if (first) {
  1764. first = false;
  1765. } else {
  1766. out << ", ";
  1767. }
  1768. out << arg_prefix << (*f_iter)->get_name();
  1769. }
  1770. out << ");" << endl;
  1771. }
  1772. void t_cpp_generator::generate_service_async_skeleton(t_service* tservice) {
  1773. string svcname = tservice->get_name();
  1774. // Service implementation file includes
  1775. string f_skeleton_name = get_out_dir() + svcname + "_async_server.skeleton.cpp";
  1776. string ns = namespace_prefix(tservice->get_program()->get_namespace("cpp"));
  1777. ofstream_with_content_based_conditional_update f_skeleton;
  1778. f_skeleton.open(f_skeleton_name.c_str());
  1779. f_skeleton << "// This autogenerated skeleton file illustrates one way to adapt a synchronous"
  1780. << endl << "// interface into an asynchronous interface. You should copy it to another"
  1781. << endl
  1782. << "// filename to avoid overwriting it and rewrite as asynchronous any functions"
  1783. << endl << "// that would otherwise introduce unwanted latency." << endl << endl
  1784. << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\"" << endl
  1785. << "#include <thrift/protocol/TBinaryProtocol.h>" << endl << endl
  1786. << "using namespace ::apache::thrift;" << endl
  1787. << "using namespace ::apache::thrift::protocol;" << endl
  1788. << "using namespace ::apache::thrift::transport;" << endl
  1789. << "using namespace ::apache::thrift::async;" << endl << endl;
  1790. // the following code would not compile:
  1791. // using namespace ;
  1792. // using namespace ::;
  1793. if ((!ns.empty()) && (ns.compare(" ::") != 0)) {
  1794. f_skeleton << "using namespace " << string(ns, 0, ns.size() - 2) << ";" << endl << endl;
  1795. }
  1796. f_skeleton << "class " << svcname << "AsyncHandler : "
  1797. << "public " << svcname << "CobSvIf {" << endl << " public:" << endl;
  1798. indent_up();
  1799. f_skeleton << indent() << svcname << "AsyncHandler() {" << endl << indent()
  1800. << " syncHandler_ = std::auto_ptr<" << svcname << "Handler>(new " << svcname
  1801. << "Handler);" << endl << indent() << " // Your initialization goes here" << endl
  1802. << indent() << "}" << endl;
  1803. f_skeleton << indent() << "virtual ~" << service_name_ << "AsyncHandler();" << endl;
  1804. vector<t_function*> functions = tservice->get_functions();
  1805. vector<t_function*>::iterator f_iter;
  1806. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  1807. f_skeleton << endl << indent() << function_signature(*f_iter, "CobSv", "", true) << " {"
  1808. << endl;
  1809. indent_up();
  1810. t_type* returntype = (*f_iter)->get_returntype();
  1811. t_field returnfield(returntype, "_return");
  1812. string target = returntype->is_void() ? "" : "_return";
  1813. if (!returntype->is_void()) {
  1814. f_skeleton << indent() << declare_field(&returnfield, true) << endl;
  1815. }
  1816. generate_function_call(f_skeleton, *f_iter, target, "syncHandler_", "");
  1817. f_skeleton << indent() << "return cob(" << target << ");" << endl;
  1818. scope_down(f_skeleton);
  1819. }
  1820. f_skeleton << endl << " protected:" << endl << indent() << "std::auto_ptr<" << svcname
  1821. << "Handler> syncHandler_;" << endl;
  1822. indent_down();
  1823. f_skeleton << "};" << endl << endl;
  1824. }
  1825. /**
  1826. * Generates a multiface, which is a single server that just takes a set
  1827. * of objects implementing the interface and calls them all, returning the
  1828. * value of the last one to be called.
  1829. *
  1830. * @param tservice The service to generate a multiserver for.
  1831. */
  1832. void t_cpp_generator::generate_service_multiface(t_service* tservice) {
  1833. // Generate the dispatch methods
  1834. vector<t_function*> functions = tservice->get_functions();
  1835. vector<t_function*>::iterator f_iter;
  1836. string extends = "";
  1837. string extends_multiface = "";
  1838. if (tservice->get_extends() != NULL) {
  1839. extends = type_name(tservice->get_extends());
  1840. extends_multiface = ", public " + extends + "Multiface";
  1841. }
  1842. string list_type = string("std::vector<apache::thrift::stdcxx::shared_ptr<") + service_name_ + "If> >";
  1843. // Generate the header portion
  1844. f_header_ << "class " << service_name_ << "Multiface : "
  1845. << "virtual public " << service_name_ << "If" << extends_multiface << " {" << endl
  1846. << " public:" << endl;
  1847. indent_up();
  1848. f_header_ << indent() << service_name_ << "Multiface(" << list_type
  1849. << "& ifaces) : ifaces_(ifaces) {" << endl;
  1850. if (!extends.empty()) {
  1851. f_header_ << indent()
  1852. << " std::vector<apache::thrift::stdcxx::shared_ptr<" + service_name_ + "If> >::iterator iter;"
  1853. << endl << indent() << " for (iter = ifaces.begin(); iter != ifaces.end(); ++iter) {"
  1854. << endl << indent() << " " << extends << "Multiface::add(*iter);" << endl
  1855. << indent() << " }" << endl;
  1856. }
  1857. f_header_ << indent() << "}" << endl << indent() << "virtual ~" << service_name_
  1858. << "Multiface() {}" << endl;
  1859. indent_down();
  1860. // Protected data members
  1861. f_header_ << " protected:" << endl;
  1862. indent_up();
  1863. f_header_ << indent() << list_type << " ifaces_;" << endl << indent() << service_name_
  1864. << "Multiface() {}" << endl << indent() << "void add(::apache::thrift::stdcxx::shared_ptr<"
  1865. << service_name_ << "If> iface) {" << endl;
  1866. if (!extends.empty()) {
  1867. f_header_ << indent() << " " << extends << "Multiface::add(iface);" << endl;
  1868. }
  1869. f_header_ << indent() << " ifaces_.push_back(iface);" << endl << indent() << "}" << endl;
  1870. indent_down();
  1871. f_header_ << indent() << " public:" << endl;
  1872. indent_up();
  1873. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  1874. t_struct* arglist = (*f_iter)->get_arglist();
  1875. const vector<t_field*>& args = arglist->get_members();
  1876. vector<t_field*>::const_iterator a_iter;
  1877. string call = string("ifaces_[i]->") + (*f_iter)->get_name() + "(";
  1878. bool first = true;
  1879. if (is_complex_type((*f_iter)->get_returntype())) {
  1880. call += "_return";
  1881. first = false;
  1882. }
  1883. for (a_iter = args.begin(); a_iter != args.end(); ++a_iter) {
  1884. if (first) {
  1885. first = false;
  1886. } else {
  1887. call += ", ";
  1888. }
  1889. call += (*a_iter)->get_name();
  1890. }
  1891. call += ")";
  1892. f_header_ << indent() << function_signature(*f_iter, "") << " {" << endl;
  1893. indent_up();
  1894. f_header_ << indent() << "size_t sz = ifaces_.size();" << endl << indent() << "size_t i = 0;"
  1895. << endl << indent() << "for (; i < (sz - 1); ++i) {" << endl;
  1896. indent_up();
  1897. f_header_ << indent() << call << ";" << endl;
  1898. indent_down();
  1899. f_header_ << indent() << "}" << endl;
  1900. if (!(*f_iter)->get_returntype()->is_void()) {
  1901. if (is_complex_type((*f_iter)->get_returntype())) {
  1902. f_header_ << indent() << call << ";" << endl << indent() << "return;" << endl;
  1903. } else {
  1904. f_header_ << indent() << "return " << call << ";" << endl;
  1905. }
  1906. } else {
  1907. f_header_ << indent() << call << ";" << endl;
  1908. }
  1909. indent_down();
  1910. f_header_ << indent() << "}" << endl << endl;
  1911. }
  1912. indent_down();
  1913. f_header_ << indent() << "};" << endl << endl;
  1914. }
  1915. /**
  1916. * Generates a service client definition.
  1917. *
  1918. * @param tservice The service to generate a server for.
  1919. */
  1920. void t_cpp_generator::generate_service_client(t_service* tservice, string style) {
  1921. string ifstyle;
  1922. if (style == "Cob") {
  1923. ifstyle = "CobCl";
  1924. }
  1925. std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);
  1926. string template_header, template_suffix, short_suffix, protocol_type, _this;
  1927. string const prot_factory_type = "::apache::thrift::protocol::TProtocolFactory";
  1928. if (gen_templates_) {
  1929. template_header = "template <class Protocol_>\n";
  1930. short_suffix = "T";
  1931. template_suffix = "T<Protocol_>";
  1932. protocol_type = "Protocol_";
  1933. _this = "this->";
  1934. } else {
  1935. protocol_type = "::apache::thrift::protocol::TProtocol";
  1936. }
  1937. string prot_ptr = "apache::thrift::stdcxx::shared_ptr< " + protocol_type + ">";
  1938. string client_suffix = "Client" + template_suffix;
  1939. string if_suffix = "If";
  1940. if (style == "Cob") {
  1941. if_suffix += template_suffix;
  1942. }
  1943. string extends = "";
  1944. string extends_client = "";
  1945. if (tservice->get_extends() != NULL) {
  1946. // TODO(simpkins): If gen_templates_ is enabled, we currently assume all
  1947. // parent services were also generated with templates enabled.
  1948. extends = type_name(tservice->get_extends());
  1949. extends_client = ", public " + extends + style + client_suffix;
  1950. }
  1951. // Generate the header portion
  1952. if (style == "Concurrent") {
  1953. f_header_ << "// The \'concurrent\' client is a thread safe client that correctly handles\n"
  1954. "// out of order responses. It is slower than the regular client, so should\n"
  1955. "// only be used when you need to share a connection among multiple threads\n";
  1956. }
  1957. f_header_ << template_header << "class " << service_name_ << style << "Client" << short_suffix
  1958. << " : "
  1959. << "virtual public " << service_name_ << ifstyle << if_suffix << extends_client << " {"
  1960. << endl << " public:" << endl;
  1961. indent_up();
  1962. if (style != "Cob") {
  1963. f_header_ << indent() << service_name_ << style << "Client" << short_suffix << "(" << prot_ptr
  1964. << " prot) ";
  1965. if (extends.empty()) {
  1966. f_header_ << "{" << endl;
  1967. f_header_ << indent() << " setProtocol" << short_suffix << "(prot);" << endl << indent()
  1968. << "}" << endl;
  1969. } else {
  1970. f_header_ << ":" << endl;
  1971. f_header_ << indent() << " " << extends << style << client_suffix << "(prot, prot) {}"
  1972. << endl;
  1973. }
  1974. f_header_ << indent() << service_name_ << style << "Client" << short_suffix << "(" << prot_ptr
  1975. << " iprot, " << prot_ptr << " oprot) ";
  1976. if (extends.empty()) {
  1977. f_header_ << "{" << endl;
  1978. f_header_ << indent() << " setProtocol" << short_suffix << "(iprot,oprot);" << endl
  1979. << indent() << "}" << endl;
  1980. } else {
  1981. f_header_ << ":" << indent() << " " << extends << style << client_suffix
  1982. << "(iprot, oprot) {}" << endl;
  1983. }
  1984. // create the setProtocol methods
  1985. if (extends.empty()) {
  1986. f_header_ << " private:" << endl;
  1987. // 1: one parameter
  1988. f_header_ << indent() << "void setProtocol" << short_suffix << "(" << prot_ptr << " prot) {"
  1989. << endl;
  1990. f_header_ << indent() << "setProtocol" << short_suffix << "(prot,prot);" << endl;
  1991. f_header_ << indent() << "}" << endl;
  1992. // 2: two parameter
  1993. f_header_ << indent() << "void setProtocol" << short_suffix << "(" << prot_ptr << " iprot, "
  1994. << prot_ptr << " oprot) {" << endl;
  1995. f_header_ << indent() << " piprot_=iprot;" << endl << indent() << " poprot_=oprot;" << endl
  1996. << indent() << " iprot_ = iprot.get();" << endl << indent()
  1997. << " oprot_ = oprot.get();" << endl;
  1998. f_header_ << indent() << "}" << endl;
  1999. f_header_ << " public:" << endl;
  2000. }
  2001. // Generate getters for the protocols.
  2002. // Note that these are not currently templated for simplicity.
  2003. // TODO(simpkins): should they be templated?
  2004. f_header_ << indent()
  2005. << "apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> getInputProtocol() {"
  2006. << endl << indent() << " return " << _this << "piprot_;" << endl << indent() << "}"
  2007. << endl;
  2008. f_header_ << indent()
  2009. << "apache::thrift::stdcxx::shared_ptr< ::apache::thrift::protocol::TProtocol> getOutputProtocol() {"
  2010. << endl << indent() << " return " << _this << "poprot_;" << endl << indent() << "}"
  2011. << endl;
  2012. } else /* if (style == "Cob") */ {
  2013. f_header_ << indent() << service_name_ << style << "Client" << short_suffix << "("
  2014. << "apache::thrift::stdcxx::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel, "
  2015. << "::apache::thrift::protocol::TProtocolFactory* protocolFactory) :" << endl;
  2016. if (extends.empty()) {
  2017. f_header_ << indent() << " channel_(channel)," << endl << indent()
  2018. << " itrans_(new ::apache::thrift::transport::TMemoryBuffer())," << endl
  2019. << indent() << " otrans_(new ::apache::thrift::transport::TMemoryBuffer()),"
  2020. << endl;
  2021. if (gen_templates_) {
  2022. // TProtocolFactory classes return generic TProtocol pointers.
  2023. // We have to dynamic cast to the Protocol_ type we are expecting.
  2024. f_header_ << indent() << " piprot_(::apache::thrift::stdcxx::dynamic_pointer_cast<Protocol_>("
  2025. << "protocolFactory->getProtocol(itrans_)))," << endl << indent()
  2026. << " poprot_(::apache::thrift::stdcxx::dynamic_pointer_cast<Protocol_>("
  2027. << "protocolFactory->getProtocol(otrans_))) {" << endl;
  2028. // Throw a TException if either dynamic cast failed.
  2029. f_header_ << indent() << " if (!piprot_ || !poprot_) {" << endl << indent()
  2030. << " throw ::apache::thrift::TException(\""
  2031. << "TProtocolFactory returned unexpected protocol type in " << service_name_
  2032. << style << "Client" << short_suffix << " constructor\");" << endl << indent()
  2033. << " }" << endl;
  2034. } else {
  2035. f_header_ << indent() << " piprot_(protocolFactory->getProtocol(itrans_))," << endl
  2036. << indent() << " poprot_(protocolFactory->getProtocol(otrans_)) {" << endl;
  2037. }
  2038. f_header_ << indent() << " iprot_ = piprot_.get();" << endl << indent()
  2039. << " oprot_ = poprot_.get();" << endl << indent() << "}" << endl;
  2040. } else {
  2041. f_header_ << indent() << " " << extends << style << client_suffix
  2042. << "(channel, protocolFactory) {}" << endl;
  2043. }
  2044. }
  2045. if (style == "Cob") {
  2046. f_header_ << indent()
  2047. << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::async::TAsyncChannel> getChannel() {" << endl
  2048. << indent() << " return " << _this << "channel_;" << endl << indent() << "}" << endl;
  2049. if (!gen_no_client_completion_) {
  2050. f_header_ << indent() << "virtual void completed__(bool /* success */) {}" << endl;
  2051. }
  2052. }
  2053. vector<t_function*> functions = tservice->get_functions();
  2054. vector<t_function*>::const_iterator f_iter;
  2055. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  2056. indent(f_header_) << function_signature(*f_iter, ifstyle) << ";" << endl;
  2057. // TODO(dreiss): Use private inheritance to avoid generating thise in cob-style.
  2058. if (style == "Concurrent" && !(*f_iter)->is_oneway()) {
  2059. // concurrent clients need to move the seqid from the send function to the
  2060. // recv function. Oneway methods don't have a recv function, so we don't need to
  2061. // move the seqid for them. Attempting to do so would result in a seqid leak.
  2062. t_function send_function(g_type_i32, /*returning seqid*/
  2063. string("send_") + (*f_iter)->get_name(),
  2064. (*f_iter)->get_arglist());
  2065. indent(f_header_) << function_signature(&send_function, "") << ";" << endl;
  2066. } else {
  2067. t_function send_function(g_type_void,
  2068. string("send_") + (*f_iter)->get_name(),
  2069. (*f_iter)->get_arglist());
  2070. indent(f_header_) << function_signature(&send_function, "") << ";" << endl;
  2071. }
  2072. if (!(*f_iter)->is_oneway()) {
  2073. if (style == "Concurrent") {
  2074. t_field seqIdArg(g_type_i32, "seqid");
  2075. t_struct seqIdArgStruct(program_);
  2076. seqIdArgStruct.append(&seqIdArg);
  2077. t_function recv_function((*f_iter)->get_returntype(),
  2078. string("recv_") + (*f_iter)->get_name(),
  2079. &seqIdArgStruct);
  2080. indent(f_header_) << function_signature(&recv_function, "") << ";" << endl;
  2081. } else {
  2082. t_struct noargs(program_);
  2083. t_function recv_function((*f_iter)->get_returntype(),
  2084. string("recv_") + (*f_iter)->get_name(),
  2085. &noargs);
  2086. indent(f_header_) << function_signature(&recv_function, "") << ";" << endl;
  2087. }
  2088. }
  2089. }
  2090. indent_down();
  2091. if (extends.empty()) {
  2092. f_header_ << " protected:" << endl;
  2093. indent_up();
  2094. if (style == "Cob") {
  2095. f_header_ << indent()
  2096. << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel_;" << endl
  2097. << indent()
  2098. << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> itrans_;" << endl
  2099. << indent()
  2100. << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> otrans_;"
  2101. << endl;
  2102. }
  2103. f_header_ <<
  2104. indent() << prot_ptr << " piprot_;" << endl <<
  2105. indent() << prot_ptr << " poprot_;" << endl <<
  2106. indent() << protocol_type << "* iprot_;" << endl <<
  2107. indent() << protocol_type << "* oprot_;" << endl;
  2108. if (style == "Concurrent") {
  2109. f_header_ <<
  2110. indent() << "::apache::thrift::async::TConcurrentClientSyncInfo sync_;"<<endl;
  2111. }
  2112. indent_down();
  2113. }
  2114. f_header_ << "};" << endl << endl;
  2115. if (gen_templates_) {
  2116. // Output a backwards compatibility typedef using
  2117. // TProtocol as the template parameter.
  2118. f_header_ << "typedef " << service_name_ << style
  2119. << "ClientT< ::apache::thrift::protocol::TProtocol> " << service_name_ << style
  2120. << "Client;" << endl << endl;
  2121. }
  2122. string scope = service_name_ + style + client_suffix + "::";
  2123. // Generate client method implementations
  2124. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  2125. string seqIdCapture;
  2126. string seqIdUse;
  2127. string seqIdCommaUse;
  2128. if (style == "Concurrent" && !(*f_iter)->is_oneway()) {
  2129. seqIdCapture = "int32_t seqid = ";
  2130. seqIdUse = "seqid";
  2131. seqIdCommaUse = ", seqid";
  2132. }
  2133. string funname = (*f_iter)->get_name();
  2134. // Open function
  2135. if (gen_templates_) {
  2136. indent(out) << template_header;
  2137. }
  2138. indent(out) << function_signature(*f_iter, ifstyle, scope) << endl;
  2139. scope_up(out);
  2140. indent(out) << seqIdCapture << "send_" << funname << "(";
  2141. // Get the struct of function call params
  2142. t_struct* arg_struct = (*f_iter)->get_arglist();
  2143. // Declare the function arguments
  2144. const vector<t_field*>& fields = arg_struct->get_members();
  2145. vector<t_field*>::const_iterator fld_iter;
  2146. bool first = true;
  2147. for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
  2148. if (first) {
  2149. first = false;
  2150. } else {
  2151. out << ", ";
  2152. }
  2153. out << (*fld_iter)->get_name();
  2154. }
  2155. out << ");" << endl;
  2156. if (style != "Cob") {
  2157. if (!(*f_iter)->is_oneway()) {
  2158. out << indent();
  2159. if (!(*f_iter)->get_returntype()->is_void()) {
  2160. if (is_complex_type((*f_iter)->get_returntype())) {
  2161. out << "recv_" << funname << "(_return" << seqIdCommaUse << ");" << endl;
  2162. } else {
  2163. out << "return recv_" << funname << "(" << seqIdUse << ");" << endl;
  2164. }
  2165. } else {
  2166. out << "recv_" << funname << "(" << seqIdUse << ");" << endl;
  2167. }
  2168. }
  2169. } else {
  2170. if (!(*f_iter)->is_oneway()) {
  2171. out << indent() << _this << "channel_->sendAndRecvMessage("
  2172. << "::apache::thrift::stdcxx::bind(cob, this), " << _this << "otrans_.get(), " << _this << "itrans_.get());"
  2173. << endl;
  2174. } else {
  2175. out << indent() << _this << "channel_->sendMessage("
  2176. << "::apache::thrift::stdcxx::bind(cob, this), " << _this << "otrans_.get());" << endl;
  2177. }
  2178. }
  2179. scope_down(out);
  2180. out << endl;
  2181. // if (style != "Cob") // TODO(dreiss): Libify the client and don't generate this for cob-style
  2182. if (true) {
  2183. t_type* send_func_return_type = g_type_void;
  2184. if (style == "Concurrent" && !(*f_iter)->is_oneway()) {
  2185. send_func_return_type = g_type_i32;
  2186. }
  2187. // Function for sending
  2188. t_function send_function(send_func_return_type,
  2189. string("send_") + (*f_iter)->get_name(),
  2190. (*f_iter)->get_arglist());
  2191. // Open the send function
  2192. if (gen_templates_) {
  2193. indent(out) << template_header;
  2194. }
  2195. indent(out) << function_signature(&send_function, "", scope) << endl;
  2196. scope_up(out);
  2197. // Function arguments and results
  2198. string argsname = tservice->get_name() + "_" + (*f_iter)->get_name() + "_pargs";
  2199. string resultname = tservice->get_name() + "_" + (*f_iter)->get_name() + "_presult";
  2200. string cseqidVal = "0";
  2201. if (style == "Concurrent") {
  2202. if (!(*f_iter)->is_oneway()) {
  2203. cseqidVal = "this->sync_.generateSeqId()";
  2204. }
  2205. }
  2206. // Serialize the request
  2207. out <<
  2208. indent() << "int32_t cseqid = " << cseqidVal << ";" << endl;
  2209. if(style == "Concurrent") {
  2210. out <<
  2211. indent() << "::apache::thrift::async::TConcurrentSendSentry sentry(&this->sync_);" << endl;
  2212. }
  2213. if (style == "Cob") {
  2214. out <<
  2215. indent() << _this << "otrans_->resetBuffer();" << endl;
  2216. }
  2217. out <<
  2218. indent() << _this << "oprot_->writeMessageBegin(\"" <<
  2219. (*f_iter)->get_name() <<
  2220. "\", ::apache::thrift::protocol::" << ((*f_iter)->is_oneway() ? "T_ONEWAY" : "T_CALL") <<
  2221. ", cseqid);" << endl << endl <<
  2222. indent() << argsname << " args;" << endl;
  2223. for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
  2224. out << indent() << "args." << (*fld_iter)->get_name() << " = &" << (*fld_iter)->get_name()
  2225. << ";" << endl;
  2226. }
  2227. out << indent() << "args.write(" << _this << "oprot_);" << endl << endl << indent() << _this
  2228. << "oprot_->writeMessageEnd();" << endl << indent() << _this
  2229. << "oprot_->getTransport()->writeEnd();" << endl << indent() << _this
  2230. << "oprot_->getTransport()->flush();" << endl;
  2231. if (style == "Concurrent") {
  2232. out << endl << indent() << "sentry.commit();" << endl;
  2233. if (!(*f_iter)->is_oneway()) {
  2234. out << indent() << "return cseqid;" << endl;
  2235. }
  2236. }
  2237. scope_down(out);
  2238. out << endl;
  2239. // Generate recv function only if not an oneway function
  2240. if (!(*f_iter)->is_oneway()) {
  2241. t_struct noargs(program_);
  2242. t_field seqIdArg(g_type_i32, "seqid");
  2243. t_struct seqIdArgStruct(program_);
  2244. seqIdArgStruct.append(&seqIdArg);
  2245. t_struct* recv_function_args = &noargs;
  2246. if (style == "Concurrent") {
  2247. recv_function_args = &seqIdArgStruct;
  2248. }
  2249. t_function recv_function((*f_iter)->get_returntype(),
  2250. string("recv_") + (*f_iter)->get_name(),
  2251. recv_function_args);
  2252. // Open the recv function
  2253. if (gen_templates_) {
  2254. indent(out) << template_header;
  2255. }
  2256. indent(out) << function_signature(&recv_function, "", scope) << endl;
  2257. scope_up(out);
  2258. out << endl <<
  2259. indent() << "int32_t rseqid = 0;" << endl <<
  2260. indent() << "std::string fname;" << endl <<
  2261. indent() << "::apache::thrift::protocol::TMessageType mtype;" << endl;
  2262. if(style == "Concurrent") {
  2263. out <<
  2264. endl <<
  2265. indent() << "// the read mutex gets dropped and reacquired as part of waitForWork()" << endl <<
  2266. indent() << "// The destructor of this sentry wakes up other clients" << endl <<
  2267. indent() << "::apache::thrift::async::TConcurrentRecvSentry sentry(&this->sync_, seqid);" << endl;
  2268. }
  2269. if (style == "Cob" && !gen_no_client_completion_) {
  2270. out << indent() << "bool completed = false;" << endl << endl << indent() << "try {";
  2271. indent_up();
  2272. }
  2273. out << endl;
  2274. if (style == "Concurrent") {
  2275. out <<
  2276. indent() << "while(true) {" << endl <<
  2277. indent() << " if(!this->sync_.getPending(fname, mtype, rseqid)) {" << endl;
  2278. indent_up();
  2279. indent_up();
  2280. }
  2281. out <<
  2282. indent() << _this << "iprot_->readMessageBegin(fname, mtype, rseqid);" << endl;
  2283. if (style == "Concurrent") {
  2284. scope_down(out);
  2285. out << indent() << "if(seqid == rseqid) {" << endl;
  2286. indent_up();
  2287. }
  2288. out <<
  2289. indent() << "if (mtype == ::apache::thrift::protocol::T_EXCEPTION) {" << endl <<
  2290. indent() << " ::apache::thrift::TApplicationException x;" << endl <<
  2291. indent() << " x.read(" << _this << "iprot_);" << endl <<
  2292. indent() << " " << _this << "iprot_->readMessageEnd();" << endl <<
  2293. indent() << " " << _this << "iprot_->getTransport()->readEnd();" << endl;
  2294. if (style == "Cob" && !gen_no_client_completion_) {
  2295. out << indent() << " completed = true;" << endl << indent() << " completed__(true);"
  2296. << endl;
  2297. }
  2298. if (style == "Concurrent") {
  2299. out << indent() << " sentry.commit();" << endl;
  2300. }
  2301. out <<
  2302. indent() << " throw x;" << endl <<
  2303. indent() << "}" << endl <<
  2304. indent() << "if (mtype != ::apache::thrift::protocol::T_REPLY) {" << endl <<
  2305. indent() << " " << _this << "iprot_->skip(" << "::apache::thrift::protocol::T_STRUCT);" << endl <<
  2306. indent() << " " << _this << "iprot_->readMessageEnd();" << endl <<
  2307. indent() << " " << _this << "iprot_->getTransport()->readEnd();" << endl;
  2308. if (style == "Cob" && !gen_no_client_completion_) {
  2309. out << indent() << " completed = true;" << endl << indent() << " completed__(false);"
  2310. << endl;
  2311. }
  2312. out <<
  2313. indent() << "}" << endl <<
  2314. indent() << "if (fname.compare(\"" << (*f_iter)->get_name() << "\") != 0) {" << endl <<
  2315. indent() << " " << _this << "iprot_->skip(" << "::apache::thrift::protocol::T_STRUCT);" << endl <<
  2316. indent() << " " << _this << "iprot_->readMessageEnd();" << endl <<
  2317. indent() << " " << _this << "iprot_->getTransport()->readEnd();" << endl;
  2318. if (style == "Cob" && !gen_no_client_completion_) {
  2319. out << indent() << " completed = true;" << endl << indent() << " completed__(false);"
  2320. << endl;
  2321. }
  2322. if (style == "Concurrent") {
  2323. out << endl <<
  2324. indent() << " // in a bad state, don't commit" << endl <<
  2325. indent() << " using ::apache::thrift::protocol::TProtocolException;" << endl <<
  2326. indent() << " throw TProtocolException(TProtocolException::INVALID_DATA);" << endl;
  2327. }
  2328. out << indent() << "}" << endl;
  2329. if (!(*f_iter)->get_returntype()->is_void()
  2330. && !is_complex_type((*f_iter)->get_returntype())) {
  2331. t_field returnfield((*f_iter)->get_returntype(), "_return");
  2332. out << indent() << declare_field(&returnfield) << endl;
  2333. }
  2334. out << indent() << resultname << " result;" << endl;
  2335. if (!(*f_iter)->get_returntype()->is_void()) {
  2336. out << indent() << "result.success = &_return;" << endl;
  2337. }
  2338. out << indent() << "result.read(" << _this << "iprot_);" << endl << indent() << _this
  2339. << "iprot_->readMessageEnd();" << endl << indent() << _this
  2340. << "iprot_->getTransport()->readEnd();" << endl << endl;
  2341. // Careful, only look for _result if not a void function
  2342. if (!(*f_iter)->get_returntype()->is_void()) {
  2343. if (is_complex_type((*f_iter)->get_returntype())) {
  2344. out <<
  2345. indent() << "if (result.__isset.success) {" << endl;
  2346. out <<
  2347. indent() << " // _return pointer has now been filled" << endl;
  2348. if (style == "Cob" && !gen_no_client_completion_) {
  2349. out << indent() << " completed = true;" << endl << indent() << " completed__(true);"
  2350. << endl;
  2351. }
  2352. if (style == "Concurrent") {
  2353. out << indent() << " sentry.commit();" << endl;
  2354. }
  2355. out <<
  2356. indent() << " return;" << endl <<
  2357. indent() << "}" << endl;
  2358. } else {
  2359. out << indent() << "if (result.__isset.success) {" << endl;
  2360. if (style == "Cob" && !gen_no_client_completion_) {
  2361. out << indent() << " completed = true;" << endl << indent() << " completed__(true);"
  2362. << endl;
  2363. }
  2364. if (style == "Concurrent") {
  2365. out << indent() << " sentry.commit();" << endl;
  2366. }
  2367. out << indent() << " return _return;" << endl << indent() << "}" << endl;
  2368. }
  2369. }
  2370. t_struct* xs = (*f_iter)->get_xceptions();
  2371. const std::vector<t_field*>& xceptions = xs->get_members();
  2372. vector<t_field*>::const_iterator x_iter;
  2373. for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
  2374. out << indent() << "if (result.__isset." << (*x_iter)->get_name() << ") {" << endl;
  2375. if (style == "Cob" && !gen_no_client_completion_) {
  2376. out << indent() << " completed = true;" << endl << indent() << " completed__(true);"
  2377. << endl;
  2378. }
  2379. if (style == "Concurrent") {
  2380. out << indent() << " sentry.commit();" << endl;
  2381. }
  2382. out << indent() << " throw result." << (*x_iter)->get_name() << ";" << endl << indent()
  2383. << "}" << endl;
  2384. }
  2385. // We only get here if we are a void function
  2386. if ((*f_iter)->get_returntype()->is_void()) {
  2387. if (style == "Cob" && !gen_no_client_completion_) {
  2388. out << indent() << "completed = true;" << endl << indent() << "completed__(true);"
  2389. << endl;
  2390. }
  2391. if (style == "Concurrent") {
  2392. out << indent() << "sentry.commit();" << endl;
  2393. }
  2394. indent(out) << "return;" << endl;
  2395. } else {
  2396. if (style == "Cob" && !gen_no_client_completion_) {
  2397. out << indent() << "completed = true;" << endl << indent() << "completed__(true);"
  2398. << endl;
  2399. }
  2400. if (style == "Concurrent") {
  2401. out << indent() << "// in a bad state, don't commit" << endl;
  2402. }
  2403. out << indent() << "throw "
  2404. "::apache::thrift::TApplicationException(::apache::thrift::"
  2405. "TApplicationException::MISSING_RESULT, \"" << (*f_iter)->get_name()
  2406. << " failed: unknown result\");" << endl;
  2407. }
  2408. if (style == "Concurrent") {
  2409. indent_down();
  2410. indent_down();
  2411. out <<
  2412. indent() << " }" << endl <<
  2413. indent() << " // seqid != rseqid" << endl <<
  2414. indent() << " this->sync_.updatePending(fname, mtype, rseqid);" << endl <<
  2415. endl <<
  2416. indent() << " // this will temporarily unlock the readMutex, and let other clients get work done" << endl <<
  2417. indent() << " this->sync_.waitForWork(seqid);" << endl <<
  2418. indent() << "} // end while(true)" << endl;
  2419. }
  2420. if (style == "Cob" && !gen_no_client_completion_) {
  2421. indent_down();
  2422. out << indent() << "} catch (...) {" << endl << indent() << " if (!completed) {" << endl
  2423. << indent() << " completed__(false);" << endl << indent() << " }" << endl
  2424. << indent() << " throw;" << endl << indent() << "}" << endl;
  2425. }
  2426. // Close function
  2427. scope_down(out);
  2428. out << endl;
  2429. }
  2430. }
  2431. }
  2432. }
  2433. class ProcessorGenerator {
  2434. public:
  2435. ProcessorGenerator(t_cpp_generator* generator, t_service* service, const string& style);
  2436. void run() {
  2437. generate_class_definition();
  2438. // Generate the dispatchCall() function
  2439. generate_dispatch_call(false);
  2440. if (generator_->gen_templates_) {
  2441. generate_dispatch_call(true);
  2442. }
  2443. // Generate all of the process subfunctions
  2444. generate_process_functions();
  2445. generate_factory();
  2446. }
  2447. void generate_class_definition();
  2448. void generate_dispatch_call(bool template_protocol);
  2449. void generate_process_functions();
  2450. void generate_factory();
  2451. protected:
  2452. std::string type_name(t_type* ttype, bool in_typedef = false, bool arg = false) {
  2453. return generator_->type_name(ttype, in_typedef, arg);
  2454. }
  2455. std::string indent() { return generator_->indent(); }
  2456. std::ostream& indent(std::ostream& os) { return generator_->indent(os); }
  2457. void indent_up() { generator_->indent_up(); }
  2458. void indent_down() { generator_->indent_down(); }
  2459. t_cpp_generator* generator_;
  2460. t_service* service_;
  2461. std::ostream& f_header_;
  2462. std::ostream& f_out_;
  2463. string service_name_;
  2464. string style_;
  2465. string pstyle_;
  2466. string class_name_;
  2467. string if_name_;
  2468. string factory_class_name_;
  2469. string finish_cob_;
  2470. string finish_cob_decl_;
  2471. string ret_type_;
  2472. string call_context_;
  2473. string cob_arg_;
  2474. string call_context_arg_;
  2475. string call_context_decl_;
  2476. string template_header_;
  2477. string template_suffix_;
  2478. string typename_str_;
  2479. string class_suffix_;
  2480. string extends_;
  2481. };
  2482. ProcessorGenerator::ProcessorGenerator(t_cpp_generator* generator,
  2483. t_service* service,
  2484. const string& style)
  2485. : generator_(generator),
  2486. service_(service),
  2487. f_header_(generator->f_header_),
  2488. f_out_(generator->gen_templates_ ? generator->f_service_tcc_ : generator->f_service_),
  2489. service_name_(generator->service_name_),
  2490. style_(style) {
  2491. if (style_ == "Cob") {
  2492. pstyle_ = "Async";
  2493. class_name_ = service_name_ + pstyle_ + "Processor";
  2494. if_name_ = service_name_ + "CobSvIf";
  2495. finish_cob_ = "::apache::thrift::stdcxx::function<void(bool ok)> cob, ";
  2496. finish_cob_decl_ = "::apache::thrift::stdcxx::function<void(bool ok)>, ";
  2497. cob_arg_ = "cob, ";
  2498. ret_type_ = "void ";
  2499. } else {
  2500. class_name_ = service_name_ + "Processor";
  2501. if_name_ = service_name_ + "If";
  2502. ret_type_ = "bool ";
  2503. // TODO(edhall) callContext should eventually be added to TAsyncProcessor
  2504. call_context_ = ", void* callContext";
  2505. call_context_arg_ = ", callContext";
  2506. call_context_decl_ = ", void*";
  2507. }
  2508. factory_class_name_ = class_name_ + "Factory";
  2509. if (generator->gen_templates_) {
  2510. template_header_ = "template <class Protocol_>\n";
  2511. template_suffix_ = "<Protocol_>";
  2512. typename_str_ = "typename ";
  2513. class_name_ += "T";
  2514. factory_class_name_ += "T";
  2515. }
  2516. if (service_->get_extends() != NULL) {
  2517. extends_ = type_name(service_->get_extends()) + pstyle_ + "Processor";
  2518. if (generator_->gen_templates_) {
  2519. // TODO(simpkins): If gen_templates_ is enabled, we currently assume all
  2520. // parent services were also generated with templates enabled.
  2521. extends_ += "T<Protocol_>";
  2522. }
  2523. }
  2524. }
  2525. void ProcessorGenerator::generate_class_definition() {
  2526. // Generate the dispatch methods
  2527. vector<t_function*> functions = service_->get_functions();
  2528. vector<t_function*>::iterator f_iter;
  2529. string parent_class;
  2530. if (service_->get_extends() != NULL) {
  2531. parent_class = extends_;
  2532. } else {
  2533. if (style_ == "Cob") {
  2534. parent_class = "::apache::thrift::async::TAsyncDispatchProcessor";
  2535. } else {
  2536. parent_class = "::apache::thrift::TDispatchProcessor";
  2537. }
  2538. if (generator_->gen_templates_) {
  2539. parent_class += "T<Protocol_>";
  2540. }
  2541. }
  2542. // Generate the header portion
  2543. f_header_ << template_header_ << "class " << class_name_ << " : public " << parent_class << " {"
  2544. << endl;
  2545. // Protected data members
  2546. f_header_ << " protected:" << endl;
  2547. indent_up();
  2548. f_header_ << indent() << "::apache::thrift::stdcxx::shared_ptr<" << if_name_ << "> iface_;" << endl;
  2549. f_header_ << indent() << "virtual " << ret_type_ << "dispatchCall(" << finish_cob_
  2550. << "::apache::thrift::protocol::TProtocol* iprot, "
  2551. << "::apache::thrift::protocol::TProtocol* oprot, "
  2552. << "const std::string& fname, int32_t seqid" << call_context_ << ");" << endl;
  2553. if (generator_->gen_templates_) {
  2554. f_header_ << indent() << "virtual " << ret_type_ << "dispatchCallTemplated(" << finish_cob_
  2555. << "Protocol_* iprot, Protocol_* oprot, "
  2556. << "const std::string& fname, int32_t seqid" << call_context_ << ");" << endl;
  2557. }
  2558. indent_down();
  2559. // Process function declarations
  2560. f_header_ << " private:" << endl;
  2561. indent_up();
  2562. // Declare processMap_
  2563. f_header_ << indent() << "typedef void (" << class_name_ << "::*"
  2564. << "ProcessFunction)(" << finish_cob_decl_ << "int32_t, "
  2565. << "::apache::thrift::protocol::TProtocol*, "
  2566. << "::apache::thrift::protocol::TProtocol*" << call_context_decl_ << ");" << endl;
  2567. if (generator_->gen_templates_) {
  2568. f_header_ << indent() << "typedef void (" << class_name_ << "::*"
  2569. << "SpecializedProcessFunction)(" << finish_cob_decl_ << "int32_t, "
  2570. << "Protocol_*, Protocol_*" << call_context_decl_ << ");" << endl << indent()
  2571. << "struct ProcessFunctions {" << endl << indent() << " ProcessFunction generic;"
  2572. << endl << indent() << " SpecializedProcessFunction specialized;" << endl << indent()
  2573. << " ProcessFunctions(ProcessFunction g, "
  2574. << "SpecializedProcessFunction s) :" << endl << indent() << " generic(g)," << endl
  2575. << indent() << " specialized(s) {}" << endl << indent()
  2576. << " ProcessFunctions() : generic(NULL), specialized(NULL) "
  2577. << "{}" << endl << indent() << "};" << endl << indent()
  2578. << "typedef std::map<std::string, ProcessFunctions> "
  2579. << "ProcessMap;" << endl;
  2580. } else {
  2581. f_header_ << indent() << "typedef std::map<std::string, ProcessFunction> "
  2582. << "ProcessMap;" << endl;
  2583. }
  2584. f_header_ << indent() << "ProcessMap processMap_;" << endl;
  2585. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  2586. indent(f_header_) << "void process_" << (*f_iter)->get_name() << "(" << finish_cob_
  2587. << "int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, "
  2588. "::apache::thrift::protocol::TProtocol* oprot" << call_context_ << ");"
  2589. << endl;
  2590. if (generator_->gen_templates_) {
  2591. indent(f_header_) << "void process_" << (*f_iter)->get_name() << "(" << finish_cob_
  2592. << "int32_t seqid, Protocol_* iprot, Protocol_* oprot" << call_context_
  2593. << ");" << endl;
  2594. }
  2595. if (style_ == "Cob") {
  2596. // XXX Factor this out, even if it is a pain.
  2597. string ret_arg = ((*f_iter)->get_returntype()->is_void()
  2598. ? ""
  2599. : ", const " + type_name((*f_iter)->get_returntype()) + "& _return");
  2600. f_header_ << indent() << "void return_" << (*f_iter)->get_name()
  2601. << "(::apache::thrift::stdcxx::function<void(bool ok)> cob, int32_t seqid, "
  2602. << "::apache::thrift::protocol::TProtocol* oprot, "
  2603. << "void* ctx" << ret_arg << ");" << endl;
  2604. if (generator_->gen_templates_) {
  2605. f_header_ << indent() << "void return_" << (*f_iter)->get_name()
  2606. << "(::apache::thrift::stdcxx::function<void(bool ok)> cob, int32_t seqid, "
  2607. << "Protocol_* oprot, void* ctx" << ret_arg << ");" << endl;
  2608. }
  2609. // XXX Don't declare throw if it doesn't exist
  2610. f_header_ << indent() << "void throw_" << (*f_iter)->get_name()
  2611. << "(::apache::thrift::stdcxx::function<void(bool ok)> cob, int32_t seqid, "
  2612. << "::apache::thrift::protocol::TProtocol* oprot, void* ctx, "
  2613. << "::apache::thrift::TDelayedException* _throw);" << endl;
  2614. if (generator_->gen_templates_) {
  2615. f_header_ << indent() << "void throw_" << (*f_iter)->get_name()
  2616. << "(::apache::thrift::stdcxx::function<void(bool ok)> cob, int32_t seqid, "
  2617. << "Protocol_* oprot, void* ctx, "
  2618. << "::apache::thrift::TDelayedException* _throw);" << endl;
  2619. }
  2620. }
  2621. }
  2622. f_header_ << " public:" << endl << indent() << class_name_ << "(::apache::thrift::stdcxx::shared_ptr<" << if_name_
  2623. << "> iface) :" << endl;
  2624. if (!extends_.empty()) {
  2625. f_header_ << indent() << " " << extends_ << "(iface)," << endl;
  2626. }
  2627. f_header_ << indent() << " iface_(iface) {" << endl;
  2628. indent_up();
  2629. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  2630. f_header_ << indent() << "processMap_[\"" << (*f_iter)->get_name() << "\"] = ";
  2631. if (generator_->gen_templates_) {
  2632. f_header_ << "ProcessFunctions(" << endl;
  2633. if (generator_->gen_templates_only_) {
  2634. indent(f_header_) << " NULL," << endl;
  2635. } else {
  2636. indent(f_header_) << " &" << class_name_ << "::process_" << (*f_iter)->get_name() << ","
  2637. << endl;
  2638. }
  2639. indent(f_header_) << " &" << class_name_ << "::process_" << (*f_iter)->get_name() << ")";
  2640. } else {
  2641. f_header_ << "&" << class_name_ << "::process_" << (*f_iter)->get_name();
  2642. }
  2643. f_header_ << ";" << endl;
  2644. }
  2645. indent_down();
  2646. f_header_ << indent() << "}" << endl << endl << indent() << "virtual ~" << class_name_ << "() {}"
  2647. << endl;
  2648. indent_down();
  2649. f_header_ << "};" << endl << endl;
  2650. if (generator_->gen_templates_) {
  2651. // Generate a backwards compatible typedef, for callers who don't know
  2652. // about the new template-style code.
  2653. //
  2654. // We can't use TProtocol as the template parameter, since ProcessorT
  2655. // provides overloaded versions of most methods, one of which accepts
  2656. // TProtocol pointers, and one which accepts Protocol_ pointers. This
  2657. // results in a compile error if instantiated with Protocol_ == TProtocol.
  2658. // Therefore, we define TDummyProtocol solely so we can use it as the
  2659. // template parameter here.
  2660. f_header_ << "typedef " << class_name_ << "< ::apache::thrift::protocol::TDummyProtocol > "
  2661. << service_name_ << pstyle_ << "Processor;" << endl << endl;
  2662. }
  2663. }
  2664. void ProcessorGenerator::generate_dispatch_call(bool template_protocol) {
  2665. string protocol = "::apache::thrift::protocol::TProtocol";
  2666. string function_suffix;
  2667. if (template_protocol) {
  2668. protocol = "Protocol_";
  2669. // We call the generic version dispatchCall(), and the specialized
  2670. // version dispatchCallTemplated(). We can't call them both
  2671. // dispatchCall(), since this will cause the compiler to issue a warning if
  2672. // a service that doesn't use templates inherits from a service that does
  2673. // use templates: the compiler complains that the subclass only implements
  2674. // the generic version of dispatchCall(), and hides the templated version.
  2675. // Using different names for the two functions prevents this.
  2676. function_suffix = "Templated";
  2677. }
  2678. f_out_ << template_header_ << ret_type_ << class_name_ << template_suffix_ << "::dispatchCall"
  2679. << function_suffix << "(" << finish_cob_ << protocol << "* iprot, " << protocol
  2680. << "* oprot, "
  2681. << "const std::string& fname, int32_t seqid" << call_context_ << ") {" << endl;
  2682. indent_up();
  2683. // HOT: member function pointer map
  2684. f_out_ << indent() << typename_str_ << "ProcessMap::iterator pfn;" << endl << indent()
  2685. << "pfn = processMap_.find(fname);" << endl << indent()
  2686. << "if (pfn == processMap_.end()) {" << endl;
  2687. if (extends_.empty()) {
  2688. f_out_ << indent() << " iprot->skip(::apache::thrift::protocol::T_STRUCT);" << endl << indent()
  2689. << " iprot->readMessageEnd();" << endl << indent()
  2690. << " iprot->getTransport()->readEnd();" << endl << indent()
  2691. << " ::apache::thrift::TApplicationException "
  2692. "x(::apache::thrift::TApplicationException::UNKNOWN_METHOD, \"Invalid method name: "
  2693. "'\"+fname+\"'\");" << endl << indent()
  2694. << " oprot->writeMessageBegin(fname, ::apache::thrift::protocol::T_EXCEPTION, seqid);"
  2695. << endl << indent() << " x.write(oprot);" << endl << indent()
  2696. << " oprot->writeMessageEnd();" << endl << indent()
  2697. << " oprot->getTransport()->writeEnd();" << endl << indent()
  2698. << " oprot->getTransport()->flush();" << endl << indent()
  2699. << (style_ == "Cob" ? " return cob(true);" : " return true;") << endl;
  2700. } else {
  2701. f_out_ << indent() << " return " << extends_ << "::dispatchCall("
  2702. << (style_ == "Cob" ? "cob, " : "") << "iprot, oprot, fname, seqid" << call_context_arg_
  2703. << ");" << endl;
  2704. }
  2705. f_out_ << indent() << "}" << endl;
  2706. if (template_protocol) {
  2707. f_out_ << indent() << "(this->*(pfn->second.specialized))";
  2708. } else {
  2709. if (generator_->gen_templates_only_) {
  2710. // TODO: This is a null pointer, so nothing good will come from calling
  2711. // it. Throw an exception instead.
  2712. f_out_ << indent() << "(this->*(pfn->second.generic))";
  2713. } else if (generator_->gen_templates_) {
  2714. f_out_ << indent() << "(this->*(pfn->second.generic))";
  2715. } else {
  2716. f_out_ << indent() << "(this->*(pfn->second))";
  2717. }
  2718. }
  2719. f_out_ << "(" << cob_arg_ << "seqid, iprot, oprot" << call_context_arg_ << ");" << endl;
  2720. // TODO(dreiss): return pfn ret?
  2721. if (style_ == "Cob") {
  2722. f_out_ << indent() << "return;" << endl;
  2723. } else {
  2724. f_out_ << indent() << "return true;" << endl;
  2725. }
  2726. indent_down();
  2727. f_out_ << "}" << endl << endl;
  2728. }
  2729. void ProcessorGenerator::generate_process_functions() {
  2730. vector<t_function*> functions = service_->get_functions();
  2731. vector<t_function*>::iterator f_iter;
  2732. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  2733. if (generator_->gen_templates_) {
  2734. generator_->generate_process_function(service_, *f_iter, style_, false);
  2735. generator_->generate_process_function(service_, *f_iter, style_, true);
  2736. } else {
  2737. generator_->generate_process_function(service_, *f_iter, style_, false);
  2738. }
  2739. }
  2740. }
  2741. void ProcessorGenerator::generate_factory() {
  2742. string if_factory_name = if_name_ + "Factory";
  2743. // Generate the factory class definition
  2744. f_header_ << template_header_ << "class " << factory_class_name_ << " : public ::apache::thrift::"
  2745. << (style_ == "Cob" ? "async::TAsyncProcessorFactory" : "TProcessorFactory") << " {"
  2746. << endl << " public:" << endl;
  2747. indent_up();
  2748. f_header_ << indent() << factory_class_name_ << "(const ::apache::thrift::stdcxx::shared_ptr< " << if_factory_name
  2749. << " >& handlerFactory) :" << endl << indent()
  2750. << " handlerFactory_(handlerFactory) {}" << endl << endl << indent()
  2751. << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::"
  2752. << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > "
  2753. << "getProcessor(const ::apache::thrift::TConnectionInfo& connInfo);" << endl;
  2754. f_header_ << endl << " protected:" << endl << indent() << "::apache::thrift::stdcxx::shared_ptr< "
  2755. << if_factory_name << " > handlerFactory_;" << endl;
  2756. indent_down();
  2757. f_header_ << "};" << endl << endl;
  2758. // If we are generating templates, output a typedef for the plain
  2759. // factory name.
  2760. if (generator_->gen_templates_) {
  2761. f_header_ << "typedef " << factory_class_name_
  2762. << "< ::apache::thrift::protocol::TDummyProtocol > " << service_name_ << pstyle_
  2763. << "ProcessorFactory;" << endl << endl;
  2764. }
  2765. // Generate the getProcessor() method
  2766. f_out_ << template_header_ << indent() << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::"
  2767. << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > "
  2768. << factory_class_name_ << template_suffix_ << "::getProcessor("
  2769. << "const ::apache::thrift::TConnectionInfo& connInfo) {" << endl;
  2770. indent_up();
  2771. f_out_ << indent() << "::apache::thrift::ReleaseHandler< " << if_factory_name
  2772. << " > cleanup(handlerFactory_);" << endl << indent() << "::apache::thrift::stdcxx::shared_ptr< "
  2773. << if_name_ << " > handler("
  2774. << "handlerFactory_->getHandler(connInfo), cleanup);" << endl << indent()
  2775. << "::apache::thrift::stdcxx::shared_ptr< ::apache::thrift::"
  2776. << (style_ == "Cob" ? "async::TAsyncProcessor" : "TProcessor") << " > "
  2777. << "processor(new " << class_name_ << template_suffix_ << "(handler));" << endl << indent()
  2778. << "return processor;" << endl;
  2779. indent_down();
  2780. f_out_ << indent() << "}" << endl << endl;
  2781. }
  2782. /**
  2783. * Generates a service processor definition.
  2784. *
  2785. * @param tservice The service to generate a processor for.
  2786. */
  2787. void t_cpp_generator::generate_service_processor(t_service* tservice, string style) {
  2788. ProcessorGenerator generator(this, tservice, style);
  2789. generator.run();
  2790. }
  2791. /**
  2792. * Generates a struct and helpers for a function.
  2793. *
  2794. * @param tfunction The function
  2795. */
  2796. void t_cpp_generator::generate_function_helpers(t_service* tservice, t_function* tfunction) {
  2797. if (tfunction->is_oneway()) {
  2798. return;
  2799. }
  2800. std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);
  2801. t_struct result(program_, tservice->get_name() + "_" + tfunction->get_name() + "_result");
  2802. t_field success(tfunction->get_returntype(), "success", 0);
  2803. if (!tfunction->get_returntype()->is_void()) {
  2804. result.append(&success);
  2805. }
  2806. t_struct* xs = tfunction->get_xceptions();
  2807. const vector<t_field*>& fields = xs->get_members();
  2808. vector<t_field*>::const_iterator f_iter;
  2809. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  2810. result.append(*f_iter);
  2811. }
  2812. generate_struct_declaration(f_header_, &result, false);
  2813. generate_struct_definition(out, f_service_, &result, false);
  2814. generate_struct_reader(out, &result);
  2815. generate_struct_result_writer(out, &result);
  2816. result.set_name(tservice->get_name() + "_" + tfunction->get_name() + "_presult");
  2817. generate_struct_declaration(f_header_, &result, false, true, true, gen_cob_style_);
  2818. generate_struct_definition(out, f_service_, &result, false);
  2819. generate_struct_reader(out, &result, true);
  2820. if (gen_cob_style_) {
  2821. generate_struct_writer(out, &result, true);
  2822. }
  2823. }
  2824. /**
  2825. * Generates a process function definition.
  2826. *
  2827. * @param tfunction The function to write a dispatcher for
  2828. */
  2829. void t_cpp_generator::generate_process_function(t_service* tservice,
  2830. t_function* tfunction,
  2831. string style,
  2832. bool specialized) {
  2833. t_struct* arg_struct = tfunction->get_arglist();
  2834. const std::vector<t_field*>& fields = arg_struct->get_members();
  2835. vector<t_field*>::const_iterator f_iter;
  2836. t_struct* xs = tfunction->get_xceptions();
  2837. const std::vector<t_field*>& xceptions = xs->get_members();
  2838. vector<t_field*>::const_iterator x_iter;
  2839. string service_func_name = "\"" + tservice->get_name() + "." + tfunction->get_name() + "\"";
  2840. std::ostream& out = (gen_templates_ ? f_service_tcc_ : f_service_);
  2841. string prot_type = (specialized ? "Protocol_" : "::apache::thrift::protocol::TProtocol");
  2842. string class_suffix;
  2843. if (gen_templates_) {
  2844. class_suffix = "T<Protocol_>";
  2845. }
  2846. // I tried to do this as one function. I really did. But it was too hard.
  2847. if (style != "Cob") {
  2848. // Open function
  2849. if (gen_templates_) {
  2850. out << indent() << "template <class Protocol_>" << endl;
  2851. }
  2852. const bool unnamed_oprot_seqid = tfunction->is_oneway() && !(gen_templates_ && !specialized);
  2853. out << "void " << tservice->get_name() << "Processor" << class_suffix << "::"
  2854. << "process_" << tfunction->get_name() << "("
  2855. << "int32_t" << (unnamed_oprot_seqid ? ", " : " seqid, ") << prot_type << "* iprot, "
  2856. << prot_type << "*" << (unnamed_oprot_seqid ? ", " : " oprot, ") << "void* callContext)"
  2857. << endl;
  2858. scope_up(out);
  2859. string argsname = tservice->get_name() + "_" + tfunction->get_name() + "_args";
  2860. string resultname = tservice->get_name() + "_" + tfunction->get_name() + "_result";
  2861. if (tfunction->is_oneway() && !unnamed_oprot_seqid) {
  2862. out << indent() << "(void) seqid;" << endl << indent() << "(void) oprot;" << endl;
  2863. }
  2864. out << indent() << "void* ctx = NULL;" << endl << indent()
  2865. << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  2866. << " ctx = this->eventHandler_->getContext(" << service_func_name << ", callContext);"
  2867. << endl << indent() << "}" << endl << indent()
  2868. << "::apache::thrift::TProcessorContextFreer freer("
  2869. << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl
  2870. << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  2871. << " this->eventHandler_->preRead(ctx, " << service_func_name << ");" << endl << indent()
  2872. << "}" << endl << endl << indent() << argsname << " args;" << endl << indent()
  2873. << "args.read(iprot);" << endl << indent() << "iprot->readMessageEnd();" << endl << indent()
  2874. << "uint32_t bytes = iprot->getTransport()->readEnd();" << endl << endl << indent()
  2875. << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  2876. << " this->eventHandler_->postRead(ctx, " << service_func_name << ", bytes);" << endl
  2877. << indent() << "}" << endl << endl;
  2878. // Declare result
  2879. if (!tfunction->is_oneway()) {
  2880. out << indent() << resultname << " result;" << endl;
  2881. }
  2882. // Try block for functions with exceptions
  2883. out << indent() << "try {" << endl;
  2884. indent_up();
  2885. // Generate the function call
  2886. bool first = true;
  2887. out << indent();
  2888. if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) {
  2889. if (is_complex_type(tfunction->get_returntype())) {
  2890. first = false;
  2891. out << "iface_->" << tfunction->get_name() << "(result.success";
  2892. } else {
  2893. out << "result.success = iface_->" << tfunction->get_name() << "(";
  2894. }
  2895. } else {
  2896. out << "iface_->" << tfunction->get_name() << "(";
  2897. }
  2898. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  2899. if (first) {
  2900. first = false;
  2901. } else {
  2902. out << ", ";
  2903. }
  2904. out << "args." << (*f_iter)->get_name();
  2905. }
  2906. out << ");" << endl;
  2907. // Set isset on success field
  2908. if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) {
  2909. out << indent() << "result.__isset.success = true;" << endl;
  2910. }
  2911. indent_down();
  2912. out << indent() << "}";
  2913. if (!tfunction->is_oneway()) {
  2914. for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
  2915. out << " catch (" << type_name((*x_iter)->get_type()) << " &" << (*x_iter)->get_name()
  2916. << ") {" << endl;
  2917. if (!tfunction->is_oneway()) {
  2918. indent_up();
  2919. out << indent() << "result." << (*x_iter)->get_name() << " = " << (*x_iter)->get_name()
  2920. << ";" << endl << indent() << "result.__isset." << (*x_iter)->get_name() << " = true;"
  2921. << endl;
  2922. indent_down();
  2923. out << indent() << "}";
  2924. } else {
  2925. out << "}";
  2926. }
  2927. }
  2928. }
  2929. if (!tfunction->is_oneway()) {
  2930. out << " catch (const std::exception& e) {" << endl;
  2931. } else {
  2932. out << " catch (const std::exception&) {" << endl;
  2933. }
  2934. indent_up();
  2935. out << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  2936. << " this->eventHandler_->handlerError(ctx, " << service_func_name << ");" << endl
  2937. << indent() << "}" << endl;
  2938. if (!tfunction->is_oneway()) {
  2939. out << endl << indent() << "::apache::thrift::TApplicationException x(e.what());" << endl
  2940. << indent() << "oprot->writeMessageBegin(\"" << tfunction->get_name()
  2941. << "\", ::apache::thrift::protocol::T_EXCEPTION, seqid);" << endl << indent()
  2942. << "x.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();" << endl
  2943. << indent() << "oprot->getTransport()->writeEnd();" << endl << indent()
  2944. << "oprot->getTransport()->flush();" << endl;
  2945. }
  2946. out << indent() << "return;" << endl;
  2947. indent_down();
  2948. out << indent() << "}" << endl << endl;
  2949. // Shortcut out here for oneway functions
  2950. if (tfunction->is_oneway()) {
  2951. out << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  2952. << " this->eventHandler_->asyncComplete(ctx, " << service_func_name << ");" << endl
  2953. << indent() << "}" << endl << endl << indent() << "return;" << endl;
  2954. indent_down();
  2955. out << "}" << endl << endl;
  2956. return;
  2957. }
  2958. // Serialize the result into a struct
  2959. out << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  2960. << " this->eventHandler_->preWrite(ctx, " << service_func_name << ");" << endl << indent()
  2961. << "}" << endl << endl << indent() << "oprot->writeMessageBegin(\"" << tfunction->get_name()
  2962. << "\", ::apache::thrift::protocol::T_REPLY, seqid);" << endl << indent()
  2963. << "result.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();" << endl
  2964. << indent() << "bytes = oprot->getTransport()->writeEnd();" << endl << indent()
  2965. << "oprot->getTransport()->flush();" << endl << endl << indent()
  2966. << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  2967. << " this->eventHandler_->postWrite(ctx, " << service_func_name << ", bytes);" << endl
  2968. << indent() << "}" << endl;
  2969. // Close function
  2970. scope_down(out);
  2971. out << endl;
  2972. }
  2973. // Cob style.
  2974. else {
  2975. // Processor entry point.
  2976. // TODO(edhall) update for callContext when TEventServer is ready
  2977. if (gen_templates_) {
  2978. out << indent() << "template <class Protocol_>" << endl;
  2979. }
  2980. out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::process_"
  2981. << tfunction->get_name() << "(::apache::thrift::stdcxx::function<void(bool ok)> cob, int32_t seqid, "
  2982. << prot_type << "* iprot, " << prot_type << "* oprot)" << endl;
  2983. scope_up(out);
  2984. // TODO(simpkins): we could try to consoldate this
  2985. // with the non-cob code above
  2986. if (gen_templates_ && !specialized) {
  2987. // If these are instances of Protocol_, instead of any old TProtocol,
  2988. // use the specialized process function instead.
  2989. out << indent() << "Protocol_* _iprot = dynamic_cast<Protocol_*>(iprot);" << endl << indent()
  2990. << "Protocol_* _oprot = dynamic_cast<Protocol_*>(oprot);" << endl << indent()
  2991. << "if (_iprot && _oprot) {" << endl << indent() << " return process_"
  2992. << tfunction->get_name() << "(cob, seqid, _iprot, _oprot);" << endl << indent() << "}"
  2993. << endl << indent() << "T_GENERIC_PROTOCOL(this, iprot, _iprot);" << endl << indent()
  2994. << "T_GENERIC_PROTOCOL(this, oprot, _oprot);" << endl << endl;
  2995. }
  2996. if (tfunction->is_oneway()) {
  2997. out << indent() << "(void) seqid;" << endl << indent() << "(void) oprot;" << endl;
  2998. }
  2999. out << indent() << tservice->get_name() + "_" + tfunction->get_name() << "_args args;" << endl
  3000. << indent() << "void* ctx = NULL;" << endl << indent()
  3001. << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3002. << " ctx = this->eventHandler_->getContext(" << service_func_name << ", NULL);" << endl
  3003. << indent() << "}" << endl << indent() << "::apache::thrift::TProcessorContextFreer freer("
  3004. << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl
  3005. << indent() << "try {" << endl;
  3006. indent_up();
  3007. out << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3008. << " this->eventHandler_->preRead(ctx, " << service_func_name << ");" << endl << indent()
  3009. << "}" << endl << indent() << "args.read(iprot);" << endl << indent()
  3010. << "iprot->readMessageEnd();" << endl << indent()
  3011. << "uint32_t bytes = iprot->getTransport()->readEnd();" << endl << indent()
  3012. << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3013. << " this->eventHandler_->postRead(ctx, " << service_func_name << ", bytes);" << endl
  3014. << indent() << "}" << endl;
  3015. scope_down(out);
  3016. // TODO(dreiss): Handle TExceptions? Expose to server?
  3017. out << indent() << "catch (const std::exception&) {" << endl << indent()
  3018. << " if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3019. << " this->eventHandler_->handlerError(ctx, " << service_func_name << ");" << endl
  3020. << indent() << " }" << endl << indent() << " return cob(false);" << endl << indent()
  3021. << "}" << endl;
  3022. if (tfunction->is_oneway()) {
  3023. out << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3024. << " this->eventHandler_->asyncComplete(ctx, " << service_func_name << ");" << endl
  3025. << indent() << "}" << endl;
  3026. }
  3027. // TODO(dreiss): Figure out a strategy for exceptions in async handlers.
  3028. out << indent() << "freer.unregister();" << endl;
  3029. if (tfunction->is_oneway()) {
  3030. // No return. Just hand off our cob.
  3031. // TODO(dreiss): Call the cob immediately?
  3032. out << indent() << "iface_->" << tfunction->get_name() << "("
  3033. << "::apache::thrift::stdcxx::bind(cob, true)" << endl;
  3034. indent_up();
  3035. indent_up();
  3036. } else {
  3037. string ret_arg, ret_placeholder;
  3038. if (!tfunction->get_returntype()->is_void()) {
  3039. ret_arg = ", const " + type_name(tfunction->get_returntype()) + "& _return";
  3040. ret_placeholder = ", ::apache::thrift::stdcxx::placeholders::_1";
  3041. }
  3042. // When gen_templates_ is true, the return_ and throw_ functions are
  3043. // overloaded. We have to declare pointers to them so that the compiler
  3044. // can resolve the correct overloaded version.
  3045. out << indent() << "void (" << tservice->get_name() << "AsyncProcessor" << class_suffix
  3046. << "::*return_fn)(::apache::thrift::stdcxx::function<void(bool ok)> "
  3047. << "cob, int32_t seqid, " << prot_type << "* oprot, void* ctx" << ret_arg
  3048. << ") =" << endl;
  3049. out << indent() << " &" << tservice->get_name() << "AsyncProcessor" << class_suffix
  3050. << "::return_" << tfunction->get_name() << ";" << endl;
  3051. if (!xceptions.empty()) {
  3052. out << indent() << "void (" << tservice->get_name() << "AsyncProcessor" << class_suffix
  3053. << "::*throw_fn)(::apache::thrift::stdcxx::function<void(bool ok)> "
  3054. << "cob, int32_t seqid, " << prot_type << "* oprot, void* ctx, "
  3055. << "::apache::thrift::TDelayedException* _throw) =" << endl;
  3056. out << indent() << " &" << tservice->get_name() << "AsyncProcessor" << class_suffix
  3057. << "::throw_" << tfunction->get_name() << ";" << endl;
  3058. }
  3059. out << indent() << "iface_->" << tfunction->get_name() << "(" << endl;
  3060. indent_up();
  3061. indent_up();
  3062. out << indent() << "::apache::thrift::stdcxx::bind(return_fn, this, cob, seqid, oprot, ctx" << ret_placeholder
  3063. << ")";
  3064. if (!xceptions.empty()) {
  3065. out << ',' << endl << indent() << "::apache::thrift::stdcxx::bind(throw_fn, this, cob, seqid, oprot, "
  3066. << "ctx, ::apache::thrift::stdcxx::placeholders::_1)";
  3067. }
  3068. }
  3069. // XXX Whitespace cleanup.
  3070. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  3071. out << ',' << endl << indent() << "args." << (*f_iter)->get_name();
  3072. }
  3073. out << ");" << endl;
  3074. indent_down();
  3075. indent_down();
  3076. scope_down(out);
  3077. out << endl;
  3078. // Normal return.
  3079. if (!tfunction->is_oneway()) {
  3080. string ret_arg_decl, ret_arg_name;
  3081. if (!tfunction->get_returntype()->is_void()) {
  3082. ret_arg_decl = ", const " + type_name(tfunction->get_returntype()) + "& _return";
  3083. ret_arg_name = ", _return";
  3084. }
  3085. if (gen_templates_) {
  3086. out << indent() << "template <class Protocol_>" << endl;
  3087. }
  3088. out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::return_"
  3089. << tfunction->get_name() << "(::apache::thrift::stdcxx::function<void(bool ok)> cob, int32_t seqid, "
  3090. << prot_type << "* oprot, void* ctx" << ret_arg_decl << ')' << endl;
  3091. scope_up(out);
  3092. if (gen_templates_ && !specialized) {
  3093. // If oprot is a Protocol_ instance,
  3094. // use the specialized return function instead.
  3095. out << indent() << "Protocol_* _oprot = dynamic_cast<Protocol_*>(oprot);" << endl
  3096. << indent() << "if (_oprot) {" << endl << indent() << " return return_"
  3097. << tfunction->get_name() << "(cob, seqid, _oprot, ctx" << ret_arg_name << ");" << endl
  3098. << indent() << "}" << endl << indent() << "T_GENERIC_PROTOCOL(this, oprot, _oprot);"
  3099. << endl << endl;
  3100. }
  3101. out << indent() << tservice->get_name() << "_" << tfunction->get_name() << "_presult result;"
  3102. << endl;
  3103. if (!tfunction->get_returntype()->is_void()) {
  3104. // The const_cast here is unfortunate, but it would be a pain to avoid,
  3105. // and we only do a write with this struct, which is const-safe.
  3106. out << indent() << "result.success = const_cast<" << type_name(tfunction->get_returntype())
  3107. << "*>(&_return);" << endl << indent() << "result.__isset.success = true;" << endl;
  3108. }
  3109. // Serialize the result into a struct
  3110. out << endl << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3111. << " ctx = this->eventHandler_->getContext(" << service_func_name << ", NULL);" << endl
  3112. << indent() << "}" << endl << indent()
  3113. << "::apache::thrift::TProcessorContextFreer freer("
  3114. << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl
  3115. << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3116. << " this->eventHandler_->preWrite(ctx, " << service_func_name << ");" << endl
  3117. << indent() << "}" << endl << endl << indent() << "oprot->writeMessageBegin(\""
  3118. << tfunction->get_name() << "\", ::apache::thrift::protocol::T_REPLY, seqid);" << endl
  3119. << indent() << "result.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();"
  3120. << endl << indent() << "uint32_t bytes = oprot->getTransport()->writeEnd();" << endl
  3121. << indent() << "oprot->getTransport()->flush();" << endl << indent()
  3122. << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3123. << " this->eventHandler_->postWrite(ctx, " << service_func_name << ", bytes);" << endl
  3124. << indent() << "}" << endl << indent() << "return cob(true);" << endl;
  3125. scope_down(out);
  3126. out << endl;
  3127. }
  3128. // Exception return.
  3129. if (!tfunction->is_oneway() && !xceptions.empty()) {
  3130. if (gen_templates_) {
  3131. out << indent() << "template <class Protocol_>" << endl;
  3132. }
  3133. out << "void " << tservice->get_name() << "AsyncProcessor" << class_suffix << "::throw_"
  3134. << tfunction->get_name() << "(::apache::thrift::stdcxx::function<void(bool ok)> cob, int32_t seqid, "
  3135. << prot_type << "* oprot, void* ctx, "
  3136. << "::apache::thrift::TDelayedException* _throw)" << endl;
  3137. scope_up(out);
  3138. if (gen_templates_ && !specialized) {
  3139. // If oprot is a Protocol_ instance,
  3140. // use the specialized throw function instead.
  3141. out << indent() << "Protocol_* _oprot = dynamic_cast<Protocol_*>(oprot);" << endl
  3142. << indent() << "if (_oprot) {" << endl << indent() << " return throw_"
  3143. << tfunction->get_name() << "(cob, seqid, _oprot, ctx, _throw);" << endl << indent()
  3144. << "}" << endl << indent() << "T_GENERIC_PROTOCOL(this, oprot, _oprot);" << endl
  3145. << endl;
  3146. }
  3147. // Get the event handler context
  3148. out << endl << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3149. << " ctx = this->eventHandler_->getContext(" << service_func_name << ", NULL);" << endl
  3150. << indent() << "}" << endl << indent()
  3151. << "::apache::thrift::TProcessorContextFreer freer("
  3152. << "this->eventHandler_.get(), ctx, " << service_func_name << ");" << endl << endl;
  3153. // Throw the TDelayedException, and catch the result
  3154. out << indent() << tservice->get_name() << "_" << tfunction->get_name() << "_result result;"
  3155. << endl << endl << indent() << "try {" << endl;
  3156. indent_up();
  3157. out << indent() << "_throw->throw_it();" << endl << indent() << "return cob(false);"
  3158. << endl; // Is this possible? TBD.
  3159. indent_down();
  3160. out << indent() << '}';
  3161. for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
  3162. out << " catch (" << type_name((*x_iter)->get_type()) << " &" << (*x_iter)->get_name()
  3163. << ") {" << endl;
  3164. indent_up();
  3165. out << indent() << "result." << (*x_iter)->get_name() << " = " << (*x_iter)->get_name()
  3166. << ";" << endl << indent() << "result.__isset." << (*x_iter)->get_name() << " = true;"
  3167. << endl;
  3168. scope_down(out);
  3169. }
  3170. // Handle the case where an undeclared exception is thrown
  3171. out << " catch (std::exception& e) {" << endl;
  3172. indent_up();
  3173. out << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3174. << " this->eventHandler_->handlerError(ctx, " << service_func_name << ");" << endl
  3175. << indent() << "}" << endl << endl << indent()
  3176. << "::apache::thrift::TApplicationException x(e.what());" << endl << indent()
  3177. << "oprot->writeMessageBegin(\"" << tfunction->get_name()
  3178. << "\", ::apache::thrift::protocol::T_EXCEPTION, seqid);" << endl << indent()
  3179. << "x.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();" << endl
  3180. << indent() << "oprot->getTransport()->writeEnd();" << endl << indent()
  3181. << "oprot->getTransport()->flush();" << endl <<
  3182. // We pass true to the cob here, since we did successfully write a
  3183. // response, even though it is an exception response.
  3184. // It looks like the argument is currently ignored, anyway.
  3185. indent() << "return cob(true);" << endl;
  3186. scope_down(out);
  3187. // Serialize the result into a struct
  3188. out << indent() << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3189. << " this->eventHandler_->preWrite(ctx, " << service_func_name << ");" << endl
  3190. << indent() << "}" << endl << endl << indent() << "oprot->writeMessageBegin(\""
  3191. << tfunction->get_name() << "\", ::apache::thrift::protocol::T_REPLY, seqid);" << endl
  3192. << indent() << "result.write(oprot);" << endl << indent() << "oprot->writeMessageEnd();"
  3193. << endl << indent() << "uint32_t bytes = oprot->getTransport()->writeEnd();" << endl
  3194. << indent() << "oprot->getTransport()->flush();" << endl << indent()
  3195. << "if (this->eventHandler_.get() != NULL) {" << endl << indent()
  3196. << " this->eventHandler_->postWrite(ctx, " << service_func_name << ", bytes);" << endl
  3197. << indent() << "}" << endl << indent() << "return cob(true);" << endl;
  3198. scope_down(out);
  3199. out << endl;
  3200. } // for each function
  3201. } // cob style
  3202. }
  3203. /**
  3204. * Generates a skeleton file of a server
  3205. *
  3206. * @param tservice The service to generate a server for.
  3207. */
  3208. void t_cpp_generator::generate_service_skeleton(t_service* tservice) {
  3209. string svcname = tservice->get_name();
  3210. // Service implementation file includes
  3211. string f_skeleton_name = get_out_dir() + svcname + "_server.skeleton.cpp";
  3212. string ns = namespace_prefix(tservice->get_program()->get_namespace("cpp"));
  3213. ofstream_with_content_based_conditional_update f_skeleton;
  3214. f_skeleton.open(f_skeleton_name.c_str());
  3215. f_skeleton << "// This autogenerated skeleton file illustrates how to build a server." << endl
  3216. << "// You should copy it to another filename to avoid overwriting it." << endl << endl
  3217. << "#include \"" << get_include_prefix(*get_program()) << svcname << ".h\"" << endl
  3218. << "#include <thrift/protocol/TBinaryProtocol.h>" << endl
  3219. << "#include <thrift/server/TSimpleServer.h>" << endl
  3220. << "#include <thrift/transport/TServerSocket.h>" << endl
  3221. << "#include <thrift/transport/TBufferTransports.h>" << endl << endl
  3222. << "using namespace ::apache::thrift;" << endl
  3223. << "using namespace ::apache::thrift::protocol;" << endl
  3224. << "using namespace ::apache::thrift::transport;" << endl
  3225. << "using namespace ::apache::thrift::server;" << endl << endl;
  3226. // the following code would not compile:
  3227. // using namespace ;
  3228. // using namespace ::;
  3229. if ((!ns.empty()) && (ns.compare(" ::") != 0)) {
  3230. f_skeleton << "using namespace " << string(ns, 0, ns.size() - 2) << ";" << endl << endl;
  3231. }
  3232. f_skeleton << "class " << svcname << "Handler : virtual public " << svcname << "If {" << endl
  3233. << " public:" << endl;
  3234. indent_up();
  3235. f_skeleton << indent() << svcname << "Handler() {" << endl << indent()
  3236. << " // Your initialization goes here" << endl << indent() << "}" << endl << endl;
  3237. vector<t_function*> functions = tservice->get_functions();
  3238. vector<t_function*>::iterator f_iter;
  3239. for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
  3240. generate_java_doc(f_skeleton, *f_iter);
  3241. f_skeleton << indent() << function_signature(*f_iter, "") << " {" << endl << indent()
  3242. << " // Your implementation goes here" << endl << indent() << " printf(\""
  3243. << (*f_iter)->get_name() << "\\n\");" << endl << indent() << "}" << endl << endl;
  3244. }
  3245. indent_down();
  3246. f_skeleton << "};" << endl << endl;
  3247. f_skeleton << indent() << "int main(int argc, char **argv) {" << endl;
  3248. indent_up();
  3249. f_skeleton
  3250. << indent() << "int port = 9090;" << endl << indent() << "::apache::thrift::stdcxx::shared_ptr<" << svcname
  3251. << "Handler> handler(new " << svcname << "Handler());" << endl << indent()
  3252. << "::apache::thrift::stdcxx::shared_ptr<TProcessor> processor(new " << svcname << "Processor(handler));" << endl
  3253. << indent() << "::apache::thrift::stdcxx::shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));"
  3254. << endl << indent()
  3255. << "::apache::thrift::stdcxx::shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());" << endl
  3256. << indent() << "::apache::thrift::stdcxx::shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());"
  3257. << endl << endl << indent()
  3258. << "TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);"
  3259. << endl << indent() << "server.serve();" << endl << indent() << "return 0;" << endl;
  3260. indent_down();
  3261. f_skeleton << "}" << endl << endl;
  3262. // Close the files
  3263. f_skeleton.close();
  3264. }
  3265. /**
  3266. * Deserializes a field of any type.
  3267. */
  3268. void t_cpp_generator::generate_deserialize_field(ostream& out,
  3269. t_field* tfield,
  3270. string prefix,
  3271. string suffix) {
  3272. t_type* type = get_true_type(tfield->get_type());
  3273. if (type->is_void()) {
  3274. throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " + prefix + tfield->get_name();
  3275. }
  3276. string name = prefix + tfield->get_name() + suffix;
  3277. if (type->is_struct() || type->is_xception()) {
  3278. generate_deserialize_struct(out, (t_struct*)type, name, is_reference(tfield));
  3279. } else if (type->is_container()) {
  3280. generate_deserialize_container(out, type, name);
  3281. } else if (type->is_base_type()) {
  3282. indent(out) << "xfer += iprot->";
  3283. t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
  3284. switch (tbase) {
  3285. case t_base_type::TYPE_VOID:
  3286. throw "compiler error: cannot serialize void field in a struct: " + name;
  3287. break;
  3288. case t_base_type::TYPE_STRING:
  3289. if (type->is_binary()) {
  3290. out << "readBinary(" << name << ");";
  3291. } else {
  3292. out << "readString(" << name << ");";
  3293. }
  3294. break;
  3295. case t_base_type::TYPE_BOOL:
  3296. out << "readBool(" << name << ");";
  3297. break;
  3298. case t_base_type::TYPE_I8:
  3299. out << "readByte(" << name << ");";
  3300. break;
  3301. case t_base_type::TYPE_I16:
  3302. out << "readI16(" << name << ");";
  3303. break;
  3304. case t_base_type::TYPE_I32:
  3305. out << "readI32(" << name << ");";
  3306. break;
  3307. case t_base_type::TYPE_I64:
  3308. out << "readI64(" << name << ");";
  3309. break;
  3310. case t_base_type::TYPE_DOUBLE:
  3311. out << "readDouble(" << name << ");";
  3312. break;
  3313. default:
  3314. throw "compiler error: no C++ reader for base type " + t_base_type::t_base_name(tbase) + name;
  3315. }
  3316. out << endl;
  3317. } else if (type->is_enum()) {
  3318. string t = tmp("ecast");
  3319. out << indent() << "int32_t " << t << ";" << endl << indent() << "xfer += iprot->readI32(" << t
  3320. << ");" << endl << indent() << name << " = (" << type_name(type) << ")" << t << ";" << endl;
  3321. } else {
  3322. printf("DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n",
  3323. tfield->get_name().c_str(),
  3324. type_name(type).c_str());
  3325. }
  3326. }
  3327. /**
  3328. * Generates an unserializer for a variable. This makes two key assumptions,
  3329. * first that there is a const char* variable named data that points to the
  3330. * buffer for deserialization, and that there is a variable protocol which
  3331. * is a reference to a TProtocol serialization object.
  3332. */
  3333. void t_cpp_generator::generate_deserialize_struct(ostream& out,
  3334. t_struct* tstruct,
  3335. string prefix,
  3336. bool pointer) {
  3337. if (pointer) {
  3338. indent(out) << "if (!" << prefix << ") { " << endl;
  3339. indent(out) << " " << prefix << " = ::apache::thrift::stdcxx::shared_ptr<" << type_name(tstruct) << ">(new "
  3340. << type_name(tstruct) << ");" << endl;
  3341. indent(out) << "}" << endl;
  3342. indent(out) << "xfer += " << prefix << "->read(iprot);" << endl;
  3343. indent(out) << "bool wasSet = false;" << endl;
  3344. const vector<t_field*>& members = tstruct->get_members();
  3345. vector<t_field*>::const_iterator f_iter;
  3346. for (f_iter = members.begin(); f_iter != members.end(); ++f_iter) {
  3347. indent(out) << "if (" << prefix << "->__isset." << (*f_iter)->get_name()
  3348. << ") { wasSet = true; }" << endl;
  3349. }
  3350. indent(out) << "if (!wasSet) { " << prefix << ".reset(); }" << endl;
  3351. } else {
  3352. indent(out) << "xfer += " << prefix << ".read(iprot);" << endl;
  3353. }
  3354. }
  3355. void t_cpp_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) {
  3356. scope_up(out);
  3357. string size = tmp("_size");
  3358. string ktype = tmp("_ktype");
  3359. string vtype = tmp("_vtype");
  3360. string etype = tmp("_etype");
  3361. t_container* tcontainer = (t_container*)ttype;
  3362. bool use_push = tcontainer->has_cpp_name();
  3363. indent(out) << prefix << ".clear();" << endl << indent() << "uint32_t " << size << ";" << endl;
  3364. // Declare variables, read header
  3365. if (ttype->is_map()) {
  3366. out << indent() << "::apache::thrift::protocol::TType " << ktype << ";" << endl << indent()
  3367. << "::apache::thrift::protocol::TType " << vtype << ";" << endl << indent()
  3368. << "xfer += iprot->readMapBegin(" << ktype << ", " << vtype << ", " << size << ");" << endl;
  3369. } else if (ttype->is_set()) {
  3370. out << indent() << "::apache::thrift::protocol::TType " << etype << ";" << endl << indent()
  3371. << "xfer += iprot->readSetBegin(" << etype << ", " << size << ");" << endl;
  3372. } else if (ttype->is_list()) {
  3373. out << indent() << "::apache::thrift::protocol::TType " << etype << ";" << endl << indent()
  3374. << "xfer += iprot->readListBegin(" << etype << ", " << size << ");" << endl;
  3375. if (!use_push) {
  3376. indent(out) << prefix << ".resize(" << size << ");" << endl;
  3377. }
  3378. }
  3379. // For loop iterates over elements
  3380. string i = tmp("_i");
  3381. out << indent() << "uint32_t " << i << ";" << endl << indent() << "for (" << i << " = 0; " << i
  3382. << " < " << size << "; ++" << i << ")" << endl;
  3383. scope_up(out);
  3384. if (ttype->is_map()) {
  3385. generate_deserialize_map_element(out, (t_map*)ttype, prefix);
  3386. } else if (ttype->is_set()) {
  3387. generate_deserialize_set_element(out, (t_set*)ttype, prefix);
  3388. } else if (ttype->is_list()) {
  3389. generate_deserialize_list_element(out, (t_list*)ttype, prefix, use_push, i);
  3390. }
  3391. scope_down(out);
  3392. // Read container end
  3393. if (ttype->is_map()) {
  3394. indent(out) << "xfer += iprot->readMapEnd();" << endl;
  3395. } else if (ttype->is_set()) {
  3396. indent(out) << "xfer += iprot->readSetEnd();" << endl;
  3397. } else if (ttype->is_list()) {
  3398. indent(out) << "xfer += iprot->readListEnd();" << endl;
  3399. }
  3400. scope_down(out);
  3401. }
  3402. /**
  3403. * Generates code to deserialize a map
  3404. */
  3405. void t_cpp_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) {
  3406. string key = tmp("_key");
  3407. string val = tmp("_val");
  3408. t_field fkey(tmap->get_key_type(), key);
  3409. t_field fval(tmap->get_val_type(), val);
  3410. out << indent() << declare_field(&fkey) << endl;
  3411. generate_deserialize_field(out, &fkey);
  3412. indent(out) << declare_field(&fval, false, false, false, true) << " = " << prefix << "[" << key
  3413. << "];" << endl;
  3414. generate_deserialize_field(out, &fval);
  3415. }
  3416. void t_cpp_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) {
  3417. string elem = tmp("_elem");
  3418. t_field felem(tset->get_elem_type(), elem);
  3419. indent(out) << declare_field(&felem) << endl;
  3420. generate_deserialize_field(out, &felem);
  3421. indent(out) << prefix << ".insert(" << elem << ");" << endl;
  3422. }
  3423. void t_cpp_generator::generate_deserialize_list_element(ostream& out,
  3424. t_list* tlist,
  3425. string prefix,
  3426. bool use_push,
  3427. string index) {
  3428. if (use_push) {
  3429. string elem = tmp("_elem");
  3430. t_field felem(tlist->get_elem_type(), elem);
  3431. indent(out) << declare_field(&felem) << endl;
  3432. generate_deserialize_field(out, &felem);
  3433. indent(out) << prefix << ".push_back(" << elem << ");" << endl;
  3434. } else {
  3435. t_field felem(tlist->get_elem_type(), prefix + "[" + index + "]");
  3436. generate_deserialize_field(out, &felem);
  3437. }
  3438. }
  3439. /**
  3440. * Serializes a field of any type.
  3441. *
  3442. * @param tfield The field to serialize
  3443. * @param prefix Name to prepend to field name
  3444. */
  3445. void t_cpp_generator::generate_serialize_field(ostream& out,
  3446. t_field* tfield,
  3447. string prefix,
  3448. string suffix) {
  3449. t_type* type = get_true_type(tfield->get_type());
  3450. string name = prefix + tfield->get_name() + suffix;
  3451. // Do nothing for void types
  3452. if (type->is_void()) {
  3453. throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " + name;
  3454. }
  3455. if (type->is_struct() || type->is_xception()) {
  3456. generate_serialize_struct(out, (t_struct*)type, name, is_reference(tfield));
  3457. } else if (type->is_container()) {
  3458. generate_serialize_container(out, type, name);
  3459. } else if (type->is_base_type() || type->is_enum()) {
  3460. indent(out) << "xfer += oprot->";
  3461. if (type->is_base_type()) {
  3462. t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
  3463. switch (tbase) {
  3464. case t_base_type::TYPE_VOID:
  3465. throw "compiler error: cannot serialize void field in a struct: " + name;
  3466. break;
  3467. case t_base_type::TYPE_STRING:
  3468. if (type->is_binary()) {
  3469. out << "writeBinary(" << name << ");";
  3470. } else {
  3471. out << "writeString(" << name << ");";
  3472. }
  3473. break;
  3474. case t_base_type::TYPE_BOOL:
  3475. out << "writeBool(" << name << ");";
  3476. break;
  3477. case t_base_type::TYPE_I8:
  3478. out << "writeByte(" << name << ");";
  3479. break;
  3480. case t_base_type::TYPE_I16:
  3481. out << "writeI16(" << name << ");";
  3482. break;
  3483. case t_base_type::TYPE_I32:
  3484. out << "writeI32(" << name << ");";
  3485. break;
  3486. case t_base_type::TYPE_I64:
  3487. out << "writeI64(" << name << ");";
  3488. break;
  3489. case t_base_type::TYPE_DOUBLE:
  3490. out << "writeDouble(" << name << ");";
  3491. break;
  3492. default:
  3493. throw "compiler error: no C++ writer for base type " + t_base_type::t_base_name(tbase)
  3494. + name;
  3495. }
  3496. } else if (type->is_enum()) {
  3497. out << "writeI32((int32_t)" << name << ");";
  3498. }
  3499. out << endl;
  3500. } else {
  3501. printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s' TYPE '%s'\n",
  3502. name.c_str(),
  3503. type_name(type).c_str());
  3504. }
  3505. }
  3506. /**
  3507. * Serializes all the members of a struct.
  3508. *
  3509. * @param tstruct The struct to serialize
  3510. * @param prefix String prefix to attach to all fields
  3511. */
  3512. void t_cpp_generator::generate_serialize_struct(ostream& out,
  3513. t_struct* tstruct,
  3514. string prefix,
  3515. bool pointer) {
  3516. if (pointer) {
  3517. indent(out) << "if (" << prefix << ") {" << endl;
  3518. indent(out) << " xfer += " << prefix << "->write(oprot); " << endl;
  3519. indent(out) << "} else {"
  3520. << "oprot->writeStructBegin(\"" << tstruct->get_name() << "\"); " << endl;
  3521. indent(out) << " oprot->writeStructEnd();" << endl;
  3522. indent(out) << " oprot->writeFieldStop();" << endl;
  3523. indent(out) << "}" << endl;
  3524. } else {
  3525. indent(out) << "xfer += " << prefix << ".write(oprot);" << endl;
  3526. }
  3527. }
  3528. void t_cpp_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) {
  3529. scope_up(out);
  3530. if (ttype->is_map()) {
  3531. indent(out) << "xfer += oprot->writeMapBegin(" << type_to_enum(((t_map*)ttype)->get_key_type())
  3532. << ", " << type_to_enum(((t_map*)ttype)->get_val_type()) << ", "
  3533. << "static_cast<uint32_t>(" << prefix << ".size()));" << endl;
  3534. } else if (ttype->is_set()) {
  3535. indent(out) << "xfer += oprot->writeSetBegin(" << type_to_enum(((t_set*)ttype)->get_elem_type())
  3536. << ", "
  3537. << "static_cast<uint32_t>(" << prefix << ".size()));" << endl;
  3538. } else if (ttype->is_list()) {
  3539. indent(out) << "xfer += oprot->writeListBegin("
  3540. << type_to_enum(((t_list*)ttype)->get_elem_type()) << ", "
  3541. << "static_cast<uint32_t>(" << prefix << ".size()));" << endl;
  3542. }
  3543. string iter = tmp("_iter");
  3544. out << indent() << type_name(ttype) << "::const_iterator " << iter << ";" << endl << indent()
  3545. << "for (" << iter << " = " << prefix << ".begin(); " << iter << " != " << prefix
  3546. << ".end(); ++" << iter << ")" << endl;
  3547. scope_up(out);
  3548. if (ttype->is_map()) {
  3549. generate_serialize_map_element(out, (t_map*)ttype, iter);
  3550. } else if (ttype->is_set()) {
  3551. generate_serialize_set_element(out, (t_set*)ttype, iter);
  3552. } else if (ttype->is_list()) {
  3553. generate_serialize_list_element(out, (t_list*)ttype, iter);
  3554. }
  3555. scope_down(out);
  3556. if (ttype->is_map()) {
  3557. indent(out) << "xfer += oprot->writeMapEnd();" << endl;
  3558. } else if (ttype->is_set()) {
  3559. indent(out) << "xfer += oprot->writeSetEnd();" << endl;
  3560. } else if (ttype->is_list()) {
  3561. indent(out) << "xfer += oprot->writeListEnd();" << endl;
  3562. }
  3563. scope_down(out);
  3564. }
  3565. /**
  3566. * Serializes the members of a map.
  3567. *
  3568. */
  3569. void t_cpp_generator::generate_serialize_map_element(ostream& out, t_map* tmap, string iter) {
  3570. t_field kfield(tmap->get_key_type(), iter + "->first");
  3571. generate_serialize_field(out, &kfield, "");
  3572. t_field vfield(tmap->get_val_type(), iter + "->second");
  3573. generate_serialize_field(out, &vfield, "");
  3574. }
  3575. /**
  3576. * Serializes the members of a set.
  3577. */
  3578. void t_cpp_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) {
  3579. t_field efield(tset->get_elem_type(), "(*" + iter + ")");
  3580. generate_serialize_field(out, &efield, "");
  3581. }
  3582. /**
  3583. * Serializes the members of a list.
  3584. */
  3585. void t_cpp_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) {
  3586. t_field efield(tlist->get_elem_type(), "(*" + iter + ")");
  3587. generate_serialize_field(out, &efield, "");
  3588. }
  3589. /**
  3590. * Makes a :: prefix for a namespace
  3591. *
  3592. * @param ns The namespace, w/ periods in it
  3593. * @return Namespaces
  3594. */
  3595. string t_cpp_generator::namespace_prefix(string ns) {
  3596. // Always start with "::", to avoid possible name collisions with
  3597. // other names in one of the current namespaces.
  3598. //
  3599. // We also need a leading space, in case the name is used inside of a
  3600. // template parameter. "MyTemplate<::foo::Bar>" is not valid C++,
  3601. // since "<:" is an alternative token for "[".
  3602. string result = " ::";
  3603. if (ns.size() == 0) {
  3604. return result;
  3605. }
  3606. string::size_type loc;
  3607. while ((loc = ns.find(".")) != string::npos) {
  3608. result += ns.substr(0, loc);
  3609. result += "::";
  3610. ns = ns.substr(loc + 1);
  3611. }
  3612. if (ns.size() > 0) {
  3613. result += ns + "::";
  3614. }
  3615. return result;
  3616. }
  3617. /**
  3618. * Opens namespace.
  3619. *
  3620. * @param ns The namespace, w/ periods in it
  3621. * @return Namespaces
  3622. */
  3623. string t_cpp_generator::namespace_open(string ns) {
  3624. if (ns.size() == 0) {
  3625. return "";
  3626. }
  3627. string result = "";
  3628. string separator = "";
  3629. string::size_type loc;
  3630. while ((loc = ns.find(".")) != string::npos) {
  3631. result += separator;
  3632. result += "namespace ";
  3633. result += ns.substr(0, loc);
  3634. result += " {";
  3635. separator = " ";
  3636. ns = ns.substr(loc + 1);
  3637. }
  3638. if (ns.size() > 0) {
  3639. result += separator + "namespace " + ns + " {";
  3640. }
  3641. return result;
  3642. }
  3643. /**
  3644. * Closes namespace.
  3645. *
  3646. * @param ns The namespace, w/ periods in it
  3647. * @return Namespaces
  3648. */
  3649. string t_cpp_generator::namespace_close(string ns) {
  3650. if (ns.size() == 0) {
  3651. return "";
  3652. }
  3653. string result = "}";
  3654. string::size_type loc;
  3655. while ((loc = ns.find(".")) != string::npos) {
  3656. result += "}";
  3657. ns = ns.substr(loc + 1);
  3658. }
  3659. result += " // namespace";
  3660. return result;
  3661. }
  3662. /**
  3663. * Returns a C++ type name
  3664. *
  3665. * @param ttype The type
  3666. * @return String of the type name, i.e. std::set<type>
  3667. */
  3668. string t_cpp_generator::type_name(t_type* ttype, bool in_typedef, bool arg) {
  3669. if (ttype->is_base_type()) {
  3670. string bname = base_type_name(((t_base_type*)ttype)->get_base());
  3671. std::map<string, string>::iterator it = ttype->annotations_.find("cpp.type");
  3672. if (it != ttype->annotations_.end()) {
  3673. bname = it->second;
  3674. }
  3675. if (!arg) {
  3676. return bname;
  3677. }
  3678. if (((t_base_type*)ttype)->get_base() == t_base_type::TYPE_STRING) {
  3679. return "const " + bname + "&";
  3680. } else {
  3681. return "const " + bname;
  3682. }
  3683. }
  3684. // Check for a custom overloaded C++ name
  3685. if (ttype->is_container()) {
  3686. string cname;
  3687. t_container* tcontainer = (t_container*)ttype;
  3688. if (tcontainer->has_cpp_name()) {
  3689. cname = tcontainer->get_cpp_name();
  3690. } else if (ttype->is_map()) {
  3691. t_map* tmap = (t_map*)ttype;
  3692. cname = "std::map<" + type_name(tmap->get_key_type(), in_typedef) + ", "
  3693. + type_name(tmap->get_val_type(), in_typedef) + "> ";
  3694. } else if (ttype->is_set()) {
  3695. t_set* tset = (t_set*)ttype;
  3696. cname = "std::set<" + type_name(tset->get_elem_type(), in_typedef) + "> ";
  3697. } else if (ttype->is_list()) {
  3698. t_list* tlist = (t_list*)ttype;
  3699. cname = "std::vector<" + type_name(tlist->get_elem_type(), in_typedef) + "> ";
  3700. }
  3701. if (arg) {
  3702. return "const " + cname + "&";
  3703. } else {
  3704. return cname;
  3705. }
  3706. }
  3707. string class_prefix;
  3708. if (in_typedef && (ttype->is_struct() || ttype->is_xception())) {
  3709. class_prefix = "class ";
  3710. }
  3711. // Check if it needs to be namespaced
  3712. string pname;
  3713. t_program* program = ttype->get_program();
  3714. if (program != NULL && program != program_) {
  3715. pname = class_prefix + namespace_prefix(program->get_namespace("cpp")) + ttype->get_name();
  3716. } else {
  3717. pname = class_prefix + ttype->get_name();
  3718. }
  3719. if (ttype->is_enum() && !gen_pure_enums_) {
  3720. pname += "::type";
  3721. }
  3722. if (arg) {
  3723. if (is_complex_type(ttype)) {
  3724. return "const " + pname + "&";
  3725. } else {
  3726. return "const " + pname;
  3727. }
  3728. } else {
  3729. return pname;
  3730. }
  3731. }
  3732. /**
  3733. * Returns the C++ type that corresponds to the thrift type.
  3734. *
  3735. * @param tbase The base type
  3736. * @return Explicit C++ type, i.e. "int32_t"
  3737. */
  3738. string t_cpp_generator::base_type_name(t_base_type::t_base tbase) {
  3739. switch (tbase) {
  3740. case t_base_type::TYPE_VOID:
  3741. return "void";
  3742. case t_base_type::TYPE_STRING:
  3743. return "std::string";
  3744. case t_base_type::TYPE_BOOL:
  3745. return "bool";
  3746. case t_base_type::TYPE_I8:
  3747. return "int8_t";
  3748. case t_base_type::TYPE_I16:
  3749. return "int16_t";
  3750. case t_base_type::TYPE_I32:
  3751. return "int32_t";
  3752. case t_base_type::TYPE_I64:
  3753. return "int64_t";
  3754. case t_base_type::TYPE_DOUBLE:
  3755. return "double";
  3756. default:
  3757. throw "compiler error: no C++ base type name for base type " + t_base_type::t_base_name(tbase);
  3758. }
  3759. }
  3760. /**
  3761. * Declares a field, which may include initialization as necessary.
  3762. *
  3763. * @param ttype The type
  3764. * @return Field declaration, i.e. int x = 0;
  3765. */
  3766. string t_cpp_generator::declare_field(t_field* tfield,
  3767. bool init,
  3768. bool pointer,
  3769. bool constant,
  3770. bool reference) {
  3771. // TODO(mcslee): do we ever need to initialize the field?
  3772. string result = "";
  3773. if (constant) {
  3774. result += "const ";
  3775. }
  3776. result += type_name(tfield->get_type());
  3777. if (is_reference(tfield)) {
  3778. result = "::apache::thrift::stdcxx::shared_ptr<" + result + ">";
  3779. }
  3780. if (pointer) {
  3781. result += "*";
  3782. }
  3783. if (reference) {
  3784. result += "&";
  3785. }
  3786. result += " " + tfield->get_name();
  3787. if (init) {
  3788. t_type* type = get_true_type(tfield->get_type());
  3789. if (type->is_base_type()) {
  3790. t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
  3791. switch (tbase) {
  3792. case t_base_type::TYPE_VOID:
  3793. case t_base_type::TYPE_STRING:
  3794. break;
  3795. case t_base_type::TYPE_BOOL:
  3796. result += " = false";
  3797. break;
  3798. case t_base_type::TYPE_I8:
  3799. case t_base_type::TYPE_I16:
  3800. case t_base_type::TYPE_I32:
  3801. case t_base_type::TYPE_I64:
  3802. result += " = 0";
  3803. break;
  3804. case t_base_type::TYPE_DOUBLE:
  3805. result += " = (double)0";
  3806. break;
  3807. default:
  3808. throw "compiler error: no C++ initializer for base type " + t_base_type::t_base_name(tbase);
  3809. }
  3810. } else if (type->is_enum()) {
  3811. result += " = (" + type_name(type) + ")0";
  3812. }
  3813. }
  3814. if (!reference) {
  3815. result += ";";
  3816. }
  3817. return result;
  3818. }
  3819. /**
  3820. * Renders a function signature of the form 'type name(args)'
  3821. *
  3822. * @param tfunction Function definition
  3823. * @return String of rendered function definition
  3824. */
  3825. string t_cpp_generator::function_signature(t_function* tfunction,
  3826. string style,
  3827. string prefix,
  3828. bool name_params) {
  3829. t_type* ttype = tfunction->get_returntype();
  3830. t_struct* arglist = tfunction->get_arglist();
  3831. bool has_xceptions = !tfunction->get_xceptions()->get_members().empty();
  3832. if (style == "") {
  3833. if (is_complex_type(ttype)) {
  3834. return "void " + prefix + tfunction->get_name() + "(" + type_name(ttype)
  3835. + (name_params ? "& _return" : "& /* _return */")
  3836. + argument_list(arglist, name_params, true) + ")";
  3837. } else {
  3838. return type_name(ttype) + " " + prefix + tfunction->get_name() + "("
  3839. + argument_list(arglist, name_params) + ")";
  3840. }
  3841. } else if (style.substr(0, 3) == "Cob") {
  3842. string cob_type;
  3843. string exn_cob;
  3844. if (style == "CobCl") {
  3845. cob_type = "(" + service_name_ + "CobClient";
  3846. if (gen_templates_) {
  3847. cob_type += "T<Protocol_>";
  3848. }
  3849. cob_type += "* client)";
  3850. } else if (style == "CobSv") {
  3851. cob_type = (ttype->is_void() ? "()" : ("(" + type_name(ttype) + " const& _return)"));
  3852. if (has_xceptions) {
  3853. exn_cob
  3854. = ", ::apache::thrift::stdcxx::function<void(::apache::thrift::TDelayedException* _throw)> /* exn_cob */";
  3855. }
  3856. } else {
  3857. throw "UNKNOWN STYLE";
  3858. }
  3859. return "void " + prefix + tfunction->get_name() + "(::apache::thrift::stdcxx::function<void" + cob_type + "> cob"
  3860. + exn_cob + argument_list(arglist, name_params, true) + ")";
  3861. } else {
  3862. throw "UNKNOWN STYLE";
  3863. }
  3864. }
  3865. /**
  3866. * Renders a field list
  3867. *
  3868. * @param tstruct The struct definition
  3869. * @return Comma sepearated list of all field names in that struct
  3870. */
  3871. string t_cpp_generator::argument_list(t_struct* tstruct, bool name_params, bool start_comma) {
  3872. string result = "";
  3873. const vector<t_field*>& fields = tstruct->get_members();
  3874. vector<t_field*>::const_iterator f_iter;
  3875. bool first = !start_comma;
  3876. for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
  3877. if (first) {
  3878. first = false;
  3879. } else {
  3880. result += ", ";
  3881. }
  3882. result += type_name((*f_iter)->get_type(), false, true) + " "
  3883. + (name_params ? (*f_iter)->get_name() : "/* " + (*f_iter)->get_name() + " */");
  3884. }
  3885. return result;
  3886. }
  3887. /**
  3888. * Converts the parse type to a C++ enum string for the given type.
  3889. *
  3890. * @param type Thrift Type
  3891. * @return String of C++ code to definition of that type constant
  3892. */
  3893. string t_cpp_generator::type_to_enum(t_type* type) {
  3894. type = get_true_type(type);
  3895. if (type->is_base_type()) {
  3896. t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
  3897. switch (tbase) {
  3898. case t_base_type::TYPE_VOID:
  3899. throw "NO T_VOID CONSTRUCT";
  3900. case t_base_type::TYPE_STRING:
  3901. return "::apache::thrift::protocol::T_STRING";
  3902. case t_base_type::TYPE_BOOL:
  3903. return "::apache::thrift::protocol::T_BOOL";
  3904. case t_base_type::TYPE_I8:
  3905. return "::apache::thrift::protocol::T_BYTE";
  3906. case t_base_type::TYPE_I16:
  3907. return "::apache::thrift::protocol::T_I16";
  3908. case t_base_type::TYPE_I32:
  3909. return "::apache::thrift::protocol::T_I32";
  3910. case t_base_type::TYPE_I64:
  3911. return "::apache::thrift::protocol::T_I64";
  3912. case t_base_type::TYPE_DOUBLE:
  3913. return "::apache::thrift::protocol::T_DOUBLE";
  3914. }
  3915. } else if (type->is_enum()) {
  3916. return "::apache::thrift::protocol::T_I32";
  3917. } else if (type->is_struct()) {
  3918. return "::apache::thrift::protocol::T_STRUCT";
  3919. } else if (type->is_xception()) {
  3920. return "::apache::thrift::protocol::T_STRUCT";
  3921. } else if (type->is_map()) {
  3922. return "::apache::thrift::protocol::T_MAP";
  3923. } else if (type->is_set()) {
  3924. return "::apache::thrift::protocol::T_SET";
  3925. } else if (type->is_list()) {
  3926. return "::apache::thrift::protocol::T_LIST";
  3927. }
  3928. throw "INVALID TYPE IN type_to_enum: " + type->get_name();
  3929. }
  3930. string t_cpp_generator::get_include_prefix(const t_program& program) const {
  3931. string include_prefix = program.get_include_prefix();
  3932. if (!use_include_prefix_ || (include_prefix.size() > 0 && include_prefix[0] == '/')) {
  3933. // if flag is turned off or this is absolute path, return empty prefix
  3934. return "";
  3935. }
  3936. string::size_type last_slash = string::npos;
  3937. if ((last_slash = include_prefix.rfind("/")) != string::npos) {
  3938. return include_prefix.substr(0, last_slash)
  3939. + (get_program()->is_out_path_absolute() ? "/" : "/" + out_dir_base_ + "/");
  3940. }
  3941. return "";
  3942. }
  3943. THRIFT_REGISTER_GENERATOR(
  3944. cpp,
  3945. "C++",
  3946. " cob_style: Generate \"Continuation OBject\"-style classes.\n"
  3947. " no_client_completion:\n"
  3948. " Omit calls to completion__() in CobClient class.\n"
  3949. " no_default_operators:\n"
  3950. " Omits generation of default operators ==, != and <\n"
  3951. " templates: Generate templatized reader/writer methods.\n"
  3952. " pure_enums: Generate pure enums instead of wrapper classes.\n"
  3953. " include_prefix: Use full include paths in generated files.\n"
  3954. " moveable_types: Generate move constructors and assignment operators.\n"
  3955. " no_ostream_operators:\n"
  3956. " Omit generation of ostream definitions.\n"
  3957. " no_skeleton: Omits generation of skeleton.\n")