hqlcppds.cpp 192 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jliball.hpp"
  14. #include "hql.hpp"
  15. #include "platform.h"
  16. #include "jlib.hpp"
  17. #include "jmisc.hpp"
  18. #include "jstream.ipp"
  19. #include "jdebug.hpp"
  20. #include "hql.hpp"
  21. #include "hqlthql.hpp"
  22. #include "hqlhtcpp.ipp"
  23. #include "hqlttcpp.ipp"
  24. #include "hqlutil.hpp"
  25. #include "hqlthql.hpp"
  26. #include "hqlpmap.hpp"
  27. #include "hqlattr.hpp"
  28. #include "hqlwcpp.hpp"
  29. #include "hqlcpputil.hpp"
  30. #include "hqltcppc.ipp"
  31. #include "hqlopt.hpp"
  32. #include "hqlfold.hpp"
  33. #include "hqlcerrors.hpp"
  34. #include "hqlcatom.hpp"
  35. #include "hqlresource.hpp"
  36. #include "hqlregex.ipp"
  37. #include "hqlsource.ipp"
  38. #include "hqlcse.ipp"
  39. #include "hqlgraph.ipp"
  40. #include "hqlccommon.hpp"
  41. #include "hqliter.ipp"
  42. #include "hqlinline.hpp"
  43. #include "hqlusage.hpp"
  44. #include "hqlcppds.hpp"
  45. #define MAX_FIXED_SIZE_RAW 1024
  46. #define INLINE_TABLE_EXPAND_LIMIT 4
  47. void addGraphIdAttribute(ActivityInstance * instance, BuildCtx & ctx, IHqlExpression * graphId)
  48. {
  49. SubGraphInfo * match = matchActiveGraph(ctx, graphId);
  50. assertex(match);
  51. instance->addAttributeInt("_graphId", match->graphId);
  52. }
  53. //===========================================================================
  54. void HqlCppTranslator::doBuildRowIfBranch(BuildCtx & initctx, BuildCtx & ctx, BoundRow * targetRow, IHqlExpression * branchExpr)
  55. {
  56. IHqlExpression * targetRowExpr = targetRow->queryBound();
  57. Owned<IReferenceSelector> rowSelector = buildNewRow(ctx, branchExpr);
  58. Owned<BoundRow> boundRow = rowSelector->getRow(ctx);
  59. OwnedHqlExpr rowExpr = getPointer(boundRow->queryBound());
  60. OwnedHqlExpr castRow = createValue(no_implicitcast, targetRowExpr->getType(), LINK(rowExpr));
  61. ctx.addAssign(targetRowExpr, castRow);
  62. if (rowSelector->isConditional())
  63. targetRow->setConditional(true);
  64. }
  65. IReferenceSelector * HqlCppTranslator::doBuildRowIf(BuildCtx & ctx, IHqlExpression * expr)
  66. {
  67. OwnedHqlExpr foldedCond = foldHqlExpression(expr->queryChild(0));
  68. if (foldedCond->queryValue())
  69. {
  70. unsigned branch = (foldedCond->queryValue()->getBoolValue()) ? 1 : 2;
  71. return buildNewRow(ctx, expr->queryChild(branch));
  72. }
  73. IHqlExpression * trueBranch = expr->queryChild(1);
  74. IHqlExpression * falseBranch = expr->queryChild(2);
  75. //Ideally should have a constant modifier on the following row...
  76. Owned<ITypeInfo> rowType = makeReferenceModifier(expr->getType());
  77. OwnedHqlExpr rowExpr = ctx.getTempDeclare(rowType, NULL);
  78. Owned<BoundRow> row = createBoundRow(expr->queryBody(), rowExpr);
  79. //MORE: Need casts because cursor may be (probably are) constant, but temporary isn't
  80. //should find out by looking at the a const modifier on the cursor.
  81. BuildCtx condctx(ctx);
  82. IHqlStmt * cond = buildFilterViaExpr(condctx, foldedCond);
  83. //Mark the context as conditional after the filter test, so any temporaries from the filter aren't affected.
  84. condctx.associateExpr(queryConditionalRowMarker(), rowExpr);
  85. doBuildRowIfBranch(ctx, condctx, row, trueBranch);
  86. condctx.selectElse(cond);
  87. condctx.associateExpr(queryConditionalRowMarker(), rowExpr);
  88. doBuildRowIfBranch(ctx, condctx, row, falseBranch);
  89. ctx.associate(*row);
  90. return createReferenceSelector(row);
  91. }
  92. IReferenceSelector * HqlCppTranslator::doBuildRowDeserializeRow(BuildCtx & ctx, IHqlExpression * expr)
  93. {
  94. IHqlExpression * srcRow = expr->queryChild(0);
  95. IHqlExpression * record = expr->queryRecord();
  96. IAtom * serializeForm = expr->queryChild(2)->queryName();
  97. Owned<BoundRow> tempRow = declareLinkedRow(ctx, expr, false);
  98. CHqlBoundTarget target;
  99. target.expr.set(tempRow->queryBound());
  100. HqlExprArray args;
  101. args.append(*createSerializer(ctx, record, serializeForm, deserializerAtom));
  102. args.append(*LINK(srcRow));
  103. Owned<ITypeInfo> resultType = makeReferenceModifier(makeAttributeModifier(makeRowType(record->getType()), getLinkCountedAttr()));
  104. OwnedHqlExpr call = bindFunctionCall(rtlDeserializeRowId, args, resultType);
  105. buildExprAssign(ctx, target, call);
  106. ctx.associate(*tempRow);
  107. return createReferenceSelector(tempRow);
  108. }
  109. void HqlCppTranslator::buildConstRow(IHqlExpression * record, IHqlExpression * rowData, CHqlBoundExpr & bound)
  110. {
  111. OwnedHqlExpr marker = createAttribute(rowAtom, LINK(record), LINK(rowData));
  112. BuildCtx declareCtx(*code, literalAtom);
  113. if (declareCtx.getMatchExpr(marker, bound))
  114. return;
  115. //MORE: This probably needs to go in the header as well...
  116. Owned<ITypeInfo> rowType = makeConstantModifier(makeRowType(record->getType()));
  117. if (options.canLinkConstantRows)
  118. rowType.setown(setLinkCountedAttr(rowType, true));
  119. StringBuffer rowName;
  120. getUniqueId(rowName.append("r"));
  121. //Generate two variables to cope with the different ways the data is interpreted.
  122. //Would prefer it to be cleaner... row value would need an associated size
  123. unsigned dataSize = rowData->queryType()->getSize();
  124. OwnedITypeInfo declareType;
  125. OwnedHqlExpr initializer;
  126. if (options.staticRowsUseStringInitializer)
  127. {
  128. //Generates smaller code (and probably more efficient representation in the c++ compiler
  129. //const byte[5+1] = "Hello"; need an extra byte for the implicit \0
  130. declareType.setown(makeDataType(dataSize+1));
  131. initializer.set(rowData);
  132. }
  133. else
  134. {
  135. //Following is strictly correct, but much larger.
  136. //const byte[5] = { 'H','e','l','l','o' };
  137. declareType.set(rowData->queryType());
  138. initializer.setown(createValue(no_create_initializer, rowData->getType(), LINK(rowData)));
  139. }
  140. //MORE: Currently these are marked as const rows, but not generated as such
  141. OwnedHqlExpr boundDeclare = createVariable(rowName, makeConstantModifier(LINK(declareType)));
  142. OwnedHqlExpr boundRow = createVariable(rowName, LINK(rowType));
  143. declareCtx.addDeclare(boundDeclare, initializer);
  144. if (options.spanMultipleCpp)
  145. {
  146. BuildCtx protoctx(*code, mainprototypesAtom);
  147. protoctx.addDeclareExternal(boundDeclare);
  148. }
  149. bound.length.setown(getSizetConstant(dataSize));
  150. bound.expr.set(boundRow);
  151. declareCtx.associateExpr(marker, bound);
  152. }
  153. bool HqlCppTranslator::doBuildRowConstantTransform(IHqlExpression * transform, CHqlBoundExpr & bound)
  154. {
  155. if (!transform->isConstant() || !options.generateStaticInlineTables)
  156. return false;
  157. OwnedHqlExpr constRow = createConstantRowExpr(transform);
  158. if (!constRow || !canGenerateStringInline(constRow->queryType()->getSize()))
  159. return false;
  160. buildConstRow(transform->queryRecord(), constRow, bound);
  161. return true;
  162. }
  163. IReferenceSelector * HqlCppTranslator::doBuildRowCreateRow(BuildCtx & ctx, IHqlExpression * expr)
  164. {
  165. CHqlBoundExpr bound;
  166. if (!doBuildRowConstantTransform(expr->queryChild(0), bound))
  167. return doBuildRowViaTemp(ctx, expr);
  168. BoundRow * row = bindConstantRow(ctx, expr, bound);
  169. return createReferenceSelector(row);
  170. }
  171. BoundRow * HqlCppTranslator::bindConstantRow(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & bound)
  172. {
  173. BoundRow * row = bindRow(ctx, expr, bound.expr);
  174. //MORE: This should be done more cleanly
  175. OwnedHqlExpr sizeOfRow = createSizeof(row->querySelector());
  176. ctx.associateExpr(sizeOfRow, bound.length);
  177. return row;
  178. }
  179. bool HqlCppTranslator::doBuildRowConstantNull(IHqlExpression * expr, CHqlBoundExpr & bound)
  180. {
  181. if (!options.generateStaticInlineTables)
  182. return false;
  183. IHqlExpression * record = expr->queryRecord();
  184. OwnedHqlExpr constRow = createConstantNullRowExpr(record);
  185. if (!constRow)
  186. return false;
  187. buildConstRow(record, constRow, bound);
  188. return true;
  189. }
  190. IReferenceSelector * HqlCppTranslator::doBuildRowNull(BuildCtx & ctx, IHqlExpression * expr)
  191. {
  192. CHqlBoundExpr bound;
  193. if (!doBuildRowConstantNull(expr, bound))
  194. return doBuildRowViaTemp(ctx, expr);
  195. BoundRow * row = bindRow(ctx, expr, bound.expr);
  196. return createReferenceSelector(row);
  197. }
  198. IReferenceSelector * HqlCppTranslator::doBuildRowViaTemp(BuildCtx & ctx, IHqlExpression * expr)
  199. {
  200. HqlExprAssociation * match;
  201. if (expr->isDataset())
  202. match = ctx.queryAssociation(expr->queryNormalizedSelector(), AssocCursor, NULL);
  203. else
  204. match = ctx.queryAssociation(expr, AssocRow, NULL);
  205. if (match)
  206. {
  207. BoundRow * row = (BoundRow *)match;
  208. return createReferenceSelector(row, expr);
  209. }
  210. Owned<BoundRow> tempRow = declareTempRow(ctx, ctx, expr);
  211. buildRowAssign(ctx, tempRow, expr);
  212. ctx.associate(*tempRow);
  213. return createReferenceSelector(tempRow);
  214. }
  215. void HqlCppTranslator::buildDefaultRow(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & bound)
  216. {
  217. OwnedHqlExpr clearExpr = createRow(no_null, LINK(expr->queryRecord()), createAttribute(clearAtom));
  218. BoundRow * matchedRow = (BoundRow *)ctx.queryAssociation(clearExpr, AssocRow, NULL);
  219. if (!matchedRow)
  220. {
  221. if (doBuildRowConstantNull(expr, bound))
  222. {
  223. bindRow(ctx, clearExpr, bound.expr);
  224. }
  225. else
  226. {
  227. BuildCtx * declarectx = &ctx;
  228. BuildCtx * callCtx = &ctx;
  229. getInvariantMemberContext(ctx, &declarectx, &callCtx, true, false);
  230. Owned<BoundRow> tempRow = declareTempRow(*declarectx, *callCtx, clearExpr);
  231. Owned<BoundRow> rowBuilder = createRowBuilder(*callCtx, tempRow);
  232. OwnedHqlExpr size = createVariable(LINK(sizetType));
  233. OwnedHqlExpr clearCall = createClearRowCall(*callCtx, rowBuilder);
  234. callCtx->addDeclare(size, clearCall);
  235. OwnedHqlExpr sizeOfRow = createSizeof(rowBuilder->querySelector());
  236. callCtx->associateExpr(sizeOfRow, size);
  237. finalizeTempRow(*callCtx, tempRow, rowBuilder);
  238. declarectx->associate(*tempRow);
  239. bound.expr.set(tempRow->queryBound());
  240. }
  241. }
  242. else
  243. bound.expr.set(matchedRow->queryBound());
  244. //yuk yuk, hack. If called from a const context then need to make the reference unconst.
  245. //The real fix is to implement real const tracking throughout the code generator, but that is far from trivial.
  246. //rkc39.hql is an example...
  247. if (ctx.queryMatchExpr(constantMemberMarkerExpr))
  248. bound.expr.setown(createValue(no_cast, makeReferenceModifier(bound.expr->getType()), getPointer(bound.expr)));
  249. }
  250. void HqlCppTranslator::buildNullRow(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & bound)
  251. {
  252. bound.expr.setown(createValue(no_nullptr, makeRowReferenceType(expr)));
  253. }
  254. IReferenceSelector * HqlCppTranslator::doBuildRowFromXML(BuildCtx & ctx, IHqlExpression * expr)
  255. {
  256. // assertex(supportsLinkCountedRows);
  257. Owned<ITypeInfo> overrideType = setLinkCountedAttr(expr->queryType(), true);
  258. Owned<ITypeInfo> utf8Type = makeUtf8Type(UNKNOWN_LENGTH, NULL);
  259. IHqlExpression * record = expr->queryRecord();
  260. OwnedHqlExpr ds = createDataset(no_anon, LINK(record));
  261. StringBuffer xmlInstanceName, xmlFactoryName, s;
  262. bool usesContents = false;
  263. getUniqueId(xmlInstanceName.append("xml"));
  264. buildXmlReadTransform(ds, xmlFactoryName, usesContents);
  265. OwnedHqlExpr curActivityId = getCurrentActivityId(ctx);
  266. //MORE: This should be generalised so that any invariant class creation can be handled by the same code.
  267. BuildCtx * declareCtx = &ctx;
  268. BuildCtx * initCtx = &ctx;
  269. if (!insideOnCreate(ctx) && getInvariantMemberContext(ctx, &declareCtx, &initCtx, false, false))
  270. {
  271. declareCtx->addQuoted(s.clear().append("Owned<IXmlToRowTransformer> ").append(xmlInstanceName).append(";"));
  272. s.clear().append(xmlInstanceName).append(".setown(").append(xmlFactoryName).append("(ctx,");
  273. generateExprCpp(s, curActivityId).append("));");
  274. initCtx->addQuoted(s);
  275. }
  276. else
  277. {
  278. s.append("Owned<IXmlToRowTransformer> ").append(xmlInstanceName).append(" = ").append(xmlFactoryName).append("(ctx,");
  279. generateExprCpp(s, curActivityId).append(");");
  280. ctx.addQuoted(s);
  281. }
  282. HqlExprArray args;
  283. args.append(*ensureExprType(expr->queryChild(1), utf8Type));
  284. args.append(*createQuoted(xmlInstanceName, makeBoolType()));
  285. args.append(*createConstant(expr->hasAttribute(trimAtom)));
  286. OwnedHqlExpr function = bindFunctionCall(createRowFromXmlId, args, overrideType);
  287. CHqlBoundExpr bound;
  288. buildExpr(ctx, function, bound);
  289. Owned<ITypeInfo> rowType = makeReferenceModifier(LINK(overrideType));
  290. OwnedHqlExpr rowExpr = ctx.getTempDeclare(rowType, NULL);
  291. Owned<BoundRow> row = createBoundRow(expr, rowExpr);
  292. ctx.associate(*row); // associate here because it is compared inside the loop
  293. OwnedHqlExpr defaultRowPtr = getPointer(bound.expr);
  294. ctx.addAssign(rowExpr, defaultRowPtr);
  295. return createReferenceSelector(row);
  296. }
  297. //NB: If this is a dataset operation, this function assumes that any parent datasets are already in scope
  298. // i.e. processed in buildDatasetAssign()
  299. // the one exception is aggregate because it needs to treat its input differently.
  300. IReferenceSelector * HqlCppTranslator::buildNewOrActiveRow(BuildCtx & ctx, IHqlExpression * expr, bool isNew)
  301. {
  302. if (isNew)
  303. return buildNewRow(ctx, expr);
  304. else
  305. return buildActiveRow(ctx, expr);
  306. }
  307. IReferenceSelector * HqlCppTranslator::buildNewRow(BuildCtx & ctx, IHqlExpression * expr)
  308. {
  309. assertex(!expr->isDataset());
  310. BoundRow * match = static_cast<BoundRow *>(ctx.queryAssociation(expr, AssocRow, NULL));
  311. if (match)
  312. return createReferenceSelector(match, expr);
  313. BoundRow * row = NULL;
  314. node_operator op = expr->getOperator();
  315. switch (op)
  316. {
  317. case no_activerow:
  318. return buildActiveRow(ctx, expr->queryChild(0));
  319. case no_if:
  320. return doBuildRowIf(ctx, expr);
  321. case no_id2blob:
  322. return doBuildRowIdToBlob(ctx, expr, true);
  323. case no_index:
  324. case no_selectnth:
  325. return buildDatasetIndex(ctx, expr);
  326. case no_selectmap:
  327. return buildDatasetSelectMap(ctx, expr);
  328. case no_left:
  329. case no_right:
  330. case no_self:
  331. case no_top:
  332. case no_activetable:
  333. return buildActiveRow(ctx, expr);
  334. case no_fromxml:
  335. return doBuildRowFromXML(ctx, expr);
  336. case no_serialize:
  337. {
  338. IHqlExpression * deserialized = expr->queryChild(0);
  339. IAtom * serializeForm = expr->queryChild(1)->queryName();
  340. if (isDummySerializeDeserialize(expr))
  341. return buildNewRow(ctx, deserialized->queryChild(0));
  342. else if (!typeRequiresDeserialization(deserialized->queryType(), serializeForm))
  343. return buildNewRow(ctx, deserialized);
  344. else
  345. return doBuildRowViaTemp(ctx, expr);
  346. }
  347. case no_deserialize:
  348. {
  349. IHqlExpression * serialized = expr->queryChild(0);
  350. IAtom * serializeForm = expr->queryChild(2)->queryName();
  351. if (isDummySerializeDeserialize(expr))
  352. return buildNewRow(ctx, serialized->queryChild(0));
  353. else if (!typeRequiresDeserialization(expr->queryType(), serializeForm))
  354. return buildNewRow(ctx, serialized);
  355. else
  356. return doBuildRowDeserializeRow(ctx, expr);
  357. }
  358. case no_deref:
  359. {
  360. //Untested
  361. CHqlBoundExpr bound;
  362. buildExpr(ctx, expr, bound);
  363. row = bindRow(ctx, expr, bound.expr);
  364. break;
  365. }
  366. case no_createrow:
  367. return doBuildRowCreateRow(ctx, expr);
  368. case no_newusertable:
  369. case no_hqlproject:
  370. case no_temprow:
  371. case no_projectrow:
  372. return doBuildRowViaTemp(ctx, expr);
  373. case no_null:
  374. return doBuildRowNull(ctx, expr);
  375. case no_typetransfer:
  376. {
  377. CHqlBoundExpr bound;
  378. IHqlExpression * value = expr->queryChild(1);
  379. if (value->isDatarow())
  380. buildAddress(ctx, value, bound);
  381. else
  382. buildExpr(ctx, value, bound);
  383. OwnedHqlExpr cursorExpr = createValue(no_implicitcast, makeReferenceModifier(expr->getType()), LINK(bound.expr));
  384. row = bindRow(ctx, expr, cursorExpr);
  385. break;
  386. }
  387. case no_getresult:
  388. {
  389. IAtom * serializeForm = diskAtom; // What if we start using internal in the engines?
  390. IHqlExpression * seqAttr = expr->queryAttribute(sequenceAtom);
  391. IHqlExpression * nameAttr = expr->queryAttribute(namedAtom);
  392. IHqlExpression * record = expr->queryRecord();
  393. OwnedHqlExpr serializedRecord = getSerializedForm(record, serializeForm);
  394. OwnedHqlExpr temp = createDatasetF(no_getresult, LINK(serializedRecord), LINK(seqAttr), LINK(nameAttr), NULL);
  395. OwnedHqlExpr row = createRow(no_selectnth, LINK(temp), createComma(getSizetConstant(1), createAttribute(noBoundCheckAtom)));
  396. row.setown(ensureDeserialized(row, expr->queryType(), serializeForm));
  397. return buildNewRow(ctx, row);
  398. }
  399. case no_matchattr:
  400. return doBuildRowMatchAttr(ctx, expr);
  401. case no_matchrow:
  402. return doBuildRowMatchRow(ctx, expr, true);
  403. case no_getgraphresult:
  404. case no_call:
  405. case no_externalcall:
  406. case no_alias:
  407. case no_translated:
  408. case no_libraryinput:
  409. {
  410. CHqlBoundExpr bound;
  411. buildExpr(ctx, expr, bound);
  412. Owned<ITypeInfo> rawType = removeModifier(expr->queryType(), typemod_ref);
  413. OwnedHqlExpr cursorExpr = createValue(no_implicitcast, makeReferenceModifier(LINK(rawType)), LINK(bound.expr));
  414. row = bindRow(ctx, expr, cursorExpr);
  415. if (bound.length)
  416. {
  417. OwnedHqlExpr sizeOfRow = createSizeof(row->querySelector());
  418. ctx.associateExpr(sizeOfRow, bound.length);
  419. }
  420. //We could associate the original expression to allow better cse for child datasets in transforms, but it doesn't actually improve any examples
  421. //IHqlExpression * original = queryAttributeChild(expr, _original_Atom, 0);
  422. //if (original)
  423. // bindRow(ctx, original, cursorExpr)->setResultAlias();
  424. break;//return createReferenceSelector(cursor);
  425. }
  426. case no_comma:
  427. case no_compound:
  428. buildStmt(ctx, expr->queryChild(0));
  429. return buildNewRow(ctx, expr->queryChild(1));
  430. case no_select:
  431. {
  432. #ifdef _DEBUG
  433. IHqlExpression * field = expr->queryChild(1);
  434. #endif
  435. Owned<IReferenceSelector> selector;
  436. if (isNewSelector(expr))
  437. selector.setown(buildNewRow(ctx, expr->queryChild(0)));
  438. else
  439. selector.setown(buildActiveRow(ctx, expr->queryChild(0)));
  440. return selector->select(ctx, expr);
  441. }
  442. //If called because known to be a single row.
  443. case no_datasetfromrow:
  444. case no_nofold:
  445. case no_nohoist:
  446. case no_section:
  447. case no_sectioninput:
  448. return buildNewRow(ctx, expr->queryChild(0));
  449. case no_skip:
  450. {
  451. buildStmt(ctx, expr);
  452. OwnedHqlExpr null = createNullExpr(expr);
  453. return buildNewRow(ctx, null);
  454. }
  455. case no_alias_scope:
  456. {
  457. expandAliasScope(ctx, expr);
  458. return buildNewRow(ctx, expr->queryChild(0));
  459. }
  460. case no_split:
  461. throwUnexpected();
  462. //not at all sure about this.....
  463. return buildNewRow(ctx, expr->queryChild(0));
  464. default:
  465. {
  466. HqlExprAssociation * match;
  467. if (expr->isDataset())
  468. match = ctx.queryAssociation(expr->queryNormalizedSelector(), AssocCursor, NULL);
  469. else
  470. match = ctx.queryAssociation(expr, AssocRow, NULL);
  471. if (match)
  472. {
  473. BoundRow * row = (BoundRow *)match;
  474. IReferenceSelector * alias = row->queryAlias();
  475. if (alias)
  476. return LINK(alias);
  477. return createReferenceSelector(row, expr);
  478. }
  479. UNIMPLEMENTED_XY("row", getOpString(expr->getOperator()));
  480. }
  481. }
  482. assertex(row);
  483. return createReferenceSelector(row);
  484. }
  485. IReferenceSelector * HqlCppTranslator::buildActiveRow(BuildCtx & ctx, IHqlExpression * expr)
  486. {
  487. node_operator op = expr->getOperator();
  488. switch (op)
  489. {
  490. case no_left:
  491. case no_right:
  492. case no_self:
  493. case no_top:
  494. case no_activetable:
  495. case no_selfref: // shouldn't ever occur...
  496. //All selectors should be listed here...
  497. break;
  498. case no_activerow:
  499. return buildActiveRow(ctx, expr->queryChild(0));
  500. default:
  501. if (!expr->isDataset() && !expr->isDictionary())
  502. return buildNewRow(ctx, expr);
  503. break;
  504. }
  505. HqlExprAssociation * match = ctx.queryAssociation(expr->queryNormalizedSelector(), AssocCursor, NULL);
  506. if (match)
  507. {
  508. BoundRow * row = (BoundRow *)match;
  509. IReferenceSelector * alias = row->queryAlias();
  510. if (alias)
  511. return LINK(alias);
  512. return createReferenceSelector(row, expr);
  513. }
  514. switch (op)
  515. {
  516. case no_select:
  517. {
  518. #ifdef _DEBUG
  519. IHqlExpression * field = expr->queryChild(1);
  520. #endif
  521. Owned<IReferenceSelector> selector = buildNewOrActiveRow(ctx, expr->queryChild(0), isNewSelector(expr));
  522. return selector->select(ctx, expr);
  523. }
  524. case no_id2blob:
  525. return doBuildRowIdToBlob(ctx, expr, false);
  526. }
  527. StringBuffer tablename;
  528. getExprIdentifier(tablename, expr);
  529. traceExpression("Dataset not found", expr);
  530. RowAssociationIterator iter(ctx);
  531. ForEach(iter)
  532. {
  533. BoundRow & cur = iter.get();
  534. traceExpression("BoundCursor:", cur.querySelector());
  535. }
  536. throwError1(HQLERR_DatasetNotActive, tablename.str());
  537. return NULL; //remove warning about control paths
  538. }
  539. BoundRow * HqlCppTranslator::ensureLinkCountedRow(BuildCtx & ctx, BoundRow * row)
  540. {
  541. if (row->isLinkCounted())
  542. return row;
  543. OwnedHqlExpr srcRow = createTranslated(row->queryBound());
  544. OwnedHqlExpr tempRowExpr = declareLinkedRowExpr(ctx, row->queryRecord(), false);
  545. Owned<BoundRow> tempRow = row->clone(tempRowExpr);
  546. OwnedHqlExpr source = getPointer(row->queryBound());
  547. BuildCtx subctx(ctx);
  548. if (row->isConditional())
  549. subctx.addFilter(source);
  550. IHqlExpression * sourceExpr = row->querySelector();
  551. OwnedHqlExpr rowExpr = sourceExpr->isDataset() ? ensureActiveRow(sourceExpr) : LINK(sourceExpr);
  552. OwnedHqlExpr size = createSizeof(rowExpr);
  553. CHqlBoundExpr boundSize;
  554. buildExpr(subctx, size, boundSize);
  555. StringBuffer allocatorName;
  556. ensureRowAllocator(allocatorName, ctx, row->queryRecord(), getCurrentActivityId(subctx));
  557. StringBuffer s;
  558. s.append("rtlCloneRow(").append(allocatorName).append(",");
  559. generateExprCpp(s, boundSize.expr).append(",");
  560. generateExprCpp(s, source);
  561. s.append(")");
  562. OwnedHqlExpr call = createQuoted(s, tempRow->queryBound()->getType());
  563. subctx.addAssign(tempRow->queryBound(), call);
  564. ctx.associate(*tempRow);
  565. return tempRow;
  566. }
  567. IReferenceSelector * HqlCppTranslator::ensureLinkCountedRow(BuildCtx & ctx, IReferenceSelector * source)
  568. {
  569. if (!source->isRoot() || !source->queryRootRow()->isLinkCounted())
  570. {
  571. Owned<BoundRow> row = source->getRow(ctx);
  572. BoundRow * lcrRow = ensureLinkCountedRow(ctx, row);
  573. assertex(row != lcrRow);
  574. return createReferenceSelector(lcrRow, source->queryExpr());
  575. }
  576. return LINK(source);
  577. }
  578. //---------------------------------------------------------------------------
  579. void HqlCppTranslator::doBuildExprAggregate(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt)
  580. {
  581. OwnedHqlExpr normalized = normalizeAnyDatasetAliases(expr);
  582. if (expr != normalized)
  583. {
  584. buildExpr(ctx, normalized, tgt);
  585. return;
  586. }
  587. node_operator op = expr->getOperator();
  588. ITypeInfo * type = expr->queryType();
  589. ITypeInfo * tempType = op == no_count ? unsignedType : type;
  590. LoopInvariantHelper helper;
  591. BuildCtx aggctx(ctx);
  592. if (options.optimizeLoopInvariant)
  593. helper.getBestContext(aggctx, expr);
  594. CHqlBoundTarget result;
  595. createTempFor(aggctx, tempType, result, typemod_none, FormatNatural);
  596. doBuildAssignAggregate(aggctx, result, expr);
  597. tgt.setFromTarget(result);
  598. if (!isSameBasicType(type, tempType))
  599. tgt.expr.setown(createValue(no_implicitcast, LINK(type), tgt.expr.getClear()));
  600. if (expr->isPure())
  601. aggctx.associateExpr(expr, tgt);
  602. }
  603. void HqlCppTranslator::doBuildAssignAggregateLoop(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr, IHqlExpression * dataset, IHqlExpression * doneFirstVar, bool multiPath)
  604. {
  605. node_operator op = expr->getOperator();
  606. switch (op)
  607. {
  608. case no_exists:
  609. {
  610. OwnedHqlExpr optimized = queryOptimizedExists(ctx, expr, dataset);
  611. if (optimized)
  612. {
  613. if (matchesBoolean(optimized, false))
  614. return;
  615. if (multiPath)
  616. {
  617. BuildCtx condctx(ctx);
  618. condctx.addFilter(optimized);
  619. assignBound(condctx, target, queryBoolExpr(true));
  620. }
  621. else
  622. assignBound(ctx, target, optimized);
  623. return;
  624. }
  625. break;
  626. }
  627. case no_count:
  628. {
  629. CHqlBoundExpr temp;
  630. if (canBuildOptimizedCount(ctx, dataset, temp))
  631. {
  632. OwnedHqlExpr thisCount = temp.getTranslatedExpr();
  633. buildIncrementAssign(ctx, target, thisCount);
  634. return;
  635. }
  636. break;
  637. }
  638. }
  639. switch (dataset->getOperator())
  640. {
  641. case no_if:
  642. {
  643. BuildCtx subctx(ctx);
  644. IHqlStmt * stmt = buildFilterViaExpr(subctx, dataset->queryChild(0));
  645. doBuildAssignAggregateLoop(subctx, target, expr, dataset->queryChild(1), doneFirstVar, multiPath);
  646. subctx.selectElse(stmt);
  647. doBuildAssignAggregateLoop(subctx, target, expr, dataset->queryChild(2), doneFirstVar, multiPath);
  648. return;
  649. }
  650. case no_addfiles:
  651. {
  652. doBuildAssignAggregateLoop(ctx, target, expr, dataset->queryChild(0), doneFirstVar, true);
  653. doBuildAssignAggregateLoop(ctx, target, expr, dataset->queryChild(1), doneFirstVar, true);
  654. return;
  655. }
  656. case no_chooseds:
  657. {
  658. CHqlBoundExpr cond;
  659. buildExpr(ctx, dataset->queryChild(0), cond);
  660. IHqlExpression * last = queryLastNonAttribute(dataset);
  661. BuildCtx subctx(ctx);
  662. IHqlStmt * switchstmt = subctx.addSwitch(cond.expr);
  663. ForEachChildFrom(i, dataset, 1)
  664. {
  665. IHqlExpression * cur = dataset->queryChild(i);
  666. if (cur != last)
  667. {
  668. OwnedHqlExpr label = getSizetConstant(i);
  669. subctx.addCase(switchstmt, label);
  670. }
  671. else
  672. subctx.addDefault(switchstmt);
  673. doBuildAssignAggregateLoop(subctx, target, expr, cur, doneFirstVar, multiPath);
  674. }
  675. return;
  676. }
  677. case no_null:
  678. return;
  679. }
  680. LinkedHqlExpr arg = expr->queryChild(1);
  681. IHqlExpression * oldDataset = expr->queryChild(0);
  682. //If no_if or no_addfiles has been optimized above then the selector for the argument will have changed => map it.
  683. if (arg && (dataset != oldDataset))
  684. arg.setown(replaceSelector(arg, oldDataset, dataset));
  685. bool needToBreak = (op == no_exists);
  686. if (needToBreak)
  687. {
  688. //if it can have at most one row (fairly strange code!) then don't add a break
  689. //unless it was deliberately a choosen to restrict the number of iterations.
  690. if (hasNoMoreRowsThan(dataset, 1) && (dataset->getOperator() != no_choosen))
  691. needToBreak = false;
  692. }
  693. BuildCtx loopctx(ctx);
  694. buildDatasetIterate(loopctx, dataset, needToBreak);
  695. switch (op)
  696. {
  697. case no_exists:
  698. buildExprAssign(loopctx, target, queryBoolExpr(true));
  699. if (needToBreak)
  700. loopctx.addBreak();
  701. break;
  702. case no_count:
  703. {
  704. OwnedHqlExpr inc = createValue(no_postinc, makeVoidType(), LINK(target.expr));
  705. loopctx.addExpr(inc);
  706. break;
  707. }
  708. case no_sum:
  709. {
  710. OwnedHqlExpr cseArg = options.spotCSE ? spotScalarCSE(arg) : LINK(arg);
  711. buildIncrementAssign(loopctx, target, cseArg);
  712. break;
  713. }
  714. case no_min:
  715. case no_max:
  716. {
  717. BuildCtx maxctx(loopctx);
  718. OwnedHqlExpr resultExpr = target.getTranslatedExpr();
  719. OwnedHqlExpr cseArg = options.spotCSE ? spotScalarCSE(arg) : LINK(arg);
  720. OwnedHqlExpr simpleArg = buildSimplifyExpr(loopctx, cseArg);
  721. OwnedHqlExpr test = createBoolExpr((op == no_min) ? no_lt : no_gt, LINK(simpleArg), LINK(resultExpr));
  722. if (doneFirstVar)
  723. {
  724. IHqlExpression * firstTest = createValue(no_not, makeBoolType(), LINK(doneFirstVar));
  725. test.setown(createBoolExpr(no_or, firstTest, test.getClear()));
  726. }
  727. buildFilter(maxctx, test);
  728. buildExprAssign(maxctx, target, simpleArg);
  729. if (doneFirstVar)
  730. buildAssignToTemp(maxctx, doneFirstVar, queryBoolExpr(true));
  731. break;
  732. }
  733. default:
  734. assertex(!"unknown aggregate on child datasets");
  735. break;
  736. }
  737. }
  738. bool assignAggregateDirect(const CHqlBoundTarget & target, IHqlExpression * expr)
  739. {
  740. node_operator op = expr->getOperator();
  741. ITypeInfo * type = expr->queryType();
  742. ITypeInfo * tempType = op == no_count ? unsignedType : type;
  743. if (!isSameUnqualifiedType(target.queryType(), tempType))
  744. return false;
  745. //For exists/count/sum use a temporary variable, and then assign rather than accumulating directly in the target
  746. switch (op)
  747. {
  748. case no_sum:
  749. if (type->getTypeCode() != type_int)
  750. break;
  751. //fall through
  752. case no_exists:
  753. case no_count:
  754. if (target.expr->getOperator() != no_variable)
  755. return false;
  756. break;
  757. }
  758. return true;
  759. }
  760. static bool isNullValueMinimumValue(ITypeInfo * type)
  761. {
  762. switch (type->getTypeCode())
  763. {
  764. case type_int:
  765. case type_swapint:
  766. case type_decimal:
  767. return !type->isSigned();
  768. case type_data:
  769. case type_qstring:
  770. return true;
  771. }
  772. return false;
  773. }
  774. void HqlCppTranslator::doBuildAssignAggregate(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * _expr)
  775. {
  776. OwnedHqlExpr expr = normalizeAnyDatasetAliases(_expr);
  777. if (assignAggregateDirect(target, expr))
  778. {
  779. IHqlExpression * dataset = expr->queryChild(0);
  780. OwnedHqlExpr resultExpr = target.getTranslatedExpr();
  781. node_operator op = expr->getOperator();
  782. switch (op)
  783. {
  784. case no_exists:
  785. buildExprAssign(ctx, target, queryBoolExpr(false));
  786. break;
  787. default:
  788. {
  789. OwnedHqlExpr null = createNullExpr(target.queryType());
  790. buildExprAssign(ctx, target, null);
  791. break;
  792. }
  793. }
  794. OwnedHqlExpr doneFirstVar;
  795. if ((op == no_min) || ((op == no_max) && !isNullValueMinimumValue(target.queryType())))
  796. {
  797. doneFirstVar.setown(ctx.getTempDeclare(queryBoolType(), queryBoolExpr(false)));
  798. }
  799. doBuildAssignAggregateLoop(ctx, target, expr, dataset, doneFirstVar, false);
  800. }
  801. else
  802. {
  803. doBuildExprAssign(ctx, target, expr);
  804. }
  805. }
  806. //---------------------------------------------------------------------------
  807. bool HqlCppTranslator::canBuildOptimizedCount(BuildCtx & ctx, IHqlExpression * dataset, CHqlBoundExpr & tgt)
  808. {
  809. switch (dataset->getOperator())
  810. {
  811. case no_select:
  812. {
  813. if (isMultiLevelDatasetSelector(dataset, false))
  814. return false;
  815. Owned<IReferenceSelector> selector = buildReference(ctx, dataset);
  816. CHqlBoundExpr temp;
  817. selector->get(ctx, temp);
  818. tgt.expr.setown(getBoundCount(temp));
  819. return true;
  820. }
  821. break;
  822. default:
  823. if (!alwaysEvaluatesToBound(dataset))
  824. break;
  825. //fall through
  826. case no_rows:
  827. case no_null:
  828. {
  829. CHqlBoundExpr temp;
  830. buildDataset(ctx, dataset, temp, FormatNatural);
  831. tgt.expr.setown(getBoundCount(temp));
  832. return true;
  833. }
  834. }
  835. #if 0
  836. //This is improves a few obscure cases (normally in the global context). I'm not convinced it is worth the extra cycles.
  837. //Could also remove the bound.count test.
  838. CHqlBoundExpr bound;
  839. if (ctx.getMatchExpr(dataset, bound) && bound.count)
  840. {
  841. tgt.expr.setown(getBoundCount(bound));
  842. return true;
  843. }
  844. #endif
  845. return false;
  846. }
  847. void HqlCppTranslator::doBuildExprCount(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt)
  848. {
  849. if (expr->hasAttribute(keyedAtom))
  850. throwError(HQLERR_KeyedCountNonKeyable);
  851. IHqlExpression * dataset = expr->queryChild(0);
  852. CHqlBoundExpr temp;
  853. if (canBuildOptimizedCount(ctx, dataset, temp))
  854. {
  855. OwnedHqlExpr translated = temp.getTranslatedExpr();
  856. OwnedHqlExpr cast = ensureExprType(translated, expr->queryType());
  857. buildExpr(ctx, cast, tgt);
  858. }
  859. else
  860. doBuildExprAggregate(ctx, expr, tgt);
  861. }
  862. //---------------------------------------------------------------------------
  863. IHqlExpression * HqlCppTranslator::queryOptimizedExists(BuildCtx & ctx, IHqlExpression * expr, IHqlExpression * dataset)
  864. {
  865. node_operator dsOp = dataset->getOperator();
  866. //really this is isSimple()
  867. CHqlBoundExpr optimized;
  868. bool canOptimizeCount = canBuildOptimizedCount(ctx, dataset, optimized);
  869. node_operator op = (expr->getOperator() == no_exists) ? no_ne : no_eq;
  870. bool specialCase = false;
  871. switch (dsOp)
  872. {
  873. case no_select:
  874. specialCase = canOptimizeCount;
  875. break;
  876. default:
  877. specialCase = !canOptimizeCount && alwaysEvaluatesToBound(dataset);
  878. break;
  879. }
  880. OwnedHqlExpr test;
  881. if (specialCase)
  882. {
  883. CHqlBoundExpr temp;
  884. buildDataset(ctx, dataset, temp, FormatNatural);
  885. if (temp.count)
  886. test.set(temp.count);
  887. else
  888. test.setown(getBoundSize(temp));
  889. }
  890. else if (canOptimizeCount)
  891. {
  892. test.set(optimized.expr);
  893. }
  894. if (test)
  895. {
  896. OwnedHqlExpr cond = createBoolExpr(op, LINK(test), createConstant(test->queryType()->castFrom(false, 0)));
  897. if (cond->isConstant())
  898. return foldHqlExpression(cond);
  899. return cond.getClear();
  900. }
  901. return NULL;
  902. }
  903. void HqlCppTranslator::doBuildExprExists(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt)
  904. {
  905. OwnedHqlExpr optimized = queryOptimizedExists(ctx, expr, expr->queryChild(0));
  906. if (optimized)
  907. tgt.expr.setown(optimized.getClear());
  908. else
  909. doBuildExprAggregate(ctx, expr, tgt);
  910. }
  911. //---------------------------------------------------------------------------
  912. static IHqlExpression * createMinMax(node_operator compareOp, ITypeInfo * type, IHqlExpression * left, IHqlExpression * right)
  913. {
  914. return createValue(no_if, LINK(type),
  915. createBoolExpr(compareOp, LINK(left), LINK(right)),
  916. LINK(left), LINK(right));
  917. }
  918. bool HqlCppTranslator::doBuildAggregateMinMaxList(BuildCtx & ctx, const CHqlBoundTarget * target, IHqlExpression * expr, IHqlExpression * list, CHqlBoundExpr * tgt, node_operator compareOp)
  919. {
  920. OwnedHqlExpr value;
  921. unsigned max = list->numChildren();
  922. switch(max)
  923. {
  924. case 0:
  925. value.setown(createNullExpr(expr));
  926. break;
  927. case 1:
  928. value.set(list->queryChild(0));
  929. break;
  930. case 2:
  931. case 3:
  932. {
  933. OwnedHqlExpr simple[3];
  934. for (unsigned i=0; i < max; i++)
  935. {
  936. CHqlBoundExpr bound;
  937. buildSimpleExpr(ctx, list->queryChild(i), bound);
  938. simple[i].setown(bound.getTranslatedExpr());
  939. }
  940. ITypeInfo * type = expr->queryType();
  941. if (max == 2)
  942. value.setown(createMinMax(compareOp, type, simple[0], simple[1]));
  943. else
  944. {
  945. OwnedHqlExpr cmp02 = createMinMax(compareOp, type, simple[0], simple[2]);
  946. OwnedHqlExpr cmp12 = createMinMax(compareOp, type, simple[1], simple[2]);
  947. value.setown(createValue(no_if, expr->getType(),
  948. createBoolExpr(compareOp, LINK(simple[0]), LINK(simple[1])),
  949. LINK(cmp02), LINK(cmp12)));
  950. }
  951. }
  952. }
  953. if (value)
  954. {
  955. buildExprOrAssign(ctx, target, value, tgt);
  956. return true;
  957. }
  958. {
  959. CHqlBoundTarget temp;
  960. createTempFor(ctx, expr, temp);
  961. buildExprAssign(ctx, temp, list->queryChild(0));
  962. OwnedHqlExpr best = temp.getTranslatedExpr();
  963. for (unsigned i=1; i < list->numChildren(); i++)
  964. {
  965. CHqlBoundExpr bound;
  966. buildSimpleExpr(ctx, list->queryChild(i), bound);
  967. OwnedHqlExpr simple = bound.getTranslatedExpr();
  968. BuildCtx subctx(ctx);
  969. OwnedHqlExpr cond = createBoolExpr(compareOp, LINK(simple), LINK(best));
  970. buildFilter(subctx, cond);
  971. buildExprAssign(subctx, temp, simple);
  972. }
  973. buildExprOrAssign(ctx, target, best, tgt);
  974. return true;
  975. }
  976. }
  977. void HqlCppTranslator::doBuildAggregateList(BuildCtx & ctx, const CHqlBoundTarget * target, IHqlExpression * expr, CHqlBoundExpr * tgt)
  978. {
  979. OwnedHqlExpr list = normalizeListCasts(expr->queryChild(0));
  980. if (list->getOperator() == no_alias_scope)
  981. {
  982. expandAliasScope(ctx, list);
  983. list.set(list->queryChild(0));
  984. }
  985. node_operator aggOp;
  986. switch (expr->getOperator())
  987. {
  988. case no_existslist:
  989. {
  990. //Fixed length lists should have been optimized away
  991. CHqlBoundExpr bound;
  992. buildExpr(ctx, list, bound);
  993. OwnedHqlExpr test;
  994. if (bound.count)
  995. test.set(bound.count);
  996. else
  997. test.setown(getBoundLength(bound));
  998. OwnedHqlExpr value = createValue(no_ne, makeBoolType(), LINK(test), ensureExprType(queryZero(), test->queryType()));
  999. OwnedHqlExpr translated = createTranslated(value);
  1000. buildExprOrAssign(ctx, target, translated, tgt);
  1001. return;
  1002. }
  1003. case no_countlist:
  1004. {
  1005. //Fixed length lists should have been optimized away
  1006. CHqlBoundExpr bound;
  1007. buildExpr(ctx, list, bound);
  1008. OwnedHqlExpr test = getBoundCount(bound);
  1009. OwnedHqlExpr value = ensureExprType(test, expr->queryType());
  1010. OwnedHqlExpr translated = createTranslated(value);
  1011. buildExprOrAssign(ctx, target, translated, tgt);
  1012. return;
  1013. }
  1014. case no_sumlist:
  1015. aggOp = no_sumgroup;
  1016. if (list->getOperator() == no_list)
  1017. {
  1018. HqlExprArray args;
  1019. ITypeInfo * exprType = expr->queryType();
  1020. ForEachChild(i, list)
  1021. args.append(*ensureExprType(list->queryChild(i), exprType));
  1022. OwnedHqlExpr balanced = createBalanced(no_add, exprType, args);
  1023. if (!balanced)
  1024. balanced.setown(ensureExprType(queryZero(), exprType));
  1025. buildExprOrAssign(ctx, target, balanced, tgt);
  1026. return;
  1027. }
  1028. //special case fixed length lists
  1029. break;
  1030. case no_minlist:
  1031. aggOp = no_mingroup;
  1032. if (list->getOperator() == no_list)
  1033. {
  1034. if (doBuildAggregateMinMaxList(ctx, target, expr, list, tgt, no_lt))
  1035. return;
  1036. }
  1037. break;
  1038. case no_maxlist:
  1039. aggOp = no_maxgroup;
  1040. if (list->getOperator() == no_list)
  1041. {
  1042. if (doBuildAggregateMinMaxList(ctx, target, expr, list, tgt, no_gt))
  1043. return;
  1044. }
  1045. break;
  1046. default:
  1047. throwUnexpectedOp(expr->getOperator());
  1048. }
  1049. ITypeInfo * elemType = list->queryType()->queryChildType();
  1050. if (!elemType)
  1051. elemType = defaultIntegralType;
  1052. //Default implementation in terms of a dataset
  1053. OwnedHqlExpr field = createField(valueId, LINK(elemType), NULL);
  1054. OwnedHqlExpr record = createRecord(field);
  1055. OwnedHqlExpr ds = createDataset(no_temptable, LINK(list), LINK(record));
  1056. OwnedHqlExpr aggField = createField(valueId, expr->getType(), NULL);
  1057. OwnedHqlExpr aggRecord = createRecord(aggField);
  1058. OwnedHqlExpr self = createSelector(no_self, aggRecord, NULL);
  1059. OwnedHqlExpr aggExpr = createValue(aggOp, expr->getType(), createSelectExpr(LINK(ds), LINK(field)));
  1060. OwnedHqlExpr aggAssign = createAssign(createSelectExpr(LINK(self), LINK(aggField)), LINK(aggExpr));
  1061. OwnedHqlExpr aggTransform = createValue(no_newtransform, makeTransformType(aggRecord->getType()), LINK(aggAssign));
  1062. OwnedHqlExpr agg = createDataset(no_newaggregate, LINK(ds), createComma(LINK(aggRecord), LINK(aggTransform)));
  1063. OwnedHqlExpr result = createNewSelectExpr(createRow(no_selectnth, LINK(agg), createConstantOne()), LINK(aggField));
  1064. buildExprOrAssign(ctx, target, result, tgt);
  1065. }
  1066. //---------------------------------------------------------------------------
  1067. static HqlTransformerInfo graphIndependanceCheckerInfo("GraphIndependanceChecker");
  1068. class GraphIndependanceChecker : public NewHqlTransformer
  1069. {
  1070. public:
  1071. GraphIndependanceChecker(IHqlExpression * _graph) : NewHqlTransformer(graphIndependanceCheckerInfo), graph(_graph) { independent = true; }
  1072. void analyseExpr(IHqlExpression * expr)
  1073. {
  1074. if (!independent || alreadyVisited(expr))
  1075. return;
  1076. switch (expr->getOperator())
  1077. {
  1078. case no_getgraphresult:
  1079. case no_getgraphloopresultset:
  1080. case no_getgraphloopresult:
  1081. if (expr->queryChild(1) == graph)
  1082. {
  1083. independent = false;
  1084. return;
  1085. }
  1086. break;
  1087. }
  1088. NewHqlTransformer::analyseExpr(expr);
  1089. }
  1090. inline bool isIndependent() const { return independent; }
  1091. protected:
  1092. LinkedHqlExpr graph;
  1093. bool independent;
  1094. };
  1095. bool isGraphIndependent(IHqlExpression * expr, IHqlExpression * graph)
  1096. {
  1097. switch (expr->getOperator())
  1098. {
  1099. case no_constant:
  1100. return true;
  1101. }
  1102. GraphIndependanceChecker checker(graph);
  1103. checker.analyse(expr, 0);
  1104. return checker.isIndependent();
  1105. }
  1106. ///--------------------------------------------------------------------------------------------------------------------
  1107. IHqlExpression * createCounterAsGraphResult(IHqlExpression * counter, IHqlExpression * represents, unsigned seq)
  1108. {
  1109. OwnedHqlExpr value = createScalarFromGraphResult(counter->queryType(), unsignedType, represents, seq);
  1110. OwnedHqlExpr internalAttr = createAttribute(internalAtom);
  1111. return createAlias(value, internalAttr);
  1112. }
  1113. ChildGraphExprBuilder::ChildGraphExprBuilder(unsigned _numInputs)
  1114. : numInputs(_numInputs)
  1115. {
  1116. numOutputs=0;
  1117. represents.setown(createAttribute(graphAtom, createUniqueId()));
  1118. resultsExpr.setown(createAttribute(resultsAtom, LINK(represents)));
  1119. }
  1120. IHqlExpression * ChildGraphExprBuilder::addDataset(IHqlExpression * expr)
  1121. {
  1122. OwnedHqlExpr resultNumExpr;
  1123. ForEachItemIn(i, results)
  1124. {
  1125. IHqlExpression & curSetResult = results.item(i);
  1126. if (expr->queryBody() == curSetResult.queryChild(0)->queryBody())
  1127. {
  1128. resultNumExpr.set(curSetResult.queryChild(2));
  1129. break;
  1130. }
  1131. }
  1132. if (!resultNumExpr)
  1133. {
  1134. resultNumExpr.setown(getSizetConstant(numResults()));
  1135. results.append(*createValue(no_setgraphresult, makeVoidType(), LINK(expr), LINK(represents), LINK(resultNumExpr)));
  1136. numOutputs++;
  1137. }
  1138. HqlExprArray args;
  1139. args.append(*LINK(expr->queryRecord()));
  1140. args.append(*LINK(represents));
  1141. args.append(*LINK(resultNumExpr));
  1142. if (isGrouped(expr))
  1143. args.append(*createAttribute(groupedAtom));
  1144. if (!expr->isDataset())
  1145. args.append(*createAttribute(rowAtom));
  1146. args.append(*createAttribute(externalAtom, LINK(resultsExpr)));
  1147. args.append(*createAttribute(_original_Atom, LINK(expr)));
  1148. IHqlExpression * recordCountAttr = queryRecordCountInfo(expr);
  1149. if (recordCountAttr)
  1150. args.append(*LINK(recordCountAttr));
  1151. OwnedHqlExpr ret = expr->isDictionary() ? createDictionary(no_getgraphresult, args) : createDataset(no_getgraphresult, args);
  1152. if (expr->isDatarow())
  1153. ret.setown(createRow(no_selectnth, LINK(ret), createComma(getSizetConstant(1), createAttribute(noBoundCheckAtom))));
  1154. return ret.getClear();
  1155. }
  1156. void ChildGraphExprBuilder::addAction(IHqlExpression * expr)
  1157. {
  1158. results.append(*LINK(expr));
  1159. }
  1160. unsigned ChildGraphExprBuilder::addInput()
  1161. {
  1162. unsigned id = numResults();
  1163. numInputs++;
  1164. return id;
  1165. }
  1166. IHqlExpression * ChildGraphExprBuilder::getGraph(node_operator listOp)
  1167. {
  1168. HqlExprArray args;
  1169. args.append(*LINK(represents));
  1170. args.append(*getSizetConstant(numResults()));
  1171. args.append(*createActionList(listOp, results));
  1172. return createValue(no_childquery, makeVoidType(), args);
  1173. }
  1174. //---------------------------------------------------------------------------
  1175. // Child dataset processing
  1176. ChildGraphBuilder::ChildGraphBuilder(HqlCppTranslator & _translator, IHqlExpression * subgraph)
  1177. : translator(_translator), childQuery(subgraph)
  1178. {
  1179. represents.set(subgraph->queryChild(0));
  1180. id = translator.nextActivityId();
  1181. appendUniqueId(instanceName.append("child"), id);
  1182. instanceExpr.setown(createQuoted(instanceName, makeBoolType()));
  1183. resultsExpr.setown(createAttribute(resultsAtom, LINK(represents)));
  1184. StringBuffer s;
  1185. resultInstanceExpr.setown(createQuoted(appendUniqueId(s.append("res"), id), makeBoolType()));
  1186. numResults = (unsigned)getIntValue(subgraph->queryChild(1));
  1187. }
  1188. void ChildGraphBuilder::generateGraph(BuildCtx & ctx)
  1189. {
  1190. BuildCtx graphctx(ctx);
  1191. //Make sure at least one results - because currently that's how we determine if new resourcing is being used
  1192. //Remove this line once all engines use the new child queries exclusively
  1193. if (numResults == 0) numResults++;
  1194. OwnedHqlExpr resourced = translator.getResourcedChildGraph(graphctx, childQuery, numResults, no_none);
  1195. Owned<ParentExtract> extractBuilder = translator.createExtractBuilder(graphctx, PETchild, represents, resourced, true);
  1196. if (!translator.queryOptions().serializeRowsetInExtract)
  1197. extractBuilder->setAllowDestructor();
  1198. translator.beginExtract(graphctx, extractBuilder);
  1199. translator.doBuildThorSubGraph(graphctx, resourced, SubGraphChild, id, represents);
  1200. EvalContext * instance = translator.queryEvalContext(graphctx);
  1201. OwnedHqlExpr retInstanceExpr;
  1202. if (instance && !translator.insideOnCreate(graphctx))
  1203. retInstanceExpr.setown(instance->createGraphLookup(id, true));
  1204. else
  1205. retInstanceExpr.setown(translator.doCreateGraphLookup(graphctx, graphctx, id, "this", true));
  1206. assertex(retInstanceExpr == instanceExpr);
  1207. CHqlBoundExpr boundExtract;
  1208. extractBuilder->endCreateExtract(boundExtract);
  1209. HqlExprArray args;
  1210. args.append(*LINK(instanceExpr));
  1211. args.append(*createTranslated(boundExtract.length));
  1212. args.append(*boundExtract.getTranslatedExpr());
  1213. OwnedHqlExpr call = translator.bindFunctionCall(evaluateChildQueryInstanceId, args);
  1214. CHqlBoundExpr bound;
  1215. translator.buildExpr(graphctx, call, bound);
  1216. StringBuffer s;
  1217. s.append("Owned<IEclGraphResults> ");
  1218. translator.generateExprCpp(s, resultInstanceExpr);
  1219. s.append(" = ");
  1220. translator.generateExprCpp(s, bound.expr);
  1221. s.append(";");
  1222. graphctx.addQuoted(s);
  1223. translator.endExtract(graphctx, extractBuilder);
  1224. ctx.associateExpr(resultsExpr, resultInstanceExpr);
  1225. }
  1226. void ChildGraphBuilder::generatePrefetchGraph(BuildCtx & _ctx, OwnedHqlExpr * retGraphExpr)
  1227. {
  1228. BuildCtx ctx(_ctx);
  1229. ctx.addGroup();
  1230. BuildCtx aliasctx(ctx);
  1231. aliasctx.addGroup();
  1232. OwnedHqlExpr resourced = translator.getResourcedChildGraph(ctx, childQuery, numResults, no_none);
  1233. Owned<ParentExtract> extractBuilder = translator.createExtractBuilder(ctx, PETchild, represents, resourced, false);
  1234. createBuilderAlias(aliasctx, extractBuilder);
  1235. translator.beginExtract(ctx, extractBuilder);
  1236. translator.doBuildThorSubGraph(ctx, resourced, SubGraphChild, id, represents);
  1237. EvalContext * instance = translator.queryEvalContext(ctx);
  1238. OwnedHqlExpr retInstanceExpr;
  1239. assertex(instance && !translator.insideOnCreate(ctx));
  1240. retInstanceExpr.setown(instance->createGraphLookup(id, true));
  1241. assertex(retInstanceExpr == instanceExpr);
  1242. retGraphExpr->setown(retInstanceExpr.getClear());
  1243. }
  1244. void ChildGraphBuilder::createBuilderAlias(BuildCtx & ctx, ParentExtract * extractBuilder)
  1245. {
  1246. StringBuffer s;
  1247. s.append("rtlRowBuilder & ");
  1248. translator.generateExprCpp(s, extractBuilder->queryExtractName());
  1249. s.append(" = builder;");
  1250. ctx.addQuoted(s);
  1251. }
  1252. unique_id_t ChildGraphBuilder::buildLoopBody(BuildCtx & ctx, bool multiInstance)
  1253. {
  1254. BuildCtx subctx(ctx);
  1255. subctx.addGroup();
  1256. OwnedHqlExpr resourced = translator.getResourcedChildGraph(ctx, childQuery, numResults, no_loop);
  1257. //Add a flag to indicate multi instance
  1258. if (multiInstance)
  1259. resourced.setown(appendOwnedOperand(resourced, createAttribute(multiInstanceAtom)));
  1260. bool isGlobalThorLoop = translator.targetThor() && !translator.insideChildQuery(ctx);
  1261. Owned<ParentExtract> extractBuilder = isGlobalThorLoop ? translator.createExtractBuilder(ctx, PETloop, represents, GraphRemote, false)
  1262. : translator.createExtractBuilder(ctx, PETloop, represents, resourced, false);
  1263. createBuilderAlias(subctx, extractBuilder);
  1264. translator.beginExtract(ctx, extractBuilder);
  1265. translator.doBuildThorSubGraph(ctx, resourced, SubGraphLoop, id, represents);
  1266. translator.endExtract(ctx, extractBuilder);
  1267. return id;
  1268. }
  1269. static HqlTransformerInfo graphLoopReplacerInfo("GraphLoopReplacer");
  1270. class GraphLoopReplacer : public NewHqlTransformer
  1271. {
  1272. public:
  1273. GraphLoopReplacer(IHqlExpression * _rowsid, IHqlExpression * _represents, IHqlExpression * _counter, bool _isParallel) :
  1274. NewHqlTransformer(graphLoopReplacerInfo), rowsid(_rowsid), represents(_represents), counter(_counter), isParallel(_isParallel)
  1275. {
  1276. }
  1277. virtual IHqlExpression * createTransformed(IHqlExpression * expr)
  1278. {
  1279. switch (expr->getOperator())
  1280. {
  1281. case no_counter:
  1282. if (expr->queryBody() == counter)
  1283. {
  1284. if (isParallel)
  1285. {
  1286. HqlExprArray args;
  1287. args.append(*LINK(represents));
  1288. // unwindChildren(args, expr);
  1289. OwnedHqlExpr ret = createValue(no_loopcounter, expr->getType(), args);
  1290. //Yuk: Wrap this in an alias to ensure it is evaluated at the correct place.
  1291. //there has to be a better way..... We could...
  1292. //a) strictly defined when it can be evaluated - e.g., ctx->defines(graph) && (!parentctx || !parentctx->definesGraph)
  1293. //b) set a flag in the expression to indicate forced evaluation (even worse than the alias)
  1294. //c) add the code to evaluate no_loopcounter inside evaluateInContext
  1295. return createAlias(ret, internalAttrExpr);
  1296. }
  1297. else
  1298. {
  1299. counterResult.setown(createCounterAsGraphResult(counter, represents, 0));
  1300. return LINK(counterResult);
  1301. }
  1302. }
  1303. break;
  1304. case no_rowsetindex:
  1305. {
  1306. IHqlExpression * rowset = expr->queryChild(0);
  1307. if (rowset->getOperator() != no_rowset)
  1308. break;
  1309. IHqlExpression * rows = rowset->queryChild(0);
  1310. if (rows->queryChild(1) != rowsid)
  1311. break;
  1312. HqlExprArray args;
  1313. args.append(*LINK(rows->queryChild(0)->queryRecord()));
  1314. args.append(*LINK(represents));
  1315. args.append(*transform(expr->queryChild(1)));
  1316. return createDataset(no_getgraphloopresult, args);
  1317. }
  1318. case no_rowset:
  1319. {
  1320. IHqlExpression * rows = expr->queryChild(0);
  1321. if (rows->queryChild(1) != rowsid)
  1322. break;
  1323. HqlExprArray args;
  1324. args.append(*LINK(rows->queryChild(0)->queryRecord()));
  1325. args.append(*LINK(represents));
  1326. return createValue(no_getgraphloopresultset, expr->getType(), args);
  1327. }
  1328. }
  1329. return NewHqlTransformer::createTransformed(expr);
  1330. }
  1331. inline IHqlExpression * queryCounterResult() { return counterResult; }
  1332. protected:
  1333. IHqlExpression * rowsid;
  1334. IHqlExpression * represents;
  1335. IHqlExpression * counter;
  1336. OwnedHqlExpr counterResult;
  1337. bool isParallel;
  1338. };
  1339. unique_id_t ChildGraphBuilder::buildGraphLoopBody(BuildCtx & ctx, bool isParallel)
  1340. {
  1341. BuildCtx subctx(ctx);
  1342. subctx.addGroup();
  1343. IHqlExpression * query = childQuery->queryChild(2);
  1344. translator.traceExpression("Before Loop resource", query);
  1345. OwnedHqlExpr resourced = translator.getResourcedChildGraph(ctx, childQuery, numResults, no_loop);
  1346. translator.traceExpression("After Loop resource", resourced);
  1347. //Add a flag to indicate multi instance
  1348. if (isParallel)
  1349. {
  1350. HqlExprArray args;
  1351. unwindChildren(args, resourced);
  1352. args.append(*createAttribute(multiInstanceAtom));
  1353. args.append(*createAttribute(delayedAtom));
  1354. resourced.setown(resourced->clone(args));
  1355. }
  1356. bool isGlobalThorLoop = translator.targetThor() && !translator.insideChildQuery(ctx);
  1357. Owned<ParentExtract> extractBuilder = isGlobalThorLoop ? translator.createExtractBuilder(ctx, PETloop, represents, GraphRemote, false)
  1358. : translator.createExtractBuilder(ctx, PETloop, represents, resourced, false);
  1359. createBuilderAlias(subctx, extractBuilder);
  1360. translator.beginExtract(ctx, extractBuilder);
  1361. translator.doBuildThorSubGraph(ctx, resourced, SubGraphLoop, id, represents);
  1362. translator.endExtract(ctx, extractBuilder);
  1363. return id;
  1364. }
  1365. unique_id_t ChildGraphBuilder::buildRemoteGraph(BuildCtx & ctx)
  1366. {
  1367. BuildCtx subctx(ctx);
  1368. subctx.addGroup();
  1369. OwnedHqlExpr resourced = translator.getResourcedChildGraph(ctx, childQuery, numResults, no_allnodes);
  1370. Owned<ParentExtract> extractBuilder = translator.createExtractBuilder(ctx, PETremote, represents, GraphRemote, false);
  1371. createBuilderAlias(subctx, extractBuilder);
  1372. translator.beginExtract(ctx, extractBuilder);
  1373. translator.doBuildThorSubGraph(ctx, resourced, SubGraphChild, id, represents);
  1374. translator.endExtract(ctx, extractBuilder);
  1375. return id;
  1376. }
  1377. void HqlCppTranslator::buildChildGraph(BuildCtx & ctx, IHqlExpression * expr)
  1378. {
  1379. IHqlExpression * represents= expr->queryChild(0);
  1380. OwnedHqlExpr resultsExpr = createAttribute(resultsAtom, LINK(represents));
  1381. //Shouldn't really happen, but if this graph has already benn called just use the results
  1382. if (ctx.queryMatchExpr(resultsExpr))
  1383. return;
  1384. ChildGraphBuilder graphBuilder(*this, expr);
  1385. graphBuilder.generateGraph(ctx);
  1386. }
  1387. void HqlCppTranslator::beginExtract(BuildCtx & ctx, ParentExtract * extractBuilder)
  1388. {
  1389. ctx.associate(*extractBuilder);
  1390. }
  1391. void HqlCppTranslator::endExtract(BuildCtx & ctx, ParentExtract * extractBuilder)
  1392. {
  1393. extractBuilder->endUseExtract(ctx);
  1394. ctx.removeAssociation(extractBuilder);
  1395. }
  1396. void HqlCppTranslator::buildAssignChildDataset(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  1397. {
  1398. switch (expr->getOperator())
  1399. {
  1400. case no_call:
  1401. case no_externalcall:
  1402. case no_libraryinput:
  1403. buildDatasetAssign(ctx, target, expr);
  1404. return;
  1405. }
  1406. OwnedHqlExpr call;
  1407. {
  1408. ChildGraphExprBuilder builder(0);
  1409. call.setown(builder.addDataset(expr));
  1410. OwnedHqlExpr subquery = builder.getGraph();
  1411. buildStmt(ctx, subquery);
  1412. }
  1413. buildExprAssign(ctx, target, call);
  1414. }
  1415. IHqlExpression * HqlCppTranslator::getResourcedChildGraph(BuildCtx & ctx, IHqlExpression * childQuery, unsigned numResults, node_operator graphKind)
  1416. {
  1417. if (options.paranoidCheckNormalized || options.paranoidCheckDependencies)
  1418. DBGLOG("Before resourcing a child graph");
  1419. IHqlExpression * graphIdExpr = childQuery->queryChild(0);
  1420. IHqlExpression * originalQuery = childQuery->queryChild(2);
  1421. LinkedHqlExpr resourced = originalQuery;
  1422. checkNormalized(ctx, resourced);
  1423. unsigned csfFlags = CSFindex|options.optimizeDiskFlag;
  1424. switch (targetClusterType)
  1425. {
  1426. case HThorCluster:
  1427. csfFlags |= CSFcompoundSpill;
  1428. break;
  1429. case ThorLCRCluster:
  1430. //Don't compound spills inside a child query because it can cause non remote projects to become remote
  1431. //And we'll also probably be using the roxie code to implement
  1432. break;
  1433. case RoxieCluster:
  1434. break;
  1435. }
  1436. {
  1437. unsigned time = msTick();
  1438. CompoundSourceTransformer transformer(*this, CSFpreload|csfFlags);
  1439. resourced.setown(transformer.process(resourced));
  1440. checkNormalized(ctx, resourced);
  1441. updateTimer("workunit;tree transform: optimize disk read", msTick()-time);
  1442. }
  1443. if (options.optimizeGraph)
  1444. {
  1445. unsigned time = msTick();
  1446. traceExpression("BeforeOptimizeSub", resourced);
  1447. resourced.setown(optimizeHqlExpression(queryErrorProcessor(), resourced, getOptimizeFlags()|HOOcompoundproject));
  1448. traceExpression("AfterOptimizeSub", resourced);
  1449. updateTimer("workunit;optimize graph", msTick()-time);
  1450. }
  1451. traceExpression("BeforeResourcing Child", resourced);
  1452. unsigned time = msTick();
  1453. HqlExprCopyArray activeRows;
  1454. gatherActiveCursors(ctx, activeRows);
  1455. if (graphKind == no_loop)
  1456. {
  1457. bool insideChild = insideChildQuery(ctx);
  1458. resourced.setown(resourceLoopGraph(*this, activeRows, resourced, targetClusterType, graphIdExpr, numResults, insideChild));
  1459. }
  1460. else
  1461. resourced.setown(resourceNewChildGraph(*this, activeRows, resourced, targetClusterType, graphIdExpr, numResults));
  1462. updateTimer("workunit;resource graph", msTick()-time);
  1463. checkNormalized(ctx, resourced);
  1464. traceExpression("AfterResourcing Child", resourced);
  1465. resourced.setown(optimizeGraphPostResource(resourced, csfFlags, false));
  1466. if (options.optimizeSpillProject)
  1467. {
  1468. resourced.setown(convertSpillsToActivities(resourced, true));
  1469. resourced.setown(optimizeGraphPostResource(resourced, csfFlags, false));
  1470. }
  1471. if (options.paranoidCheckNormalized || options.paranoidCheckDependencies)
  1472. DBGLOG("After resourcing a child graph");
  1473. return resourced.getClear();
  1474. }
  1475. void HqlCppTranslator::buildChildDataset(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt)
  1476. {
  1477. if (expr->isPure() && ctx.getMatchExpr(expr, tgt))
  1478. return;
  1479. LoopInvariantHelper helper;
  1480. BuildCtx bestctx(ctx);
  1481. if (options.optimizeLoopInvariant)
  1482. helper.getBestContext(bestctx, expr);
  1483. CHqlBoundTarget temp;
  1484. //MORE: Should have similar code to buildTempExpr()
  1485. createTempFor(bestctx, expr, temp);
  1486. buildAssignChildDataset(bestctx, temp, expr);
  1487. tgt.setFromTarget(temp);
  1488. if (expr->isPure())
  1489. bestctx.associateExpr(expr, tgt);
  1490. }
  1491. unique_id_t HqlCppTranslator::buildGraphLoopSubgraph(BuildCtx & ctx, IHqlExpression * dataset, IHqlExpression * selSeq, IHqlExpression * rowsid, IHqlExpression * body, IHqlExpression * counter, bool multiInstance)
  1492. {
  1493. ChildGraphExprBuilder graphBuilder(0);
  1494. OwnedHqlExpr transformedBody;
  1495. OwnedHqlExpr counterResult;
  1496. IHqlExpression * graphid = graphBuilder.queryRepresents();
  1497. {
  1498. const bool isParallel = multiInstance;
  1499. GraphLoopReplacer replacer(rowsid, graphid, counter, isParallel);
  1500. transformedBody.setown(replacer.transformRoot(body));
  1501. counterResult.set(replacer.queryCounterResult());
  1502. }
  1503. if (counterResult)
  1504. graphBuilder.addInput();
  1505. OwnedHqlExpr result = createValue(no_setgraphloopresult, makeVoidType(), LINK(transformedBody), LINK(graphid));
  1506. graphBuilder.addAction(result);
  1507. OwnedHqlExpr subquery = graphBuilder.getGraph();
  1508. ChildGraphBuilder builder(*this, subquery);
  1509. return builder.buildGraphLoopBody(ctx, multiInstance);
  1510. }
  1511. unique_id_t HqlCppTranslator::buildRemoteSubgraph(BuildCtx & ctx, IHqlExpression * dataset)
  1512. {
  1513. ChildGraphExprBuilder graphBuilder(0);
  1514. if (dataset->isAction())
  1515. {
  1516. graphBuilder.addAction(dataset);
  1517. }
  1518. else
  1519. {
  1520. OwnedHqlExpr ignoredResult = graphBuilder.addDataset(dataset);
  1521. }
  1522. OwnedHqlExpr subquery = graphBuilder.getGraph();
  1523. ChildGraphBuilder builder(*this, subquery);
  1524. return builder.buildRemoteGraph(ctx);
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. // Functions to check whether a dataset can be evaluated inline or not.
  1528. //MORE: These should probably be split out into an hqlinline.cpp
  1529. bool HqlCppTranslator::canIterateInline(BuildCtx * ctx, IHqlExpression * expr)
  1530. {
  1531. return (isInlineOk() && ::canIterateInline(ctx, expr));
  1532. }
  1533. bool HqlCppTranslator::canAssignInline(BuildCtx * ctx, IHqlExpression * expr)
  1534. {
  1535. if (!isInlineOk())
  1536. return false;
  1537. return options.allowInlineSpill ? ::canProcessInline(ctx, expr) : ::canAssignInline(ctx, expr);
  1538. }
  1539. bool HqlCppTranslator::canEvaluateInline(BuildCtx * ctx, IHqlExpression * expr)
  1540. {
  1541. if (!isInlineOk())
  1542. return false;
  1543. return options.allowInlineSpill ? ::canProcessInline(ctx, expr) : ::canEvaluateInline(ctx, expr);
  1544. }
  1545. bool HqlCppTranslator::canProcessInline(BuildCtx * ctx, IHqlExpression * expr)
  1546. {
  1547. if (!isInlineOk())
  1548. return false;
  1549. return ::canProcessInline(ctx, expr);
  1550. }
  1551. bool HqlCppTranslator::isInlineOk()
  1552. {
  1553. if (!activeGraphCtx)
  1554. return true;
  1555. return true;
  1556. }
  1557. IHqlExpression * HqlCppTranslator::buildSpillChildDataset(BuildCtx & ctx, IHqlExpression * expr)
  1558. {
  1559. CHqlBoundExpr bound;
  1560. buildChildDataset(ctx, expr, bound);
  1561. return bound.getTranslatedExpr();
  1562. }
  1563. IHqlExpression * HqlCppTranslator::forceInlineAssignDataset(BuildCtx & ctx, IHqlExpression * expr)
  1564. {
  1565. loop
  1566. {
  1567. CHqlBoundExpr bound;
  1568. if (expr->isPure() && ctx.getMatchExpr(expr, bound))
  1569. return bound.getTranslatedExpr();
  1570. if (canProcessInline(&ctx, expr) || (expr->getOperator() == no_translated))
  1571. return LINK(expr);
  1572. switch (expr->getOperator())
  1573. {
  1574. case no_compound:
  1575. buildStmt(ctx, expr->queryChild(0));
  1576. expr = expr->queryChild(1);
  1577. break;
  1578. default:
  1579. return buildSpillChildDataset(ctx, expr);
  1580. }
  1581. }
  1582. }
  1583. //---------------------------------------------------------------------------
  1584. // Dataset temp creation
  1585. IHqlExpression * createGetResultFromWorkunitDataset(IHqlExpression * expr)
  1586. {
  1587. IHqlExpression * name = queryAttributeChild(expr, nameAtom, 0);
  1588. if (name)
  1589. name = createExprAttribute(namedAtom, LINK(name));
  1590. assertex(expr->isDataset());
  1591. return createDataset(no_getresult, LINK(expr->queryRecord()), createComma(LINK(expr->queryAttribute(sequenceAtom)), name));
  1592. }
  1593. void HqlCppTranslator::buildAssignSerializedDataset(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr, IAtom * serializeForm)
  1594. {
  1595. OwnedITypeInfo serializedType = getSerializedForm(expr->queryType(), serializeForm);
  1596. assertex(recordTypesMatch(target.queryType(), serializedType));
  1597. HqlExprArray args;
  1598. args.append(*createSerializer(ctx, expr->queryRecord(), serializeForm, serializerAtom));
  1599. args.append(*LINK(expr));
  1600. IIdAtom * func;
  1601. if (target.expr->isDictionary())
  1602. {
  1603. assertex(serializeForm == internalAtom);
  1604. func = rtlSerializeDictionaryId;
  1605. }
  1606. else if (expr->isDictionary())
  1607. {
  1608. assertex(serializeForm == diskAtom);
  1609. func = rtlSerializeDictionaryToDatasetId;
  1610. }
  1611. else
  1612. {
  1613. if (isGrouped(expr))
  1614. func = groupedRowset2DatasetXId;
  1615. else
  1616. func = rowset2DatasetXId;
  1617. }
  1618. OwnedHqlExpr call = bindFunctionCall(func, args);
  1619. buildExprAssign(ctx, target, call);
  1620. }
  1621. void HqlCppTranslator::buildSerializedDataset(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, IAtom * serializeForm)
  1622. {
  1623. CHqlBoundTarget target;
  1624. OwnedITypeInfo serializedType = getSerializedForm(expr->queryType(), serializeForm);
  1625. createTempFor(ctx, serializedType, target, typemod_none, FormatBlockedDataset);
  1626. buildAssignSerializedDataset(ctx, target, expr, serializeForm);
  1627. tgt.setFromTarget(target);
  1628. }
  1629. void HqlCppTranslator::buildAssignDeserializedDataset(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr, IAtom * serializeForm)
  1630. {
  1631. OwnedITypeInfo serializedType = getSerializedForm(target.queryType(), serializeForm);
  1632. assertex(recordTypesMatch(serializedType, expr->queryType()));
  1633. IIdAtom * func;
  1634. IHqlExpression * record = ::queryRecord(target.queryType());
  1635. HqlExprArray args;
  1636. args.append(*createSerializer(ctx, record, serializeForm, deserializerAtom));
  1637. if (target.expr->isDictionary())
  1638. {
  1639. if (serializeForm == internalAtom)
  1640. {
  1641. assertex(expr->isDictionary());
  1642. func = rtlDeserializeDictionaryId;
  1643. }
  1644. else if (serializeForm == diskAtom)
  1645. {
  1646. assertex(expr->isDataset());
  1647. func = rtlDeserializeDictionaryFromDatasetId;
  1648. StringBuffer lookupHelperName;
  1649. buildDictionaryHashClass(record, lookupHelperName);
  1650. args.append(*createQuoted(lookupHelperName.str(), makeBoolType()));
  1651. }
  1652. else
  1653. throwUnexpected();
  1654. }
  1655. else
  1656. {
  1657. if (isGrouped(expr))
  1658. func = groupedDataset2RowsetXId;
  1659. else
  1660. func = dataset2RowsetXId;
  1661. }
  1662. args.append(*LINK(expr));
  1663. OwnedHqlExpr call = bindFunctionCall(func, args, target.queryType());
  1664. buildExprAssign(ctx, target, call);
  1665. }
  1666. void HqlCppTranslator::buildDeserializedDataset(BuildCtx & ctx, ITypeInfo * type, IHqlExpression * expr, CHqlBoundExpr & tgt, IAtom * serializeForm)
  1667. {
  1668. #ifdef _DEBUG
  1669. OwnedITypeInfo serializedType = getSerializedForm(type, serializeForm);
  1670. assertex(recordTypesMatch(expr->queryType(), serializedType));
  1671. #endif
  1672. ITypeInfo * const exprType = expr->queryType();
  1673. assertex(!hasLinkedRow(exprType));
  1674. CHqlBoundTarget target;
  1675. createTempFor(ctx, type, target, typemod_none, FormatLinkedDataset);
  1676. buildAssignDeserializedDataset(ctx, target, expr, serializeForm);
  1677. tgt.setFromTarget(target);
  1678. }
  1679. void HqlCppTranslator::ensureDatasetFormat(BuildCtx & ctx, ITypeInfo * type, CHqlBoundExpr & tgt, ExpressionFormat format)
  1680. {
  1681. IAtom * serializeForm = internalAtom; // The format of serialized expressions in memory must match the internal serialization format
  1682. ITypeInfo * tgtType = tgt.queryType();
  1683. switch (format)
  1684. {
  1685. case FormatStreamedDataset:
  1686. if (!hasStreamedModifier(tgtType))
  1687. {
  1688. ensureDatasetFormat(ctx, type, tgt, FormatLinkedDataset);
  1689. HqlExprArray args;
  1690. args.append(*tgt.getTranslatedExpr());
  1691. OwnedITypeInfo streamedType = setStreamedAttr(type, true);
  1692. OwnedHqlExpr call = bindFunctionCall(createRowStreamId, args, streamedType);
  1693. buildTempExpr(ctx, call, tgt);
  1694. return;
  1695. }
  1696. break;
  1697. case FormatBlockedDataset:
  1698. if (isArrayRowset(tgtType))
  1699. {
  1700. OwnedHqlExpr deserializedExpr = tgt.getTranslatedExpr();
  1701. LinkedHqlExpr savedCount = tgt.count;
  1702. assertex(!deserializedExpr->isDictionary());
  1703. buildSerializedDataset(ctx, deserializedExpr, tgt, serializeForm);
  1704. if (savedCount && !isFixedWidthDataset(deserializedExpr))
  1705. tgt.count.set(savedCount);
  1706. return;
  1707. }
  1708. break;
  1709. case FormatLinkedDataset:
  1710. if (!hasLinkCountedModifier(tgtType))
  1711. {
  1712. OwnedHqlExpr serializedExpr = tgt.getTranslatedExpr();
  1713. if (recordTypesMatch(type, tgtType))
  1714. {
  1715. //source is an array of rows, or a simple dataset that doesn't need any transformation
  1716. buildTempExpr(ctx, serializedExpr, tgt, FormatLinkedDataset);
  1717. }
  1718. else
  1719. buildDeserializedDataset(ctx, type, serializedExpr, tgt, serializeForm);
  1720. return;
  1721. }
  1722. break;
  1723. case FormatArrayDataset:
  1724. if (!isArrayRowset(tgtType))
  1725. {
  1726. OwnedHqlExpr serializedExpr = tgt.getTranslatedExpr();
  1727. buildDeserializedDataset(ctx, type, serializedExpr, tgt, serializeForm);
  1728. return;
  1729. }
  1730. break;
  1731. }
  1732. }
  1733. void HqlCppTranslator::buildDataset(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  1734. {
  1735. doBuildDataset(ctx, expr, tgt, format);
  1736. ensureDatasetFormat(ctx, expr->queryType(), tgt, format);
  1737. }
  1738. void HqlCppTranslator::doBuildDataset(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  1739. {
  1740. if (expr->isPure() && ctx.getMatchExpr(expr, tgt))
  1741. return;
  1742. /*
  1743. OwnedHqlExpr transformed = normalizeAnyDatasetAliases(expr);
  1744. if (transformed && (transformed != expr))
  1745. {
  1746. doBuildDataset(ctx, transformed, tgt, format);
  1747. ctx.associateExpr(expr, tgt);
  1748. return;
  1749. }
  1750. */
  1751. node_operator op = expr->getOperator();
  1752. switch (op)
  1753. {
  1754. case no_dataset_alias:
  1755. if (!expr->hasAttribute(_normalized_Atom))
  1756. {
  1757. OwnedHqlExpr uniqueChild = normalizeDatasetAlias(expr);
  1758. doBuildDataset(ctx, uniqueChild, tgt, format);
  1759. }
  1760. else
  1761. doBuildDataset(ctx, expr->queryChild(0), tgt, format);
  1762. return;
  1763. case no_alias:
  1764. doBuildExprAlias(ctx, expr, &tgt);
  1765. return;
  1766. case no_owned_ds:
  1767. buildTempExpr(ctx, expr, tgt);
  1768. return;
  1769. case no_fail:
  1770. doBuildStmtFail(ctx, expr->queryChild(1));
  1771. //fallthrough
  1772. case no_null:
  1773. {
  1774. tgt.count.setown(getSizetConstant(0));
  1775. tgt.length.setown(getSizetConstant(0));
  1776. IHqlExpression * record = expr->queryRecord();
  1777. Owned<ITypeInfo> type;
  1778. if (expr->isDictionary())
  1779. type.setown(makeDictionaryType(makeRowType(record->getType())));
  1780. else
  1781. type.setown(makeTableType(makeRowType(record->getType())));
  1782. if ((format == FormatLinkedDataset) || (format == FormatArrayDataset) || expr->isDictionary())
  1783. type.setown(setLinkCountedAttr(type, true));
  1784. tgt.expr.setown(createValue(no_nullptr, makeReferenceModifier(type.getClear())));
  1785. return;
  1786. }
  1787. case no_translated:
  1788. expandTranslated(expr, tgt);
  1789. return;
  1790. case no_select:
  1791. {
  1792. if (isMultiLevelDatasetSelector(expr, false))
  1793. break;
  1794. Owned<IReferenceSelector> selected = buildReference(ctx, expr);
  1795. selected->get(ctx, tgt);
  1796. return;
  1797. }
  1798. case no_libraryinput:
  1799. if (!buildExprInCorrectContext(ctx, expr, tgt, false))
  1800. throwUnexpected();
  1801. return;
  1802. case no_call:
  1803. case no_externalcall:
  1804. buildTempExpr(ctx, expr, tgt);
  1805. return;
  1806. case no_newaggregate:
  1807. if (canAssignInline(&ctx, expr))
  1808. {
  1809. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  1810. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  1811. Owned<IReferenceSelector> createdRef = createReferenceSelector(rowBuilder);
  1812. BuildCtx subctx(ctx);
  1813. subctx.addGroup();
  1814. doBuildRowAssignAggregate(subctx, createdRef, expr);
  1815. finalizeTempRow(ctx, tempRow, rowBuilder);
  1816. convertBoundRowToDataset(ctx, tgt, tempRow, format);
  1817. return;
  1818. }
  1819. break;
  1820. case no_id2blob:
  1821. doBuildExprIdToBlob(ctx, expr, tgt);
  1822. return;
  1823. case no_rows:
  1824. {
  1825. if (!buildExprInCorrectContext(ctx, expr, tgt, false))
  1826. throwError(HQLERR_RowsUsedOutsideContext);
  1827. return;
  1828. }
  1829. case no_limit:
  1830. if (expr->hasAttribute(skipAtom) || expr->hasAttribute(onFailAtom))
  1831. break;
  1832. doBuildDatasetLimit(ctx, expr, tgt, format);
  1833. return;
  1834. case no_compound_childread:
  1835. case no_compound_childnormalize:
  1836. case no_compound_childaggregate:
  1837. case no_compound_selectnew:
  1838. case no_compound_inline:
  1839. case no_distributed:
  1840. case no_preservemeta:
  1841. case no_sorted:
  1842. case no_nofold:
  1843. case no_nohoist:
  1844. case no_section:
  1845. case no_sectioninput:
  1846. buildDataset(ctx, expr->queryChild(0), tgt, format);
  1847. return;
  1848. case no_forcegraph:
  1849. #ifdef _DEBUG
  1850. throwUnexpected();
  1851. #endif
  1852. buildDataset(ctx, expr->queryChild(0), tgt, format);
  1853. return;
  1854. case no_getgraphresult:
  1855. doBuildExprGetGraphResult(ctx, expr, tgt, format);
  1856. return;
  1857. case no_getresult:
  1858. case no_workunit_dataset:
  1859. if (!isGrouped(expr))
  1860. {
  1861. doBuildExprGetResult(ctx, expr, tgt);
  1862. return;
  1863. }
  1864. break;
  1865. case no_skip:
  1866. {
  1867. buildStmt(ctx, expr);
  1868. OwnedHqlExpr null = createNullExpr(expr);
  1869. buildDataset(ctx, null, tgt, format);
  1870. return;
  1871. }
  1872. case no_serialize:
  1873. {
  1874. IHqlExpression * deserialized = expr->queryChild(0);
  1875. IAtom * serializeForm = expr->queryChild(1)->queryName();
  1876. if (isDummySerializeDeserialize(expr))
  1877. doBuildDataset(ctx, deserialized->queryChild(0), tgt, format);
  1878. else if (!typeRequiresDeserialization(deserialized->queryType(), serializeForm))
  1879. //Optimize creating a serialized version of a dataset if the record is the same serialized and unserialized
  1880. buildDataset(ctx, deserialized, tgt, FormatNatural);
  1881. else
  1882. buildSerializedDataset(ctx, deserialized, tgt, serializeForm);
  1883. return;
  1884. }
  1885. case no_deserialize:
  1886. {
  1887. IHqlExpression * serialized = expr->queryChild(0);
  1888. IAtom * serializeForm = expr->queryChild(2)->queryName();
  1889. if (isDummySerializeDeserialize(expr))
  1890. doBuildDataset(ctx, serialized->queryChild(0), tgt, format);
  1891. else if (!typeRequiresDeserialization(expr->queryType(), serializeForm))
  1892. //Optimize creating a deserialized version of a dataset if the record is the same serialized and unserialized
  1893. buildDataset(ctx, serialized, tgt, FormatNatural);
  1894. else
  1895. buildDeserializedDataset(ctx, expr->queryType(), serialized, tgt, serializeForm);
  1896. return;
  1897. }
  1898. case no_datasetfromrow:
  1899. {
  1900. IHqlExpression * row = expr->queryChild(0);
  1901. if (isAlwaysActiveRow(row) && (format == FormatNatural))
  1902. {
  1903. Owned<IReferenceSelector> selector = buildActiveRow(ctx, row);
  1904. BuildCtx groupctx(ctx);
  1905. groupctx.addGroup();
  1906. BoundRow * bound = bindSelectorAsRootRow(groupctx, selector, row);
  1907. convertBoundRowToDataset(groupctx, tgt, bound, format);
  1908. tgt.count.setown(getSizetConstant(1));
  1909. ctx.associateExpr(expr, tgt);
  1910. return;
  1911. }
  1912. break;
  1913. }
  1914. case no_inlinetable:
  1915. if (doBuildDatasetInlineTable(ctx, expr, tgt, format))
  1916. return;
  1917. break;
  1918. case no_compound:
  1919. {
  1920. buildStmt(ctx, expr->queryChild(0));
  1921. buildDataset(ctx, expr->queryChild(1), tgt, format);
  1922. return;
  1923. }
  1924. case no_createdictionary:
  1925. {
  1926. if (isConstantDictionary(expr))
  1927. {
  1928. if (doBuildDictionaryInlineTable(ctx, expr, tgt, format))
  1929. return;
  1930. }
  1931. IHqlExpression * record = expr->queryRecord();
  1932. IHqlExpression * dataset = expr->queryChild(0);
  1933. Owned<IHqlCppDatasetBuilder> builder = createLinkedDictionaryBuilder(record);
  1934. builder->buildDeclare(ctx);
  1935. buildDatasetAssign(ctx, builder, dataset);
  1936. builder->buildFinish(ctx, tgt);
  1937. ctx.associateExpr(expr, tgt);
  1938. return;
  1939. }
  1940. case no_if:
  1941. if (::canEvaluateInline(&ctx, expr->queryChild(1)) && ::canEvaluateInline(&ctx, expr->queryChild(2)))
  1942. {
  1943. buildTempExpr(ctx, expr, tgt, format);
  1944. return;
  1945. }
  1946. }
  1947. if (expr->isDictionary())
  1948. {
  1949. buildTempExpr(ctx, expr, tgt, format);
  1950. return;
  1951. }
  1952. bool singleRow = hasSingleRow(expr);
  1953. bool useTempRow = singleRow && canAssignInline(&ctx, expr) && (format != FormatLinkedDataset) && (format != FormatArrayDataset);
  1954. //Conditional row assignment if variable length causes offset to be recalculated outside of the if()
  1955. //if (useTempRow && (op == no_if) && isVariableSizeRecord(expr->queryRecord()))
  1956. // useTempRow = false;
  1957. if (useTempRow)
  1958. {
  1959. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  1960. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  1961. Owned<IHqlCppDatasetBuilder> builder = createSingleRowTempDatasetBuilder(expr->queryRecord(), rowBuilder);
  1962. builder->buildDeclare(ctx);
  1963. buildDatasetAssign(ctx, builder, expr);
  1964. //builder->buildFinish(ctx, tempTarget);
  1965. finalizeTempRow(ctx, tempRow, rowBuilder);
  1966. convertBoundRowToDataset(ctx, tgt, tempRow, format);
  1967. }
  1968. else
  1969. {
  1970. if (!canAssignInline(&ctx, expr))
  1971. {
  1972. CHqlBoundTarget tempTarget;
  1973. createTempFor(ctx, expr->queryType(), tempTarget, typemod_none, format);
  1974. buildDatasetAssign(ctx, tempTarget, expr);
  1975. tgt.setFromTarget(tempTarget);
  1976. //buildTempExpr(ctx, expr, tgt); // can't use this because it causes recursion on no_selectnth
  1977. }
  1978. else
  1979. {
  1980. Owned<IHqlCppDatasetBuilder> builder;
  1981. IHqlExpression * record = expr->queryRecord();
  1982. IAtom * serializeForm = internalAtom; // The format of serialized expressions in memory must match the internal serialization format
  1983. OwnedHqlExpr serializedRecord = getSerializedForm(record, serializeForm);
  1984. if (format == FormatNatural)
  1985. {
  1986. if (record != serializedRecord)
  1987. ensureContextAvailable(ctx);
  1988. if (!ctx.queryMatchExpr(codeContextMarkerExpr))
  1989. {
  1990. if (record != serializedRecord)
  1991. throwError(HQLERR_LinkedDatasetNoContext);
  1992. format = FormatBlockedDataset;
  1993. }
  1994. else
  1995. {
  1996. format = FormatLinkedDataset;
  1997. }
  1998. }
  1999. else if (record != serializedRecord)
  2000. format = FormatLinkedDataset; // Have to serialize it later - otherwise it won't be compatible
  2001. if (format == FormatLinkedDataset || format == FormatArrayDataset)
  2002. {
  2003. IHqlExpression * choosenLimit = NULL;
  2004. if ((op == no_choosen) && !isChooseNAllLimit(expr->queryChild(1)) && !queryRealChild(expr, 2))
  2005. {
  2006. choosenLimit = expr->queryChild(1);
  2007. expr = expr->queryChild(0);
  2008. }
  2009. //MORE: Extract limit and choosen and pass as parameters
  2010. builder.setown(createLinkedDatasetBuilder(record, choosenLimit));
  2011. }
  2012. else if ((op == no_choosen) && !isChooseNAllLimit(expr->queryChild(1)) && !queryRealChild(expr, 2))
  2013. {
  2014. //Build a limited builder - it is likely to be just as efficient, and often much more e.g., choosen(a+b, n)
  2015. builder.setown(createChoosenDatasetBuilder(serializedRecord, expr->queryChild(1)));
  2016. expr = expr->queryChild(0);
  2017. }
  2018. else
  2019. builder.setown(createBlockedDatasetBuilder(serializedRecord));
  2020. builder->buildDeclare(ctx);
  2021. buildDatasetAssign(ctx, builder, expr);
  2022. builder->buildFinish(ctx, tgt);
  2023. }
  2024. }
  2025. if (singleRow)
  2026. tgt.count.setown(getSizetConstant(1));
  2027. else if (op == no_inlinetable)
  2028. {
  2029. IHqlExpression * transforms = expr->queryChild(0);
  2030. if (!transformListContainsSkip(transforms))
  2031. tgt.count.setown(getSizetConstant(transforms->numChildren()));
  2032. }
  2033. ctx.associateExpr(expr, tgt);
  2034. }
  2035. //---------------------------------------------------------------------------
  2036. // Dataset assignment - to temp
  2037. static bool isWorthAssigningDirectly(BuildCtx & ctx, const CHqlBoundTarget & /*target*/, IHqlExpression * expr)
  2038. {
  2039. //target parameter is currently unused - it should be used to check that linkcounted attributes match etc.
  2040. if (expr->getOperator() == no_null)
  2041. return false;
  2042. //A poor approximation. Could also include function calls if the is-link-counted matches.
  2043. return ::canEvaluateInline(&ctx, expr);
  2044. }
  2045. void HqlCppTranslator::buildDatasetAssign(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  2046. {
  2047. node_operator op = expr->getOperator();
  2048. switch (op)
  2049. {
  2050. case no_fail:
  2051. doBuildStmtFail(ctx, expr->queryChild(1));
  2052. return;
  2053. case no_call:
  2054. case no_externalcall:
  2055. doBuildCall(ctx, &target, expr, NULL);
  2056. return;
  2057. case no_getgraphresult:
  2058. doBuildAssignGetGraphResult(ctx, target, expr);
  2059. return;
  2060. case no_workunit_dataset:
  2061. case no_getresult:
  2062. buildExprAssign(ctx, target, expr);
  2063. return;
  2064. case no_null:
  2065. {
  2066. CHqlBoundExpr bound;
  2067. buildDataset(ctx, expr, bound, isArrayRowset(target.queryType()) ? FormatLinkedDataset : FormatBlockedDataset);
  2068. if (hasWrapperModifier(target.queryType()) && hasLinkCountedModifier(target.queryType()))
  2069. {
  2070. OwnedHqlExpr complex = bound.getComplexExpr();
  2071. ctx.addAssign(target.expr, complex);
  2072. }
  2073. else
  2074. {
  2075. if (target.count) ctx.addAssign(target.count, bound.count);
  2076. if (target.length) ctx.addAssign(target.length, bound.length);
  2077. ctx.addAssign(target.expr, bound.expr);
  2078. }
  2079. return;
  2080. }
  2081. case no_inlinetable:
  2082. {
  2083. //This will typically generate a loop. If few items then it is more efficient to expand the assigns/clones out.
  2084. if (options.canLinkConstantRows || (expr->queryChild(0)->numChildren() > INLINE_TABLE_EXPAND_LIMIT))
  2085. {
  2086. CHqlBoundExpr bound;
  2087. if (doBuildDatasetInlineTable(ctx, expr, bound, FormatNatural))
  2088. {
  2089. OwnedHqlExpr translated = bound.getTranslatedExpr();
  2090. buildDatasetAssign(ctx, target, translated);
  2091. return;
  2092. }
  2093. }
  2094. break;
  2095. }
  2096. case no_alias:
  2097. {
  2098. CHqlBoundExpr bound;
  2099. buildDataset(ctx, expr, bound, FormatNatural);
  2100. OwnedHqlExpr translated = bound.getTranslatedExpr();
  2101. buildDatasetAssign(ctx, target, translated);
  2102. return;
  2103. }
  2104. case no_owned_ds:
  2105. {
  2106. ITypeInfo * targetType = target.queryType();
  2107. if (hasLinkCountedModifier(targetType) && hasWrapperModifier(targetType))
  2108. {
  2109. CHqlBoundExpr bound;
  2110. buildDataset(ctx, expr->queryChild(0), bound, FormatLinkedDataset);
  2111. OwnedHqlExpr compound = createValue(no_complex, bound.expr->getType(), LINK(bound.count), LINK(bound.expr));
  2112. ctx.addAssign(target.expr, compound);
  2113. return;
  2114. }
  2115. break;
  2116. }
  2117. case no_compound:
  2118. {
  2119. buildStmt(ctx, expr->queryChild(0));
  2120. buildDatasetAssign(ctx, target, expr->queryChild(1));
  2121. return;
  2122. }
  2123. case no_compound_childread:
  2124. case no_compound_childnormalize:
  2125. case no_compound_childaggregate:
  2126. case no_compound_selectnew:
  2127. case no_compound_inline:
  2128. case no_distributed:
  2129. case no_preservemeta:
  2130. case no_sorted:
  2131. case no_nofold:
  2132. case no_nohoist:
  2133. case no_section:
  2134. case no_sectioninput:
  2135. buildDatasetAssign(ctx, target, expr->queryChild(0));
  2136. return;
  2137. case no_if:
  2138. //Only generate conditional assignments to a target if both source and target require no temporary.
  2139. if (expr->isDictionary() || (::canEvaluateInline(&ctx, expr->queryChild(1)) && ::canEvaluateInline(&ctx, expr->queryChild(2))))
  2140. //The following line would be better, but it needs improvements to the cse generation first, otherwise some examples get worse.
  2141. //if (expr->isDictionary() || (isWorthAssigningDirectly(ctx, target, expr->queryChild(1)) || isWorthAssigningDirectly(ctx, target, expr->queryChild(2))))
  2142. {
  2143. buildDatasetAssignIf(ctx, target, expr);
  2144. return;
  2145. }
  2146. break;
  2147. case no_chooseds:
  2148. if (expr->isDictionary())
  2149. {
  2150. buildDatasetAssignChoose(ctx, target, expr);
  2151. return;
  2152. }
  2153. break;
  2154. case no_serialize:
  2155. {
  2156. IHqlExpression * deserialized = expr->queryChild(0);
  2157. IAtom * serializeForm = expr->queryChild(1)->queryName();
  2158. if (isDummySerializeDeserialize(expr))
  2159. buildDatasetAssign(ctx, target, deserialized->queryChild(0));
  2160. else if (!typeRequiresDeserialization(deserialized->queryType(), serializeForm))
  2161. buildDatasetAssign(ctx, target, deserialized);
  2162. else
  2163. buildAssignSerializedDataset(ctx, target, deserialized, serializeForm);
  2164. return;
  2165. }
  2166. case no_deserialize:
  2167. {
  2168. IHqlExpression * serialized = expr->queryChild(0);
  2169. IAtom * serializeForm = expr->queryChild(2)->queryName();
  2170. if (isDummySerializeDeserialize(expr))
  2171. buildDatasetAssign(ctx, target, serialized->queryChild(0));
  2172. else if (!typeRequiresDeserialization(expr->queryType(), serializeForm))
  2173. buildDatasetAssign(ctx, target, serialized);
  2174. else
  2175. buildAssignDeserializedDataset(ctx, target, serialized, serializeForm);
  2176. return;
  2177. }
  2178. case no_select:
  2179. {
  2180. bool isNew;
  2181. IHqlExpression * ds = querySelectorDataset(expr, isNew);
  2182. if (!isNew || ds->isDatarow())
  2183. {
  2184. Owned<IReferenceSelector> selected = buildReference(ctx, expr);
  2185. selected->assignTo(ctx, target);
  2186. return;
  2187. }
  2188. break;
  2189. }
  2190. case no_typetransfer:
  2191. {
  2192. IHqlExpression * child = expr->queryChild(0);
  2193. if (expr->isDataset() && child->isDataset())
  2194. {
  2195. //Special case no-op type transfers and assignment from a call returning unknown-type dataset
  2196. if (!recordTypesMatch(expr, child) &&
  2197. !(child->getOperator() == no_externalcall && recordTypesMatch(child, queryNullRecord())))
  2198. {
  2199. CHqlBoundExpr bound;
  2200. buildDataset(ctx, child, bound, FormatNatural);
  2201. ITypeInfo * newType = cloneModifiers(bound.expr->queryType(), expr->queryType());
  2202. bound.expr.setown(createValue(no_typetransfer, newType, LINK(bound.expr)));
  2203. OwnedHqlExpr translated = bound.getTranslatedExpr();
  2204. buildDatasetAssign(ctx, target, translated);
  2205. }
  2206. else
  2207. buildDatasetAssign(ctx, target, child);
  2208. return;
  2209. }
  2210. break;
  2211. }
  2212. case no_createdictionary:
  2213. {
  2214. if (isConstantDictionary(expr))
  2215. {
  2216. CHqlBoundExpr temp;
  2217. if (doBuildDictionaryInlineTable(ctx, expr, temp, FormatNatural))
  2218. {
  2219. OwnedHqlExpr translated = temp.getTranslatedExpr();
  2220. buildDatasetAssign(ctx, target, translated);
  2221. return;
  2222. }
  2223. }
  2224. IHqlExpression * record = expr->queryRecord();
  2225. Owned<IHqlCppDatasetBuilder> builder = createLinkedDictionaryBuilder(record);
  2226. builder->buildDeclare(ctx);
  2227. buildDatasetAssign(ctx, builder, expr->queryChild(0));
  2228. builder->buildFinish(ctx, target);
  2229. return;
  2230. }
  2231. }
  2232. if (!canAssignInline(&ctx, expr) && (op != no_translated))
  2233. {
  2234. buildAssignChildDataset(ctx, target, expr);
  2235. return;
  2236. }
  2237. ITypeInfo * to = target.queryType();
  2238. ITypeInfo * exprType = expr->queryType();
  2239. bool targetOutOfLine = isArrayRowset(to);
  2240. switch (op)
  2241. {
  2242. case no_limit:
  2243. assertex(!expr->hasAttribute(skipAtom) && !expr->hasAttribute(onFailAtom));
  2244. //Do the limit check as a post test.
  2245. //It means we may read more records than we need to, but the code is inline, and the code is generally much better.
  2246. if (target.count)
  2247. {
  2248. buildDatasetAssign(ctx, target, expr->queryChild(0));
  2249. CHqlBoundExpr bound;
  2250. bound.setFromTarget(target);
  2251. doBuildCheckDatasetLimit(ctx, expr, bound);
  2252. return;
  2253. }
  2254. break;
  2255. case no_translated:
  2256. {
  2257. bool sourceOutOfLine = isArrayRowset(exprType);
  2258. if (sourceOutOfLine != targetOutOfLine && !hasStreamedModifier(exprType))
  2259. {
  2260. IAtom * serializeFormat = internalAtom; // The format of serialized expressions in memory must match the internal serialization format
  2261. OwnedITypeInfo serializedSourceType = getSerializedForm(exprType, serializeFormat);
  2262. OwnedITypeInfo serializedTargetType = getSerializedForm(to, serializeFormat);
  2263. if (queryUnqualifiedType(serializedSourceType) == queryUnqualifiedType(serializedTargetType))
  2264. {
  2265. if (targetOutOfLine)
  2266. {
  2267. buildAssignDeserializedDataset(ctx, target, expr, serializeFormat);
  2268. }
  2269. else
  2270. {
  2271. buildAssignSerializedDataset(ctx, target, expr, serializeFormat);
  2272. }
  2273. return;
  2274. }
  2275. }
  2276. break;
  2277. }
  2278. }
  2279. if (recordTypesMatch(to, exprType))
  2280. {
  2281. switch (op)
  2282. {
  2283. case no_rows:
  2284. {
  2285. CHqlBoundExpr bound;
  2286. buildDataset(ctx, expr, bound, FormatLinkedDataset);
  2287. OwnedHqlExpr translated = bound.getTranslatedExpr();
  2288. buildDatasetAssign(ctx, target, translated);
  2289. return;
  2290. }
  2291. case no_select:
  2292. {
  2293. bool isNew;
  2294. IHqlExpression * ds = querySelectorDataset(expr, isNew);
  2295. if (isNew && !ds->isDatarow())
  2296. break;
  2297. }
  2298. //fall through
  2299. case no_translated:
  2300. case no_null:
  2301. case no_id2blob:
  2302. {
  2303. IIdAtom * func = NULL;
  2304. if (!isArrayRowset(to))
  2305. {
  2306. if (!isArrayRowset(exprType))
  2307. func = dataset2DatasetXId;
  2308. }
  2309. else if (hasLinkCountedModifier(to))
  2310. {
  2311. if (hasLinkCountedModifier(exprType))
  2312. {
  2313. CHqlBoundExpr bound;
  2314. buildDataset(ctx, expr, bound, FormatLinkedDataset);
  2315. assertex(bound.count && bound.expr);
  2316. if (hasWrapperModifier(to))
  2317. {
  2318. //assigns to count and rows members
  2319. StringBuffer s;
  2320. generateExprCpp(s, target.expr);
  2321. s.append(".set(");
  2322. generateExprCpp(s, bound.count);
  2323. s.append(",");
  2324. generateExprCpp(s, bound.expr);
  2325. s.append(");");
  2326. ctx.addQuoted(s);
  2327. }
  2328. else
  2329. {
  2330. ctx.addAssign(target.count, bound.count);
  2331. HqlExprArray args;
  2332. args.append(*LINK(bound.expr));
  2333. OwnedHqlExpr call = bindTranslatedFunctionCall(linkRowsetId, args);
  2334. ctx.addAssign(target.expr, call);
  2335. }
  2336. return;
  2337. }
  2338. }
  2339. if (func)
  2340. {
  2341. HqlExprArray args;
  2342. args.append(*LINK(expr));
  2343. OwnedHqlExpr call = bindFunctionCall(func, args);
  2344. buildExprAssign(ctx, target, call);
  2345. return;
  2346. }
  2347. }
  2348. }
  2349. }
  2350. IHqlExpression * record = ::queryRecord(to);
  2351. Owned<IHqlCppDatasetBuilder> builder;
  2352. if (targetOutOfLine)
  2353. {
  2354. if (isDictionaryType(target.queryType()))
  2355. {
  2356. builder.setown(createLinkedDictionaryBuilder(record));
  2357. }
  2358. else
  2359. {
  2360. IHqlExpression * choosenLimit = NULL;
  2361. if ((op == no_choosen) && !isChooseNAllLimit(expr->queryChild(1)) && !queryRealChild(expr, 2))
  2362. {
  2363. choosenLimit = expr->queryChild(1);
  2364. expr = expr->queryChild(0);
  2365. }
  2366. builder.setown(createLinkedDatasetBuilder(record, choosenLimit));
  2367. }
  2368. }
  2369. else
  2370. builder.setown(createBlockedDatasetBuilder(record));
  2371. builder->buildDeclare(ctx);
  2372. buildDatasetAssign(ctx, builder, expr);
  2373. builder->buildFinish(ctx, target);
  2374. }
  2375. //---------------------------------------------------------------------------
  2376. void HqlCppTranslator::doBuildCheckDatasetLimit(BuildCtx & ctx, IHqlExpression * expr, const CHqlBoundExpr & bound)
  2377. {
  2378. IHqlExpression * record = expr->queryRecord();
  2379. IHqlExpression * limit = expr->queryChild(1);
  2380. OwnedHqlExpr test;
  2381. if (!bound.count && bound.length && isFixedRecordSize(record))
  2382. {
  2383. OwnedHqlExpr size = bound.length->queryValue() ? LINK(bound.length) : createTranslated(bound.length);
  2384. OwnedHqlExpr maxSize = createValue(no_mul, LINK(sizetType), ensureExprType(limit, sizetType), getSizetConstant(getFixedRecordSize(record)));
  2385. test.setown(createBoolExpr(no_gt, ensureExprType(size, sizetType), LINK(maxSize)));
  2386. }
  2387. else
  2388. {
  2389. OwnedHqlExpr count = getBoundCount(bound);
  2390. OwnedHqlExpr translatedCount = count->queryValue() ? LINK(count) : createTranslated(count);
  2391. test.setown(createBoolExpr(no_gt, ensureExprType(translatedCount, sizetType), ensureExprType(limit, sizetType)));
  2392. }
  2393. OwnedHqlExpr folded = foldHqlExpression(test);
  2394. LinkedHqlExpr fail = queryRealChild(expr, 2);
  2395. if (folded->queryValue())
  2396. {
  2397. if (!folded->queryValue()->getBoolValue())
  2398. return;
  2399. StringBuffer failMessageText;
  2400. if (fail)
  2401. {
  2402. OwnedHqlExpr failMessage = getFailMessage(fail, true);
  2403. if (failMessage && failMessage->queryValue())
  2404. failMessage->queryValue()->getStringValue(failMessageText);
  2405. }
  2406. if (failMessageText.length())
  2407. WARNING1(HQLWRN_LimitAlwaysExceededX, failMessageText.str());
  2408. else
  2409. WARNING(HQLWRN_LimitAlwaysExceeded);
  2410. }
  2411. if (!fail)
  2412. fail.setown(createFailAction("Limit exceeded", limit, NULL, queryCurrentActivityId(ctx)));
  2413. BuildCtx subctx(ctx);
  2414. buildFilter(subctx, folded);
  2415. buildStmt(subctx, fail);
  2416. }
  2417. void HqlCppTranslator::doBuildDatasetLimit(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  2418. {
  2419. buildDataset(ctx, expr->queryChild(0), tgt, format);
  2420. doBuildCheckDatasetLimit(ctx, expr, tgt);
  2421. }
  2422. class ConstantRow : public CInterface
  2423. {
  2424. public:
  2425. ConstantRow(IHqlExpression * _transform, IHqlExpression * _boundRow) : transform(_transform), boundRow(_boundRow)
  2426. {
  2427. }
  2428. public:
  2429. IHqlExpression * transform;
  2430. LinkedHqlExpr boundRow;
  2431. };
  2432. class ConstantRowArray : public CIArrayOf<ConstantRow> {};
  2433. bool HqlCppTranslator::buildConstantRows(ConstantRowArray & boundRows, IHqlExpression * transforms)
  2434. {
  2435. HqlExprArray rows;
  2436. ForEachChild(row, transforms)
  2437. {
  2438. OwnedHqlExpr constRow = createConstantRowExpr(transforms->queryChild(row));
  2439. if (!constRow || !canGenerateStringInline(constRow->queryType()->getSize()))
  2440. return false;
  2441. rows.append(*constRow.getClear());
  2442. }
  2443. ForEachItemIn(i, rows)
  2444. {
  2445. IHqlExpression * transform = transforms->queryChild(i);
  2446. CHqlBoundExpr bound;
  2447. buildConstRow(transform->queryRecord(), &rows.item(i), bound);
  2448. boundRows.append(*new ConstantRow(transform, bound.expr));
  2449. }
  2450. return true;
  2451. }
  2452. bool HqlCppTranslator::doBuildDatasetInlineTable(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  2453. {
  2454. if (!options.generateStaticInlineTables)
  2455. return false;
  2456. IHqlExpression * transforms = expr->queryChild(0);
  2457. IHqlExpression * record = expr->queryRecord();
  2458. if (transforms->numChildren() == 0)
  2459. {
  2460. OwnedHqlExpr null = createDataset(no_null, LINK(record));
  2461. buildDataset(ctx, null, tgt, format);
  2462. return true;
  2463. }
  2464. BuildCtx declareCtx(*code, literalAtom);
  2465. //Remove unique id when checking for constant datasets already generated
  2466. OwnedHqlExpr exprKey = removeAttribute(expr, _uid_Atom);
  2467. if (declareCtx.getMatchExpr(exprKey, tgt))
  2468. return true;
  2469. ConstantRowArray boundRows;
  2470. if (!buildConstantRows(boundRows, transforms))
  2471. return false;
  2472. Owned<ITypeInfo> rowType = makeConstantModifier(makeReferenceModifier(makeRowType(LINK(queryRecordType(expr->queryType())))));
  2473. HqlExprArray args;
  2474. ForEachItemIn(i, boundRows)
  2475. args.append(*LINK(boundRows.item(i).boundRow));
  2476. OwnedHqlExpr values = createValue(no_list, makeSetType(LINK(rowType)), args);
  2477. unsigned maxRows = values->numChildren();
  2478. Owned<ITypeInfo> declareType = makeConstantModifier(makeArrayType(LINK(rowType), maxRows));
  2479. OwnedITypeInfo rowsType = makeOutOfLineModifier(makeTableType(LINK(rowType)));
  2480. if (options.canLinkConstantRows)
  2481. rowsType.setown(setLinkCountedAttr(rowsType, true));
  2482. OwnedHqlExpr table = declareCtx.getTempDeclare(declareType, values);
  2483. if (options.spanMultipleCpp)
  2484. {
  2485. BuildCtx protoctx(*code, mainprototypesAtom);
  2486. protoctx.addDeclareExternal(table);
  2487. }
  2488. tgt.count.setown(getSizetConstant(maxRows));
  2489. tgt.expr.setown(createValue(no_typetransfer, LINK(rowsType), LINK(table)));
  2490. declareCtx.associateExpr(exprKey, tgt);
  2491. return true;
  2492. }
  2493. //---------------------------------------------------------------------------------------------------------------------
  2494. //The code generator uses the the run time library code used to build dictionaries to try and ensure they stay compatible.
  2495. //
  2496. //The following classes allow IHqlExpressions to be used with those external classes. A ConstantRow * is used where a
  2497. //row would normally be used at runtime.
  2498. //This class provides the minimal functionality for the interface required to call the dictionary builder class
  2499. class EclccEngineRowAllocator : public CInterfaceOf<IEngineRowAllocator>
  2500. {
  2501. public:
  2502. virtual byte * * createRowset(unsigned _numItems) { return (byte * *)malloc(_numItems * sizeof(byte *)); }
  2503. virtual byte * * linkRowset(byte * * rowset) { throwUnexpected(); }
  2504. virtual void releaseRowset(unsigned count, byte * * rowset) { free(rowset); }
  2505. virtual byte * * appendRowOwn(byte * * rowset, unsigned newRowCount, void * row)
  2506. {
  2507. byte * * expanded = reallocRows(rowset, newRowCount-1, newRowCount);
  2508. expanded[newRowCount-1] = (byte *)row;
  2509. return expanded;
  2510. }
  2511. virtual byte * * reallocRows(byte * * rowset, unsigned oldRowCount, unsigned newRowCount)
  2512. {
  2513. return (byte * *)realloc(rowset, newRowCount * sizeof(byte *));
  2514. }
  2515. virtual void * createRow() { throwUnexpected(); }
  2516. virtual void releaseRow(const void * row) { } // can occur if a row is removed from a dictionary.
  2517. virtual void * linkRow(const void * row) { return const_cast<void *>(row); } // can occur if a dictionary is resized.
  2518. //Used for dynamically sizing rows.
  2519. virtual void * createRow(size32_t & allocatedSize) { throwUnexpected(); }
  2520. virtual void * resizeRow(size32_t newSize, void * row, size32_t & size) { throwUnexpected(); }
  2521. virtual void * finalizeRow(size32_t newSize, void * row, size32_t oldSize) { throwUnexpected(); }
  2522. virtual IOutputMetaData * queryOutputMeta() { return NULL; }
  2523. virtual unsigned queryActivityId() { return 0; }
  2524. virtual StringBuffer &getId(StringBuffer & out) { return out; }
  2525. virtual IOutputRowSerializer *createDiskSerializer(ICodeContext *ctx = NULL) { throwUnexpected(); }
  2526. virtual IOutputRowDeserializer *createDiskDeserializer(ICodeContext *ctx) { throwUnexpected(); }
  2527. virtual IOutputRowSerializer *createInternalSerializer(ICodeContext *ctx = NULL) { throwUnexpected(); }
  2528. virtual IOutputRowDeserializer *createInternalDeserializer(ICodeContext *ctx) { throwUnexpected(); }
  2529. virtual IEngineRowAllocator *createChildRowAllocator(const RtlTypeInfo *type) { throwUnexpected(); }
  2530. };
  2531. //Use a (constant) transform to map selectors of the form queryActiveTableSelector().field
  2532. static IHqlExpression * mapExprViaTransform(IHqlExpression * transform, IHqlExpression * expr)
  2533. {
  2534. NewProjectMapper2 mapper;
  2535. mapper.setMapping(transform);
  2536. return mapper.expandFields(expr, queryActiveTableSelector(), queryActiveTableSelector(), queryActiveTableSelector());
  2537. }
  2538. //Implement hash - constructor parameter is the hash expression
  2539. class EclccCHash : implements IHash
  2540. {
  2541. public:
  2542. EclccCHash(IHqlExpression * _hashExpr) : hashExpr(_hashExpr) {}
  2543. virtual unsigned hash(const void *data)
  2544. {
  2545. const ConstantRow * row = reinterpret_cast<const ConstantRow *>(data);
  2546. OwnedHqlExpr expanded = mapExprViaTransform(row->transform, hashExpr);
  2547. OwnedHqlExpr folded = foldHqlExpression(expanded);
  2548. assertex(folded->queryValue());
  2549. return (unsigned)getIntValue(folded, 0);
  2550. }
  2551. protected:
  2552. LinkedHqlExpr hashExpr;
  2553. };
  2554. // implement compare -the constructor parameter is the list of fields to compare
  2555. class EclccCCompare : implements ICompare
  2556. {
  2557. public:
  2558. EclccCCompare(IHqlExpression * _sortorder) : sortorder(_sortorder) {}
  2559. virtual int docompare(const void * _left,const void * _right) const
  2560. {
  2561. const ConstantRow * left = reinterpret_cast<const ConstantRow *>(_left);
  2562. const ConstantRow * right = reinterpret_cast<const ConstantRow *>(_right);
  2563. OwnedHqlExpr expandedLeft = mapExprViaTransform(left->transform, sortorder);
  2564. OwnedHqlExpr expandedRight = mapExprViaTransform(right->transform, sortorder);
  2565. OwnedHqlExpr order = createValue(no_order, LINK(signedType), expandedLeft.getClear(), expandedRight.getClear());
  2566. OwnedHqlExpr folded = foldHqlExpression(order);
  2567. assertex(folded->queryValue());
  2568. return (int)getIntValue(folded, 0);
  2569. }
  2570. protected:
  2571. LinkedHqlExpr sortorder;
  2572. };
  2573. //The dictionary information class - the hash lookup versions are not implemented
  2574. class EclccHashLookupInfo : implements IHThorHashLookupInfo
  2575. {
  2576. public:
  2577. EclccHashLookupInfo(IHqlExpression * hashExpr, IHqlExpression * sortorder)
  2578. : hasher(hashExpr), comparer(sortorder)
  2579. {
  2580. }
  2581. virtual IHash * queryHash() { return &hasher; }
  2582. virtual ICompare * queryCompare() { return &comparer; }
  2583. virtual IHash * queryHashLookup() { throwUnexpected(); }
  2584. virtual ICompare * queryCompareLookup() { throwUnexpected(); }
  2585. protected:
  2586. EclccCHash hasher;
  2587. EclccCCompare comparer;
  2588. };
  2589. void HqlCppTranslator::createInlineDictionaryRows(HqlExprArray & args, ConstantRowArray & boundRows, IHqlExpression * keyRecord, IHqlExpression * nullRow)
  2590. {
  2591. //The code generator uses the the run time library code used to build dictionaries to try and ensure they stay compatible.
  2592. HqlExprArray keyedDictFields;
  2593. expandRecord(keyedDictFields, queryActiveTableSelector(), keyRecord);
  2594. OwnedHqlExpr keyedlist = createSortList(keyedDictFields);
  2595. OwnedHqlExpr hash = createValue(no_hash32, LINK(unsignedType), LINK(keyedlist));
  2596. //Estimate a good hash table size from the number of rows - otherwise the size can be more than double the number of rows
  2597. size32_t hashSize = (boundRows.ordinality() * 4 / 3) + 1;
  2598. EclccEngineRowAllocator rowsetAllocator;
  2599. EclccHashLookupInfo hasher(hash, keyedlist);
  2600. RtlLinkedDictionaryBuilder builder(&rowsetAllocator, &hasher, hashSize);
  2601. ForEachItemIn(i, boundRows)
  2602. builder.appendOwn(&boundRows.item(i));
  2603. unsigned size = builder.getcount();
  2604. ConstantRow * * rows = reinterpret_cast<ConstantRow * *>(builder.queryrows());
  2605. for (unsigned i=0; i < size; i++)
  2606. {
  2607. if (rows[i])
  2608. args.append(*LINK(rows[i]->boundRow));
  2609. else
  2610. args.append(*LINK(nullRow));
  2611. }
  2612. }
  2613. bool HqlCppTranslator::doBuildDictionaryInlineTable(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  2614. {
  2615. if (!options.generateStaticInlineTables || !options.canLinkConstantRows)
  2616. return false;
  2617. IHqlExpression * dataset = expr->queryChild(0);
  2618. assertex(dataset->getOperator() == no_inlinetable);
  2619. IHqlExpression * transforms = dataset->queryChild(0);
  2620. IHqlExpression * record = dataset->queryRecord();
  2621. if (transforms->numChildren() == 0)
  2622. {
  2623. OwnedHqlExpr null = createDictionary(no_null, LINK(record));
  2624. buildDataset(ctx, null, tgt, format);
  2625. return true;
  2626. }
  2627. BuildCtx declareCtx(*code, literalAtom);
  2628. //Remove unique id when checking for constant datasets already generated
  2629. OwnedHqlExpr exprNoUnique = removeAttribute(dataset, _uid_Atom);
  2630. OwnedHqlExpr exprKey = createAttribute(dictionaryAtom, exprNoUnique.getClear());
  2631. if (declareCtx.getMatchExpr(exprKey, tgt))
  2632. return true;
  2633. ConstantRowArray boundRows;
  2634. if (!buildConstantRows(boundRows, transforms))
  2635. return false;
  2636. OwnedHqlExpr keyRecord = getDictionaryKeyRecord(record);
  2637. Owned<ITypeInfo> rowType = makeConstantModifier(makeReferenceModifier(makeRowType(LINK(queryRecordType(expr->queryType())))));
  2638. OwnedHqlExpr nullExpr = createValue(no_nullptr, LINK(rowType));
  2639. HqlExprArray args;
  2640. try
  2641. {
  2642. createInlineDictionaryRows(args, boundRows, keyRecord, nullExpr);
  2643. }
  2644. catch (IException * e)
  2645. {
  2646. //If the hash or compare couldn't be done (e.g., some strange field type that isn't constant folded)
  2647. //then generate a warning and fall back to the default inline dictionary code
  2648. EXCLOG(e, "Generating an inline dictionary");
  2649. e->Release();
  2650. return false;
  2651. }
  2652. OwnedHqlExpr values = createValue(no_list, makeSetType(LINK(rowType)), args);
  2653. unsigned maxRows = values->numChildren();
  2654. Owned<ITypeInfo> declareType = makeConstantModifier(makeArrayType(LINK(rowType), maxRows));
  2655. OwnedITypeInfo rowsType = makeOutOfLineModifier(makeDictionaryType(LINK(rowType)));
  2656. rowsType.setown(setLinkCountedAttr(rowsType, true));
  2657. OwnedHqlExpr table = declareCtx.getTempDeclare(declareType, values);
  2658. if (options.spanMultipleCpp)
  2659. {
  2660. BuildCtx protoctx(*code, mainprototypesAtom);
  2661. protoctx.addDeclareExternal(table);
  2662. }
  2663. tgt.count.setown(getSizetConstant(maxRows));
  2664. tgt.expr.setown(createValue(no_typetransfer, LINK(rowsType), LINK(table)));
  2665. declareCtx.associateExpr(exprKey, tgt);
  2666. return true;
  2667. }
  2668. //---------------------------------------------------------------------------
  2669. // Dataset creation via builder
  2670. void HqlCppTranslator::buildDatasetAssignTempTable(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2671. {
  2672. OwnedHqlExpr values = normalizeListCasts(expr->queryChild(0));
  2673. if (values->getOperator() == no_null)
  2674. return;
  2675. IHqlExpression * record = expr->queryChild(1);
  2676. OwnedHqlExpr rowsExpr;
  2677. if (values->queryType()->getTypeCode() == type_set)
  2678. {
  2679. if ((values->getOperator() == no_list) && !values->isConstant())
  2680. {
  2681. ForEachChild(i, values)
  2682. {
  2683. BuildCtx loopctx(ctx);
  2684. BoundRow * targetRow = target->buildCreateRow(loopctx);
  2685. OwnedHqlExpr targetField = createSelectExpr(LINK(targetRow->querySelector()), LINK(record->queryChild(0)));
  2686. buildAssign(loopctx, targetField, values->queryChild(i));
  2687. target->finishRow(loopctx, targetRow);
  2688. }
  2689. }
  2690. else
  2691. {
  2692. Owned<IHqlCppSetCursor> cursor = createSetSelector(ctx, values);
  2693. BuildCtx loopctx(ctx);
  2694. CHqlBoundExpr boundCurElement;
  2695. cursor->buildIterateLoop(loopctx, boundCurElement, false);
  2696. BoundRow * targetRow = target->buildCreateRow(loopctx);
  2697. OwnedHqlExpr targetField = createSelectExpr(LINK(targetRow->querySelector()), LINK(record->queryChild(0)));
  2698. OwnedHqlExpr value = boundCurElement.getTranslatedExpr();
  2699. buildAssign(loopctx, targetField, value);
  2700. target->finishRow(loopctx, targetRow);
  2701. }
  2702. }
  2703. else
  2704. {
  2705. BuildCtx subctx(ctx);
  2706. BoundRow * targetRow = target->buildCreateRow(subctx);
  2707. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  2708. buildRowAssign(subctx, targetRef, values);
  2709. target->finishRow(subctx, targetRow);
  2710. }
  2711. }
  2712. void HqlCppTranslator::buildDatasetAssignInlineTable(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2713. {
  2714. IHqlExpression * transforms = expr->queryChild(0);
  2715. if (transforms->numChildren() == 0)
  2716. return;
  2717. unsigned maxRows = transforms->numChildren();
  2718. unsigned row;
  2719. const bool copyConstantRows = true;//getFieldCount(expr->queryRecord()) > 2;
  2720. for (row = 0; row < maxRows; row++)
  2721. {
  2722. IHqlExpression * transform = transforms->queryChild(row);
  2723. OwnedHqlExpr rowValue = createRow(no_createrow, LINK(transform));
  2724. BuildCtx subctx(ctx);
  2725. CHqlBoundExpr bound;
  2726. //Work in progress. Check if there are several fields - otherwise not worth it.s
  2727. if (doBuildRowConstantTransform(transform, bound))
  2728. {
  2729. BoundRow * row = bindConstantRow(subctx, rowValue, bound);
  2730. if (target->buildLinkRow(subctx, row))
  2731. continue;
  2732. }
  2733. BoundRow * targetRow = target->buildCreateRow(subctx);
  2734. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  2735. buildRowAssign(subctx, targetRef, rowValue);
  2736. target->finishRow(subctx, targetRow);
  2737. }
  2738. }
  2739. void HqlCppTranslator::buildDatasetAssignDatasetFromTransform(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2740. {
  2741. assertex(expr->getOperator() == no_dataset_from_transform);
  2742. IHqlExpression * count = expr->queryChild(0);
  2743. if (isZero(count) || isNegative(count))
  2744. return;
  2745. IHqlExpression * transform = expr->queryChild(1);
  2746. IHqlExpression * counter = queryAttributeChild(expr, _countProject_Atom, 0);
  2747. // If it is at all possible that it could be negative, we must test before producing rows
  2748. CHqlBoundExpr boundCount;
  2749. buildSimpleExpr(ctx, count, boundCount);
  2750. BuildCtx subctx(ctx);
  2751. if (couldBeNegative(count))
  2752. {
  2753. OwnedHqlExpr zero = createConstant(0, count->getType());
  2754. OwnedHqlExpr ifTest = createValue(no_gt, makeBoolType(), boundCount.getTranslatedExpr(), LINK(zero));
  2755. buildFilter(subctx, ifTest);
  2756. }
  2757. // loopVar = 1;
  2758. OwnedHqlExpr loopVar = subctx.getTempDeclare(counterType, NULL);
  2759. OwnedHqlExpr one = getSizetConstant(1);
  2760. buildAssignToTemp(subctx, loopVar, one);
  2761. // for(; loopVar <= maxRows; loopVar++)
  2762. OwnedHqlExpr loopTest = createValue(no_le, makeBoolType(), LINK(loopVar), LINK(boundCount.expr));
  2763. OwnedHqlExpr inc = createValue(no_postinc, loopVar->getType(), LINK(loopVar));
  2764. subctx.addLoop(loopTest, inc, false);
  2765. if (counter)
  2766. subctx.associateExpr(counter, loopVar);
  2767. OwnedHqlExpr rowValue = createRow(no_createrow, LINK(transform));
  2768. BoundRow * targetRow = target->buildCreateRow(subctx);
  2769. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  2770. buildRowAssign(subctx, targetRef, rowValue);
  2771. target->finishRow(subctx, targetRow);
  2772. }
  2773. class InlineDatasetSkipCallback : public CInterface, implements IHqlCodeCallback
  2774. {
  2775. public:
  2776. IMPLEMENT_IINTERFACE
  2777. virtual void buildCode(HqlCppTranslator & translator, BuildCtx & ctx)
  2778. {
  2779. ctx.addContinue();
  2780. }
  2781. };
  2782. void HqlCppTranslator::buildDatasetAssignProject(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2783. {
  2784. BuildCtx iterctx(ctx);
  2785. IHqlExpression * ds = expr->queryChild(0);
  2786. IHqlExpression * counter = queryAttributeChild(expr, _countProject_Atom, 0);
  2787. OwnedHqlExpr counterVar;
  2788. if (counter)
  2789. {
  2790. counterVar.setown(iterctx.getTempDeclare(unsignedType, queryZero()));
  2791. }
  2792. bool containsSkip = transformContainsSkip(expr->queryChild(1));
  2793. BoundRow * sourceCursor = buildDatasetIterate(iterctx, ds, containsSkip);
  2794. if (counter)
  2795. {
  2796. iterctx.associateExpr(counter, counterVar);
  2797. OwnedHqlExpr inc = createValue(no_postinc, LINK(unsignedType), LINK(counterVar));
  2798. iterctx.addExpr(inc);
  2799. }
  2800. if (sourceCursor)
  2801. {
  2802. if (isNullProject(expr, true, false))
  2803. {
  2804. if (target->buildLinkRow(iterctx, sourceCursor))
  2805. return;
  2806. }
  2807. BoundRow * targetRow = target->buildCreateRow(iterctx);
  2808. HqlExprAssociation * skipAssociation = NULL;
  2809. if (containsSkip)
  2810. {
  2811. OwnedHqlExpr callback = createUnknown(no_unknown, makeVoidType(), NULL, new InlineDatasetSkipCallback);
  2812. skipAssociation = ctx.associateExpr(skipActionMarker, callback);
  2813. }
  2814. Owned<IReferenceSelector> targetRef = buildActiveRow(iterctx, targetRow->querySelector());
  2815. switch (expr->getOperator())
  2816. {
  2817. case no_hqlproject:
  2818. doBuildRowAssignProject(iterctx, targetRef, expr);
  2819. break;
  2820. case no_newusertable:
  2821. doBuildRowAssignUserTable(iterctx, targetRef, expr);
  2822. break;
  2823. }
  2824. ctx.removeAssociation(skipAssociation);
  2825. target->finishRow(iterctx, targetRow);
  2826. }
  2827. }
  2828. void HqlCppTranslator::buildDatasetAssignJoin(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2829. {
  2830. IHqlExpression * left = expr->queryChild(0);
  2831. IHqlExpression * right = expr->queryChild(1);
  2832. IHqlExpression * cond = expr->queryChild(2);
  2833. IHqlExpression * selSeq = querySelSeq(expr);
  2834. bool leftOuter = expr->hasAttribute(leftonlyAtom) || expr->hasAttribute(leftouterAtom);
  2835. CHqlBoundExpr nullRhs;
  2836. if (leftOuter)
  2837. buildDefaultRow(ctx, right, nullRhs);
  2838. BuildCtx leftIterCtx(ctx);
  2839. BoundRow * leftCursor = buildDatasetIterate(leftIterCtx, left, false);
  2840. bindTableCursor(leftIterCtx, left, leftCursor->queryBound(), no_left, selSeq);
  2841. OwnedHqlExpr matchedAnyVar;
  2842. if (leftOuter)
  2843. matchedAnyVar.setown(leftIterCtx.getTempDeclare(queryBoolType(), queryBoolExpr(false)));
  2844. BuildCtx rightIterCtx(leftIterCtx);
  2845. BoundRow * rightCursor = buildDatasetIterate(rightIterCtx, right, false);
  2846. bindTableCursor(rightIterCtx, right, rightCursor->queryBound(), no_right, selSeq);
  2847. OwnedHqlExpr cseCond = options.spotCSE ? spotScalarCSE(cond) : LINK(cond);
  2848. buildFilter(rightIterCtx, cseCond);
  2849. if (!expr->hasAttribute(leftonlyAtom))
  2850. {
  2851. BoundRow * targetRow = target->buildCreateRow(rightIterCtx);
  2852. Owned<IReferenceSelector> targetRef = buildActiveRow(rightIterCtx, targetRow->querySelector());
  2853. OwnedHqlExpr rowValue = createRow(no_createrow, LINK(expr->queryChild(3)));
  2854. buildRowAssign(rightIterCtx, targetRef, rowValue);
  2855. target->finishRow(rightIterCtx, targetRow);
  2856. }
  2857. if (matchedAnyVar)
  2858. {
  2859. buildAssignToTemp(rightIterCtx, matchedAnyVar, queryBoolExpr(true));
  2860. OwnedHqlExpr test = getInverse(matchedAnyVar);
  2861. leftIterCtx.addFilter(test);
  2862. OwnedHqlExpr defaultRowPtr = getPointer(nullRhs.expr);
  2863. bindTableCursor(leftIterCtx, right, defaultRowPtr, no_right, selSeq);
  2864. BoundRow * targetRow = target->buildCreateRow(leftIterCtx);
  2865. Owned<IReferenceSelector> targetRef = buildActiveRow(leftIterCtx, targetRow->querySelector());
  2866. OwnedHqlExpr rowValue = createRow(no_createrow, LINK(expr->queryChild(3)));
  2867. buildRowAssign(leftIterCtx, targetRef, rowValue);
  2868. target->finishRow(leftIterCtx, targetRow);
  2869. }
  2870. }
  2871. void HqlCppTranslator::buildDatasetAssignAggregate(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2872. {
  2873. BuildCtx subctx(ctx);
  2874. subctx.addGroup();
  2875. BoundRow * targetRow = target->buildCreateRow(subctx);
  2876. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  2877. doBuildRowAssignAggregate(subctx, targetRef, expr);
  2878. target->finishRow(subctx, targetRow);
  2879. }
  2880. void HqlCppTranslator::buildDatasetAssignChoose(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * expr)
  2881. {
  2882. CHqlBoundExpr cond;
  2883. buildExpr(ctx, expr->queryChild(0), cond);
  2884. IHqlExpression * last = queryLastNonAttribute(expr);
  2885. BuildCtx subctx(ctx);
  2886. IHqlStmt * switchstmt = subctx.addSwitch(cond.expr);
  2887. ForEachChildFrom(i, expr, 1)
  2888. {
  2889. IHqlExpression * cur = expr->queryChild(i);
  2890. if (cur != last)
  2891. {
  2892. OwnedHqlExpr label = getSizetConstant(i);
  2893. subctx.addCase(switchstmt, label);
  2894. }
  2895. else
  2896. subctx.addDefault(switchstmt);
  2897. buildDatasetAssign(subctx, target, cur);
  2898. }
  2899. }
  2900. void HqlCppTranslator::buildDatasetAssignChoose(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  2901. {
  2902. CHqlBoundExpr cond;
  2903. buildExpr(ctx, expr->queryChild(0), cond);
  2904. IHqlExpression * last = queryLastNonAttribute(expr);
  2905. BuildCtx subctx(ctx);
  2906. IHqlStmt * switchstmt = subctx.addSwitch(cond.expr);
  2907. ForEachChildFrom(i, expr, 1)
  2908. {
  2909. IHqlExpression * cur = expr->queryChild(i);
  2910. if (cur != last)
  2911. {
  2912. OwnedHqlExpr label = getSizetConstant(i);
  2913. subctx.addCase(switchstmt, label);
  2914. }
  2915. else
  2916. subctx.addDefault(switchstmt);
  2917. buildDatasetAssign(subctx, target, cur);
  2918. }
  2919. }
  2920. void HqlCppTranslator::buildDatasetAssignIf(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  2921. {
  2922. BuildCtx subctx(ctx);
  2923. IHqlStmt * filter = buildFilterViaExpr(subctx, expr->queryChild(0));
  2924. buildDatasetAssign(subctx, target, expr->queryChild(1));
  2925. IHqlExpression * elseExpr = expr->queryChild(2);
  2926. assertex(elseExpr);
  2927. subctx.selectElse(filter);
  2928. buildDatasetAssign(subctx, target, elseExpr);
  2929. }
  2930. void HqlCppTranslator::buildDatasetAssign(BuildCtx & ctx, IHqlCppDatasetBuilder * target, IHqlExpression * _expr)
  2931. {
  2932. OwnedHqlExpr expr = forceInlineAssignDataset(ctx, _expr);
  2933. bool isRowAssign = false;
  2934. BuildCtx subctx(ctx);
  2935. switch (expr->getOperator())
  2936. {
  2937. case no_fail:
  2938. doBuildStmtFail(ctx, expr->queryChild(1));
  2939. return;
  2940. case no_addfiles:
  2941. buildDatasetAssign(subctx, target, expr->queryChild(0));
  2942. buildDatasetAssign(subctx, target, expr->queryChild(1));
  2943. return;
  2944. case no_temptable:
  2945. buildDatasetAssignTempTable(subctx, target, expr);
  2946. //MORE: Create rows and assign each one in turn. Could possibly be done with a different dataset selector
  2947. return;
  2948. case no_inlinetable:
  2949. buildDatasetAssignInlineTable(subctx, target, expr);
  2950. return;
  2951. case no_dataset_from_transform:
  2952. buildDatasetAssignDatasetFromTransform(subctx, target, expr);
  2953. return;
  2954. case no_xmlproject:
  2955. buildDatasetAssignXmlProject(subctx, target, expr);
  2956. return;
  2957. case no_datasetfromrow:
  2958. {
  2959. isRowAssign = true;
  2960. expr.set(expr->queryChild(0));
  2961. break;
  2962. }
  2963. case no_if:
  2964. {
  2965. CHqlBoundExpr bound;
  2966. buildExpr(subctx, expr->queryChild(0), bound);
  2967. IHqlStmt * filter = subctx.addFilter(bound.expr);
  2968. buildDatasetAssign(subctx, target, expr->queryChild(1));
  2969. IHqlExpression * elseExpr = expr->queryChild(2);
  2970. if (elseExpr && elseExpr->getOperator() != no_null)
  2971. {
  2972. subctx.selectElse(filter);
  2973. buildDatasetAssign(subctx, target, elseExpr);
  2974. }
  2975. }
  2976. return;
  2977. case no_chooseds:
  2978. buildDatasetAssignChoose(subctx, target, expr);
  2979. return;
  2980. case no_null:
  2981. return;
  2982. case no_activetable:
  2983. case no_temprow:
  2984. case no_createrow:
  2985. case no_projectrow:
  2986. case no_typetransfer:
  2987. isRowAssign = true;
  2988. break;
  2989. case no_newaggregate:
  2990. buildDatasetAssignAggregate(subctx, target, expr);
  2991. return;
  2992. case no_hqlproject:
  2993. case no_newusertable:
  2994. buildDatasetAssignProject(subctx, target, expr);
  2995. return;
  2996. case no_compound_childread:
  2997. case no_compound_childnormalize:
  2998. case no_compound_childaggregate:
  2999. case no_compound_selectnew:
  3000. case no_compound_inline:
  3001. case no_distributed:
  3002. case no_preservemeta:
  3003. case no_sorted:
  3004. case no_nofold:
  3005. case no_nohoist:
  3006. case no_section:
  3007. case no_sectioninput:
  3008. buildDatasetAssign(subctx, target, expr->queryChild(0));
  3009. return;
  3010. case no_alias_scope:
  3011. // expandAliasScope(subctx, expr);
  3012. buildDatasetAssign(subctx, target, expr->queryChild(0));
  3013. return;
  3014. case no_filter:
  3015. {
  3016. //We want to evaluate invariant conditions outside of the loop, rather than inside the dataset assignment
  3017. //Currently the test is whether the expression is independent of any tables. Better would be to
  3018. //see if the test was dependent on any of the datasets introduced by expr->queryChild(0).
  3019. HqlExprArray conds;
  3020. unwindFilterConditions(conds, expr);
  3021. IHqlExpression * ds = expr->queryChild(0);
  3022. #if 0
  3023. HqlExprCopyArray selectors;
  3024. loop
  3025. {
  3026. selectors.append(*ds->queryNormalizedSelector());
  3027. IHqlExpression * root = queryRoot(expr);
  3028. if (!root || root->getOperator() != no_select)
  3029. break;
  3030. bool isNew;
  3031. ds = querySelectorDataset(root, isNew);
  3032. if (!isNew)
  3033. break;
  3034. }
  3035. #endif
  3036. unsigned max = conds.ordinality();
  3037. unsigned i = 0;
  3038. bool optimized = false;
  3039. while (i < max)
  3040. {
  3041. IHqlExpression & cur = conds.item(i);
  3042. #if 0
  3043. bool overlap = false;
  3044. ForEachItemIn(j, selectors)
  3045. {
  3046. if (containsSelector(&cur, &selectors.item(j)))
  3047. {
  3048. overlap = true;
  3049. break;
  3050. }
  3051. }
  3052. #else
  3053. bool overlap = containsSelector(&cur, ds->queryNormalizedSelector());
  3054. #endif
  3055. if (!overlap)
  3056. {
  3057. buildFilter(subctx, &cur);
  3058. conds.remove(i);
  3059. optimized = true;
  3060. max--;
  3061. }
  3062. else
  3063. i++;
  3064. }
  3065. if (max == 0)
  3066. {
  3067. buildDatasetAssign(subctx, target, ds);
  3068. return;
  3069. }
  3070. if (optimized)
  3071. {
  3072. conds.add(*LINK(ds), 0);
  3073. expr.setown(expr->clone(conds));
  3074. }
  3075. break;
  3076. }
  3077. case no_join:
  3078. buildDatasetAssignJoin(subctx, target, expr);
  3079. return;
  3080. }
  3081. ITypeInfo * type = expr->queryType();
  3082. if (type)
  3083. {
  3084. switch (type->getTypeCode())
  3085. {
  3086. case type_record: // e.g. dataset.recordfield
  3087. case type_row:
  3088. isRowAssign = true;
  3089. break;
  3090. }
  3091. }
  3092. if (isRowAssign)
  3093. {
  3094. bool done = false;
  3095. subctx.addGroup();
  3096. //Some code primarily here to improve the generated code for productions inside parse statements for text parsing.
  3097. //see if we can replace a memcpy of the child record with a link...
  3098. if (!target->isRestricted())
  3099. {
  3100. switch (expr->getOperator())
  3101. {
  3102. case no_matchattr:
  3103. case no_left:
  3104. case no_right:
  3105. {
  3106. //Only try for really simple cases...
  3107. Owned<IReferenceSelector> sourceRef = buildNewRow(subctx, expr);
  3108. Owned<BoundRow> sourceRow = sourceRef->getRow(subctx);
  3109. if (!target->buildLinkRow(subctx, sourceRow))
  3110. {
  3111. BoundRow * targetRow = target->buildCreateRow(subctx);
  3112. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  3113. buildRowAssign(subctx, targetRef, sourceRef);
  3114. target->finishRow(subctx, targetRow);
  3115. }
  3116. done = true;
  3117. break;
  3118. }
  3119. }
  3120. }
  3121. if (!done)
  3122. {
  3123. BoundRow * match = static_cast<BoundRow *>(ctx.queryAssociation(expr, AssocRow, NULL));
  3124. if (match && target->buildLinkRow(subctx, match))
  3125. done = true;
  3126. }
  3127. if (!done)
  3128. {
  3129. BoundRow * targetRow = target->buildCreateRow(subctx);
  3130. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  3131. buildRowAssign(subctx, targetRef, expr);
  3132. target->finishRow(subctx, targetRow);
  3133. }
  3134. }
  3135. else
  3136. {
  3137. if (!target->buildAppendRows(subctx, expr))
  3138. {
  3139. BoundRow * sourceRow = buildDatasetIterate(subctx, expr, false);
  3140. if (sourceRow)
  3141. {
  3142. if (!target->buildLinkRow(subctx, sourceRow))
  3143. {
  3144. BoundRow * targetRow = target->buildCreateRow(subctx);
  3145. Owned<IReferenceSelector> targetRef = buildActiveRow(subctx, targetRow->querySelector());
  3146. Owned<IReferenceSelector> sourceRef = buildActiveRow(subctx, sourceRow->querySelector());
  3147. buildRowAssign(subctx, targetRef, sourceRef);
  3148. target->finishRow(subctx, targetRow);
  3149. }
  3150. }
  3151. }
  3152. }
  3153. }
  3154. //---------------------------------------------------------------------------
  3155. // Dataset iteration
  3156. BoundRow * HqlCppTranslator::buildDatasetIterateSelectN(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  3157. {
  3158. OwnedHqlExpr counter = ctx.getTempDeclare(sizetType, NULL);
  3159. buildAssignToTemp(ctx, counter, expr->queryChild(1));
  3160. BoundRow * cursor = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  3161. if (cursor)
  3162. {
  3163. OwnedHqlExpr dec = createValue(no_predec, counter->getType(), LINK(counter));
  3164. OwnedHqlExpr test = createBoolExpr(no_eq, LINK(dec), getSizetConstant(0));
  3165. ctx.addFilter(test);
  3166. }
  3167. return cursor;
  3168. }
  3169. BoundRow * HqlCppTranslator::buildDatasetIterateChoosen(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  3170. {
  3171. OwnedHqlExpr counter = ctx.getTempDeclare(sizetType, queryZero());
  3172. CHqlBoundExpr boundLow, boundHigh;
  3173. OwnedHqlExpr foldedHigh = foldHqlExpression(expr->queryChild(1));
  3174. if (!isChooseNAllLimit(foldedHigh))
  3175. buildSimpleExpr(ctx, foldedHigh, boundHigh);
  3176. if (queryRealChild(expr, 2))
  3177. {
  3178. OwnedHqlExpr foldedLow = foldHqlExpression(expr->queryChild(2));
  3179. OwnedHqlExpr low = adjustValue(foldedLow, -1);
  3180. buildSimpleExpr(ctx, low, boundLow);
  3181. if (boundHigh.expr)
  3182. boundHigh.expr.setown(createValue(no_add, LINK(boundHigh.queryType()), LINK(boundHigh.expr), LINK(boundLow.expr)));
  3183. }
  3184. BoundRow * cursor = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  3185. if (cursor)
  3186. {
  3187. OwnedHqlExpr inc = createValue(no_postinc, counter->getType(), LINK(counter));
  3188. ctx.addExpr(inc);
  3189. OwnedHqlExpr cond;
  3190. if (boundLow.expr)
  3191. extendConditionOwn(cond, no_and, createBoolExpr(no_gt, LINK(counter), LINK(boundLow.expr)));
  3192. if (boundHigh.expr)
  3193. extendConditionOwn(cond, no_and, createBoolExpr(no_le, LINK(counter), LINK(boundHigh.expr)));
  3194. if (cond)
  3195. ctx.addFilter(cond);
  3196. }
  3197. return cursor;
  3198. }
  3199. BoundRow * HqlCppTranslator::buildDatasetIterateLimit(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  3200. {
  3201. OwnedHqlExpr counter = ctx.getTempDeclare(sizetType, queryZero());
  3202. CHqlBoundExpr boundHigh;
  3203. OwnedHqlExpr foldedHigh = foldHqlExpression(expr->queryChild(1));
  3204. buildSimpleExpr(ctx, foldedHigh, boundHigh);
  3205. BoundRow * cursor = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  3206. if (cursor)
  3207. {
  3208. OwnedHqlExpr inc = createValue(no_preinc, counter->getType(), LINK(counter));
  3209. OwnedHqlExpr cond = createBoolExpr(no_gt, LINK(inc), LINK(boundHigh.expr));
  3210. BuildCtx subctx(ctx);
  3211. subctx.addFilter(cond);
  3212. LinkedHqlExpr fail = expr->queryChild(2);
  3213. if (!fail || fail->isAttribute())
  3214. fail.setown(createFailAction("Limit exceeded", foldedHigh, NULL, queryCurrentActivityId(ctx)));
  3215. buildStmt(subctx, fail);
  3216. }
  3217. return cursor;
  3218. }
  3219. BoundRow * HqlCppTranslator::buildDatasetIterateProject(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  3220. {
  3221. IHqlExpression * dataset = expr->queryChild(0);
  3222. OwnedHqlExpr counterVar;
  3223. IHqlExpression * counter = queryAttributeChild(expr, _countProject_Atom, 0);
  3224. if (counter)
  3225. {
  3226. counterVar.setown(ctx.getTempDeclare(unsignedType, queryZero()));
  3227. }
  3228. bool containsSkip = transformContainsSkip(expr->queryChild(1));
  3229. if (containsSkip)
  3230. needToBreak = true;
  3231. buildDatasetIterate(ctx, dataset, needToBreak);
  3232. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  3233. if (counter)
  3234. {
  3235. ctx.associateExpr(counter, counterVar);
  3236. OwnedHqlExpr inc = createValue(no_postinc, LINK(unsignedType), LINK(counterVar));
  3237. ctx.addExpr(inc);
  3238. }
  3239. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  3240. OwnedHqlExpr leftSelect = createSelector(no_left, dataset, querySelSeq(expr));
  3241. OwnedHqlExpr transform = replaceSelector(expr->queryChild(1), leftSelect, dataset->queryNormalizedSelector());
  3242. HqlExprAssociation * skipAssociation = NULL;
  3243. if (containsSkip)
  3244. {
  3245. OwnedHqlExpr callback = createUnknown(no_unknown, makeVoidType(), NULL, new InlineDatasetSkipCallback);
  3246. skipAssociation = ctx.associateExpr(skipActionMarker, callback);
  3247. }
  3248. doTransform(ctx, transform, rowBuilder);
  3249. ctx.removeAssociation(skipAssociation); //remove it in case keeping hold of it causes issues.
  3250. finalizeTempRow(ctx, tempRow, rowBuilder);
  3251. return bindTableCursor(ctx, expr, tempRow->queryBound());
  3252. }
  3253. BoundRow * HqlCppTranslator::buildDatasetIterateUserTable(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  3254. {
  3255. IHqlExpression * dataset = expr->queryChild(0);
  3256. buildDatasetIterate(ctx, dataset, needToBreak);
  3257. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  3258. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  3259. doTransform(ctx, expr->queryChild(2), rowBuilder);
  3260. finalizeTempRow(ctx, tempRow, rowBuilder);
  3261. return bindTableCursor(ctx, expr, tempRow->queryBound());
  3262. }
  3263. BoundRow * HqlCppTranslator::buildDatasetIterateSpecialTempTable(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  3264. {
  3265. IHqlExpression * values = expr->queryChild(0);
  3266. bool requiresTempRow = false;
  3267. ITypeInfo * setType = values->queryType();
  3268. ITypeInfo * type = setType->queryChildType();
  3269. switch (type->getTypeCode())
  3270. {
  3271. case type_int:
  3272. requiresTempRow = isComplexSet(setType, false);
  3273. break;
  3274. case type_swapint:
  3275. case type_packedint:
  3276. case type_alien:
  3277. case type_bitfield:
  3278. requiresTempRow = true;
  3279. break;
  3280. default:
  3281. if (type->getSize() == UNKNOWN_LENGTH)
  3282. requiresTempRow = true;
  3283. break;
  3284. }
  3285. Owned<IHqlCppSetCursor> cursor = createSetSelector(ctx, values);
  3286. CHqlBoundExpr boundCurElement;
  3287. cursor->buildIterateLoop(ctx, boundCurElement, false);
  3288. if (requiresTempRow)
  3289. {
  3290. //MORE: This could probably be improved by having a variety of buildIterateLoop which returned the
  3291. //underlying bound row. However it occurs fairly infrequently, so not a priority.
  3292. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  3293. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  3294. IHqlExpression * record = expr->queryRecord();
  3295. OwnedHqlExpr target = createSelectExpr(LINK(rowBuilder->querySelector()), LINK(record->queryChild(0)));
  3296. OwnedHqlExpr curValue = boundCurElement.getTranslatedExpr();
  3297. buildAssign(ctx, target, curValue);
  3298. finalizeTempRow(ctx, tempRow, rowBuilder);
  3299. return bindTableCursor(ctx, expr, tempRow->queryBound());
  3300. }
  3301. else
  3302. {
  3303. assertex(!boundCurElement.length && !boundCurElement.count);
  3304. OwnedHqlExpr address = getPointer(boundCurElement.expr);
  3305. address.setown(createValue(no_implicitcast, makeRowReferenceType(expr), LINK(address)));
  3306. return bindTableCursor(ctx, expr, address);
  3307. }
  3308. }
  3309. BoundRow * HqlCppTranslator::buildDatasetIterateFromDictionary(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  3310. {
  3311. BoundRow * dictionaryRow = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  3312. assertex(dictionaryRow->isConditional());
  3313. ctx.addFilter(dictionaryRow->queryBound());
  3314. return rebindTableCursor(ctx, expr, dictionaryRow, no_none, NULL);
  3315. }
  3316. BoundRow * HqlCppTranslator::buildDatasetIterateStreamedCall(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  3317. {
  3318. CHqlBoundExpr bound;
  3319. doBuildExprCall(ctx, expr, bound);
  3320. ITypeInfo * exprType = expr->queryType();
  3321. Owned<ITypeInfo> wrappedType = makeWrapperModifier(LINK(exprType));
  3322. ctx.addLoop(NULL, NULL, false);
  3323. Owned<ITypeInfo> wrappedRowType = makeWrapperModifier(LINK(queryRowType(exprType)));
  3324. OwnedHqlExpr tempRow = ctx.getTempDeclare(wrappedRowType, NULL);
  3325. StringBuffer s;
  3326. generateExprCpp(s, tempRow).append(".setown(");
  3327. generateExprCpp(s, bound.expr).append("->nextRow());");
  3328. ctx.addQuoted(s);
  3329. s.clear().append("if (!");generateExprCpp(s, tempRow).append(".getbytes()) break;");
  3330. ctx.addQuoted(s);
  3331. return bindTableCursor(ctx, expr, tempRow);
  3332. }
  3333. BoundRow * HqlCppTranslator::buildDatasetIterate(BuildCtx & ctx, IHqlExpression * expr, bool needToBreak)
  3334. {
  3335. if (!canProcessInline(&ctx, expr))
  3336. {
  3337. Owned<IHqlCppDatasetCursor> cursor = createDatasetSelector(ctx, expr);
  3338. return cursor->buildIterateLoop(ctx, needToBreak);
  3339. }
  3340. switch (expr->getOperator())
  3341. {
  3342. case no_dataset_alias:
  3343. if (!expr->hasAttribute(_normalized_Atom))
  3344. {
  3345. OwnedHqlExpr uniqueChild = normalizeDatasetAlias(expr);
  3346. BoundRow * childCursor = buildDatasetIterate(ctx, uniqueChild, needToBreak);
  3347. return rebindTableCursor(ctx, expr, childCursor, no_none, NULL);
  3348. }
  3349. else
  3350. {
  3351. throwUnexpected();
  3352. //The following would only be triggered for a splitter (not yet generated), and that would require
  3353. //disambiguation when that was built.
  3354. BoundRow * childCursor = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  3355. return rebindTableCursor(ctx, expr, childCursor, no_none, NULL);
  3356. }
  3357. case no_null:
  3358. buildFilter(ctx, queryBoolExpr(false));
  3359. return NULL;
  3360. case no_filter:
  3361. {
  3362. IHqlExpression * dataset = expr->queryChild(0);
  3363. #ifdef _OPTIMZE_INLINE_FILTERS_
  3364. //Good code, but messes up accidental cse in some createSegmentMonitor calls.
  3365. HqlExprAttr invariant;
  3366. OwnedHqlExpr cond = extractFilterConditions(invariant, expr, dataset);
  3367. if (invariant)
  3368. buildFilter(ctx, invariant);
  3369. //MORE: if (canAssignInline(ctx, ds) && !canIterateInline(ctx, ds)) break;
  3370. BoundRow * cursor = buildDatasetIterate(ctx, dataset, needToBreak);
  3371. if (cond)
  3372. buildFilter(ctx, cond);
  3373. #else
  3374. //MORE: if (canAssignInline(ctx, ds) && !canIterateInline(ctx, ds)) break;
  3375. BoundRow * cursor = buildDatasetIterate(ctx, dataset, needToBreak);
  3376. unsigned max = expr->numChildren();
  3377. for (unsigned i=1; i < max; i++)
  3378. buildFilter(ctx, expr->queryChild(i));
  3379. #endif
  3380. return cursor;
  3381. }
  3382. case no_id2blob:
  3383. case no_select:
  3384. case no_translated:
  3385. {
  3386. Owned<IHqlCppDatasetCursor> cursor = createDatasetSelector(ctx, expr);
  3387. return cursor->buildIterateLoop(ctx, needToBreak);
  3388. }
  3389. case no_choosen:
  3390. return buildDatasetIterateChoosen(ctx, expr, needToBreak);
  3391. case no_limit:
  3392. return buildDatasetIterateLimit(ctx, expr, needToBreak);
  3393. case no_index:
  3394. case no_selectnth:
  3395. return buildDatasetIterateSelectN(ctx, expr, needToBreak);
  3396. case no_hqlproject:
  3397. return buildDatasetIterateProject(ctx, expr, needToBreak);
  3398. case no_newusertable:
  3399. return buildDatasetIterateUserTable(ctx, expr, needToBreak);
  3400. case no_compound_childread:
  3401. case no_compound_childnormalize:
  3402. case no_compound_childaggregate:
  3403. case no_compound_selectnew:
  3404. case no_compound_inline:
  3405. case no_distributed:
  3406. case no_preservemeta:
  3407. case no_sorted:
  3408. case no_nofold:
  3409. case no_nohoist:
  3410. return buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  3411. case no_sectioninput:
  3412. case no_section:
  3413. {
  3414. BoundRow * row = buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  3415. #ifdef _DEBUG
  3416. StringBuffer s;
  3417. if (expr->getOperator() == no_section)
  3418. s.append("//---- section ");
  3419. else
  3420. s.append("//---- end section ");
  3421. getStringValue(s, expr->queryChild(1), "<?>").append(" ");
  3422. getStringValue(s, expr->queryChild(2)).append("----");
  3423. ctx.addQuoted(s);
  3424. #endif
  3425. return row;
  3426. }
  3427. case no_alias_scope:
  3428. // expandAliasScope(ctx, expr);
  3429. return buildDatasetIterate(ctx, expr->queryChild(0), needToBreak);
  3430. case no_temptable:
  3431. {
  3432. IHqlExpression * values = expr->queryChild(0);
  3433. if (values->queryType()->getTypeCode() == type_set)
  3434. {
  3435. if (values->getOperator() == no_alias)
  3436. values = values->queryChild(0);
  3437. bool special = false;
  3438. switch (values->getOperator())
  3439. {
  3440. case no_getresult:
  3441. case no_null:
  3442. special = true;
  3443. break;
  3444. }
  3445. if (special)
  3446. return buildDatasetIterateSpecialTempTable(ctx, expr, needToBreak);
  3447. }
  3448. break;
  3449. }
  3450. case no_datasetfromdictionary:
  3451. return buildDatasetIterateFromDictionary(ctx, expr, needToBreak);
  3452. case no_call:
  3453. case no_externalcall:
  3454. if (hasStreamedModifier(expr->queryType()))
  3455. return buildDatasetIterateStreamedCall(ctx, expr, needToBreak);
  3456. break;
  3457. #if 0
  3458. //Following should improve the code, but I'm not sure how to correctly convert a referenceSelector to a boundExpr (since it may be with an existing row)
  3459. case no_datasetfromrow:
  3460. if (!needToBreak)
  3461. {
  3462. BoundRow * row = buildNewRow(ctx, expr->queryChild(0));
  3463. bindTableCursor(ctx, expr, tempRow->queryBound(), no_none, NULL);
  3464. return row;
  3465. }
  3466. break;
  3467. #endif
  3468. }
  3469. Owned<IHqlCppDatasetCursor> cursor = createDatasetSelector(ctx, expr);
  3470. return cursor->buildIterateLoop(ctx, needToBreak);
  3471. }
  3472. //---------------------------------------------------------------------------
  3473. // Row Assignment
  3474. void HqlCppTranslator::buildCompoundAssign(BuildCtx & ctx, IHqlExpression * left, IReferenceSelector * leftSelector, IHqlExpression * rightScope, IHqlExpression * rightSelector)
  3475. {
  3476. switch (left->getOperator())
  3477. {
  3478. case no_ifblock:
  3479. {
  3480. BuildCtx subctx(ctx);
  3481. OwnedHqlExpr test = replaceSelector(left->queryChild(0), querySelfReference(), leftSelector->queryExpr());
  3482. buildFilter(subctx, test);
  3483. buildCompoundAssign(subctx, left->queryChild(1), leftSelector, rightScope, rightSelector);
  3484. //This calculates the size of the previous block. It means that subsequent uses of the
  3485. //offsets are cached - even if they are inside another ifblock().
  3486. CHqlBoundExpr bound;
  3487. IHqlExpression * mapexpr = createSelectExpr(LINK(leftSelector->queryExpr()), LINK(left));
  3488. OwnedHqlExpr size = createValue(no_sizeof, makeIntType(4,false), mapexpr);
  3489. buildCachedExpr(ctx, size, bound);
  3490. }
  3491. break;
  3492. case no_field:
  3493. {
  3494. Owned<IReferenceSelector> selectedLeft = leftSelector->select(ctx, left);
  3495. OwnedHqlExpr selectedRight;
  3496. IHqlExpression * leftRecord = ::queryRecord(leftSelector->queryType());
  3497. if (!rightScope || (leftRecord==rightScope))
  3498. {
  3499. selectedRight.setown(createSelectExpr(LINK(rightSelector), LINK(left)));
  3500. }
  3501. else
  3502. {
  3503. IHqlSimpleScope * scope = rightScope->querySimpleScope();
  3504. IHqlExpression * resolved = scope->lookupSymbol(left->queryId());
  3505. assertex(resolved);
  3506. selectedRight.setown(createSelectExpr(LINK(rightSelector), resolved));
  3507. }
  3508. if (left->queryType()->getTypeCode() == type_row)
  3509. buildCompoundAssign(ctx, left->queryRecord(), selectedLeft, selectedRight->queryRecord(), selectedRight);
  3510. else
  3511. selectedLeft->set(ctx, selectedRight);
  3512. break;
  3513. }
  3514. break;
  3515. case no_record:
  3516. {
  3517. ForEachChild(i, left)
  3518. buildCompoundAssign(ctx, left->queryChild(i), leftSelector, rightScope, rightSelector);
  3519. break;
  3520. }
  3521. case no_attr:
  3522. case no_attr_expr:
  3523. case no_attr_link:
  3524. break;
  3525. default:
  3526. UNIMPLEMENTED;
  3527. }
  3528. }
  3529. void HqlCppTranslator::buildCompoundAssign(BuildCtx & ctx, IHqlExpression * left, IHqlExpression * right)
  3530. {
  3531. //MORE: May need to resolve lhs and rhs in scope to find out the record type.
  3532. // buildCompoundAssign(ctx, column->queryRecord(), selector->queryExpr(), value->queryRecord(), value);
  3533. UNIMPLEMENTED;
  3534. }
  3535. void HqlCppTranslator::doBuildRowAssignAggregateClear(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3536. {
  3537. IHqlExpression * transform = expr->queryChild(2);
  3538. unsigned numAggregates = transform->numChildren();
  3539. unsigned idx;
  3540. OwnedHqlExpr self = getSelf(expr);
  3541. for (idx = 0; idx < numAggregates; idx++)
  3542. {
  3543. IHqlExpression * cur = transform->queryChild(idx);
  3544. Owned<IReferenceSelector> curTarget = createSelfSelect(ctx, target, cur->queryChild(0), self);
  3545. IHqlExpression * src = cur->queryChild(1);
  3546. switch (src->getOperator())
  3547. {
  3548. case no_countgroup:
  3549. case no_maxgroup:
  3550. case no_mingroup:
  3551. case no_sumgroup:
  3552. case no_existsgroup:
  3553. curTarget->buildClear(ctx, 0);
  3554. break;
  3555. default:
  3556. if (src->isConstant())
  3557. curTarget->set(ctx, src);
  3558. else
  3559. curTarget->buildClear(ctx, 0);
  3560. break;
  3561. }
  3562. }
  3563. }
  3564. void HqlCppTranslator::doBuildRowAssignAggregateNext(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr, bool isSingleExists, IHqlExpression * alreadyDoneExpr)
  3565. {
  3566. IHqlExpression * transform = expr->queryChild(2);
  3567. unsigned numAggregates = transform->numChildren();
  3568. OwnedHqlExpr self = getSelf(expr);
  3569. OwnedHqlExpr notAlreadyDone = alreadyDoneExpr ? getInverse(alreadyDoneExpr) : NULL;
  3570. bool isVariableOffset = false;
  3571. for (unsigned idx = 0; idx < numAggregates; idx++)
  3572. {
  3573. IHqlExpression * cur = transform->queryChild(idx);
  3574. if (cur->isAttribute())
  3575. continue;
  3576. IHqlExpression * targetSelect = cur->queryChild(0);
  3577. Owned<IReferenceSelector> curTarget = createSelfSelect(ctx, target, targetSelect, self);
  3578. IHqlExpression * src = cur->queryChild(1);
  3579. IHqlExpression * arg = src->queryChild(0);
  3580. IHqlExpression * cond = src->queryChild(1);
  3581. BuildCtx condctx(ctx);
  3582. node_operator srcOp = src->getOperator();
  3583. switch (srcOp)
  3584. {
  3585. case no_countgroup:
  3586. {
  3587. assertex(!(arg && isVariableOffset));
  3588. if (arg)
  3589. buildFilter(condctx, arg);
  3590. OwnedHqlExpr one = getSizetConstant(1);
  3591. if (isVariableOffset)
  3592. {
  3593. IHqlStmt * ifStmt = condctx.addFilter(notAlreadyDone);
  3594. curTarget->set(condctx, one);
  3595. condctx.selectElse(ifStmt);
  3596. }
  3597. buildIncrementAssign(condctx, curTarget, one);
  3598. }
  3599. break;
  3600. case no_sumgroup:
  3601. {
  3602. assertex(!(cond && isVariableOffset));
  3603. if (cond)
  3604. buildFilter(condctx, cond);
  3605. if (isVariableOffset)
  3606. {
  3607. IHqlStmt * ifStmt = condctx.addFilter(notAlreadyDone);
  3608. curTarget->set(condctx, arg);
  3609. condctx.selectElse(ifStmt);
  3610. }
  3611. buildIncrementAssign(condctx, curTarget, arg);
  3612. }
  3613. break;
  3614. case no_maxgroup:
  3615. case no_mingroup:
  3616. {
  3617. node_operator op = (srcOp == no_maxgroup) ? no_gt : no_lt;
  3618. assertex(!cond);
  3619. OwnedHqlExpr castArg = ensureExprType(arg, targetSelect->queryType()); // cast to correct type, assume it can fit in the target type.
  3620. OwnedHqlExpr temp = buildSimplifyExpr(condctx, castArg);
  3621. OwnedHqlExpr compare = createBoolExpr (op, LINK(temp), LINK(curTarget->queryExpr()));
  3622. if (notAlreadyDone)
  3623. compare.setown(createBoolExpr(no_or, LINK(notAlreadyDone), compare.getClear()));
  3624. buildFilter(condctx, compare);
  3625. curTarget->set(condctx, temp);
  3626. }
  3627. break;
  3628. case no_existsgroup:
  3629. assertex(!(arg && isVariableOffset));
  3630. if (arg)
  3631. buildFilter(condctx, arg);
  3632. curTarget->set(condctx, queryBoolExpr(true));
  3633. if (isSingleExists)
  3634. condctx.addBreak();
  3635. break;
  3636. default:
  3637. if (!src->isConstant() || isVariableOffset)
  3638. {
  3639. condctx.addFilter(notAlreadyDone);
  3640. curTarget->set(condctx, src);
  3641. }
  3642. break;
  3643. }
  3644. if (targetSelect->queryType()->getSize() == UNKNOWN_LENGTH)
  3645. isVariableOffset = true;
  3646. }
  3647. if (alreadyDoneExpr)
  3648. buildAssignToTemp(ctx, alreadyDoneExpr, queryBoolExpr(true));
  3649. }
  3650. void HqlCppTranslator::doBuildRowAssignAggregate(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3651. {
  3652. IHqlExpression * dataset = expr->queryChild(0);
  3653. IHqlExpression * transform = expr->queryChild(2);
  3654. unsigned numAggregates = transform->numChildren();
  3655. if (isKeyedCountAggregate(expr))
  3656. throwError(HQLERR_KeyedCountNonKeyable);
  3657. bool needGuard = false;
  3658. bool isSingleExists = true;
  3659. unsigned idx;
  3660. for (idx = 0; idx < numAggregates; idx++)
  3661. {
  3662. IHqlExpression * cur = transform->queryChild(idx);
  3663. if (cur->isAttribute())
  3664. continue;
  3665. IHqlExpression * tgt = cur->queryChild(0);
  3666. IHqlExpression * src = cur->queryChild(1);
  3667. switch (src->getOperator())
  3668. {
  3669. case no_countgroup:
  3670. case no_sumgroup:
  3671. isSingleExists = false;
  3672. break;
  3673. case no_existsgroup:
  3674. break;
  3675. case no_mingroup:
  3676. isSingleExists = false;
  3677. needGuard = true;
  3678. break;
  3679. case no_maxgroup:
  3680. isSingleExists = false;
  3681. if (!isNullValueMinimumValue(src->queryType()))
  3682. needGuard = true;
  3683. break;
  3684. default:
  3685. isSingleExists = false;
  3686. if (!src->isConstant())
  3687. needGuard = true;
  3688. break;
  3689. }
  3690. if ((tgt->queryType()->getSize() == UNKNOWN_LENGTH) && (idx+1 != numAggregates))
  3691. needGuard = true;
  3692. }
  3693. OwnedHqlExpr guard;
  3694. if (needGuard)
  3695. {
  3696. Owned<ITypeInfo> boolType = makeBoolType();
  3697. guard.setown(ctx.getTempDeclare(boolType, queryBoolExpr(false)));
  3698. }
  3699. doBuildRowAssignAggregateClear(ctx, target, expr);
  3700. BuildCtx condctx(ctx);
  3701. buildDatasetIterate(condctx, dataset, isSingleExists);
  3702. doBuildRowAssignAggregateNext(condctx, target, expr, isSingleExists, guard);
  3703. }
  3704. void HqlCppTranslator::doBuildRowAssignProject(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3705. {
  3706. IHqlExpression * dataset = expr->queryChild(0);
  3707. IHqlExpression * counter = queryAttributeChild(expr, _countProject_Atom, 0);
  3708. if (counter && !ctx.queryMatchExpr(counter))
  3709. throwError(HQLERR_CounterNotFound);
  3710. BuildCtx subctx(ctx);
  3711. assertex(target->isRoot());
  3712. IHqlExpression * selSeq = querySelSeq(expr);
  3713. OwnedHqlExpr leftSelect = createSelector(no_left, dataset, selSeq);
  3714. OwnedHqlExpr activeDataset = ensureActiveRow(dataset->queryNormalizedSelector());
  3715. OwnedHqlExpr transform = queryNewReplaceSelector(expr->queryChild(1), leftSelect, activeDataset);
  3716. Owned<BoundRow> selfCursor;
  3717. if (!transform)
  3718. {
  3719. subctx.addGroup();
  3720. selfCursor.set(bindSelectorAsSelf(subctx, target, expr));
  3721. //Mapping may potentially be ambiguous, so do things correctly (see hqlsource for details)
  3722. BoundRow * prevCursor = resolveSelectorDataset(subctx, dataset->queryNormalizedSelector());
  3723. transform.set(expr->queryChild(1));
  3724. bindTableCursor(subctx, dataset, prevCursor->queryBound(), no_left, selSeq);
  3725. }
  3726. else
  3727. {
  3728. //Not introducing any new left rows => no problem assigning to target selector
  3729. selfCursor.setown(target->getRow(subctx));
  3730. }
  3731. doTransform(subctx, transform, selfCursor);
  3732. }
  3733. void HqlCppTranslator::doBuildRowAssignCreateRow(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3734. {
  3735. IHqlExpression * transform = expr->queryChild(0);
  3736. if (transform->isConstant())
  3737. {
  3738. #ifdef USE_CONSTANT_ROW_FOR_ASSIGN
  3739. //Generally not worthwhile - unless maybe it has a large number of fields....
  3740. CHqlBoundExpr bound;
  3741. if (doBuildRowConstantTransform(transform, bound))
  3742. {
  3743. OwnedHqlExpr raw = bound.getTranslatedExpr();
  3744. buildRowAssign(ctx, target, raw);
  3745. return;
  3746. }
  3747. #endif
  3748. }
  3749. Owned<BoundRow> selfCursor = target->getRow(ctx);
  3750. doTransform(ctx, transform, selfCursor);
  3751. }
  3752. void HqlCppTranslator::doBuildRowAssignNullRow(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3753. {
  3754. target->buildClear(ctx, 0);
  3755. }
  3756. void HqlCppTranslator::doBuildRowAssignProjectRow(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3757. {
  3758. IHqlExpression * srcRow = expr->queryChild(0);
  3759. IHqlExpression * transform = expr->queryChild(1);
  3760. Owned<IReferenceSelector> source = buildNewRow(ctx, srcRow);
  3761. BuildCtx subctx(ctx);
  3762. OwnedHqlExpr leftSelect = createSelector(no_left, srcRow, querySelSeq(expr));
  3763. OwnedHqlExpr newTransform = replaceSelector(transform, leftSelect, srcRow);
  3764. Owned<BoundRow> selfCursor = target->getRow(subctx);
  3765. doTransform(subctx, newTransform, selfCursor);
  3766. }
  3767. void HqlCppTranslator::doBuildRowAssignSerializeRow(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3768. {
  3769. IHqlExpression * srcRow = expr->queryChild(0);
  3770. IAtom * serializeForm = expr->queryChild(1)->queryName();
  3771. Owned<IReferenceSelector> source = buildNewRow(ctx, srcRow);
  3772. BuildCtx subctx(ctx);
  3773. Owned<BoundRow> leftCursor = source->getRow(subctx);
  3774. BoundRow * selfCursor = bindSelectorAsSelf(subctx, target, expr);
  3775. IHqlExpression * unserializedRecord = srcRow->queryRecord();
  3776. //If builder isn't provided then the target must be a fixed size record that doesn't require serialization
  3777. //Therefore this should never be called.
  3778. assertex(selfCursor->queryBuilder());
  3779. {
  3780. HqlExprArray args;
  3781. args.append(*createSerializer(ctx, unserializedRecord, serializeForm, serializerAtom));
  3782. args.append(*LINK(srcRow));
  3783. Owned<ITypeInfo> type = makeTransformType(expr->queryRecord()->getType());
  3784. OwnedHqlExpr call = bindFunctionCall(rtlSerializeToBuilderId, args, type);
  3785. doTransform(subctx, call, selfCursor);
  3786. //MORE: This doesn't associated the returned size with the target if assigned to a child field.
  3787. //very unusual code, so not too concerned.
  3788. }
  3789. subctx.removeAssociation(selfCursor);
  3790. }
  3791. void HqlCppTranslator::doBuildRowAssignUserTable(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3792. {
  3793. Owned<BoundRow> selfCursor = target->getRow(ctx);
  3794. doTransform(ctx, expr->queryChild(2), selfCursor);
  3795. }
  3796. void HqlCppTranslator::buildRowAssign(BuildCtx & ctx, BoundRow * targetRow, IHqlExpression * expr)
  3797. {
  3798. //MORE: We should improve assigning a link counted row to a dataset as well.
  3799. //The problem is that currently the dataset constructor is responsible for finializing the rows.
  3800. //which is more compact if the row can't just be appended. Possibly needs an alwaysCreatesTemp()
  3801. //to help decide.
  3802. IHqlExpression * targetExpr = targetRow->queryBound();
  3803. if (targetRow->isLinkCounted() && hasWrapperModifier(targetExpr->queryType()))
  3804. {
  3805. CHqlBoundTarget target;
  3806. target.expr.set(targetRow->queryBound());
  3807. switch (expr->getOperator())
  3808. {
  3809. //MORE could support no_null, no_if, no_translated, constant no_createrow etc.
  3810. case no_call:
  3811. case no_externalcall:
  3812. case no_getgraphresult:
  3813. buildExprAssign(ctx, target, expr);
  3814. return;
  3815. case no_comma:
  3816. case no_compound:
  3817. buildStmt(ctx, expr->queryChild(0));
  3818. buildRowAssign(ctx, targetRow, expr->queryChild(1));
  3819. return;
  3820. }
  3821. }
  3822. BuildCtx subctx(ctx);
  3823. IHqlStmt * stmt = subctx.addGroup();
  3824. stmt->setIncomplete(true);
  3825. Owned<BoundRow> rowBuilder = createRowBuilder(subctx, targetRow);
  3826. Owned<IReferenceSelector> createdRef = createReferenceSelector(rowBuilder);
  3827. buildRowAssign(subctx, createdRef, expr);
  3828. finalizeTempRow(subctx, targetRow, rowBuilder);
  3829. stmt->setIncomplete(false);
  3830. stmt->mergeScopeWithContainer();
  3831. }
  3832. void HqlCppTranslator::buildRowAssign(BuildCtx & ctx, IReferenceSelector * target, IHqlExpression * expr)
  3833. {
  3834. switch (expr->getOperator())
  3835. {
  3836. case no_temprow:
  3837. throwUnexpected();
  3838. case no_projectrow:
  3839. doBuildRowAssignProjectRow(ctx, target, expr);
  3840. return;
  3841. case no_createrow:
  3842. doBuildRowAssignCreateRow(ctx, target, expr);
  3843. return;
  3844. case no_null:
  3845. doBuildRowAssignNullRow(ctx, target, expr);
  3846. return;
  3847. case no_serialize:
  3848. {
  3849. IHqlExpression * deserialized = expr->queryChild(0);
  3850. IAtom * serializeForm = expr->queryChild(1)->queryName();
  3851. if (isDummySerializeDeserialize(expr))
  3852. buildRowAssign(ctx, target, deserialized->queryChild(0));
  3853. else if (!typeRequiresDeserialization(deserialized->queryType(), serializeForm))
  3854. buildRowAssign(ctx, target, deserialized);
  3855. else
  3856. doBuildRowAssignSerializeRow(ctx, target, expr);
  3857. return;
  3858. }
  3859. case no_if:
  3860. {
  3861. //Assigning a variable size record can mean that references to self need recalculating outside of the condition,
  3862. //producing poor code.
  3863. if (!isVariableSizeRecord(expr->queryRecord()))
  3864. {
  3865. OwnedHqlExpr foldedCond = foldHqlExpression(expr->queryChild(0));
  3866. BuildCtx condctx(ctx);
  3867. IHqlStmt * cond = buildFilterViaExpr(condctx, foldedCond);
  3868. buildRowAssign(condctx, target, expr->queryChild(1));
  3869. condctx.selectElse(cond);
  3870. buildRowAssign(condctx, target, expr->queryChild(2));
  3871. return;
  3872. }
  3873. }
  3874. break;
  3875. /*
  3876. case no_externalcall:
  3877. //MORE: Should assign directly to the target, but may not be very easy....
  3878. if (target->isBinary() && queryRecord(source->queryType()) == expr->queryRecord())
  3879. {
  3880. CHqlBoundExpr address;
  3881. target->buildAddress(ctx, address);
  3882. row.setown(createValue(no_typetransfer, makeReferenceModifier(LINK(selector->queryType())), LINK(address.expr)));
  3883. doBuildCall(ctx, &target, expr, NULL);
  3884. }
  3885. break;
  3886. */
  3887. case no_comma:
  3888. case no_compound:
  3889. buildStmt(ctx, expr->queryChild(0));
  3890. buildRowAssign(ctx, target, expr->queryChild(1));
  3891. return;
  3892. }
  3893. Owned<IReferenceSelector> src = buildNewRow(ctx, expr);
  3894. buildRowAssign(ctx, target, src);
  3895. }
  3896. void HqlCppTranslator::buildRowAssign(BuildCtx & ctx, IReferenceSelector * target, IReferenceSelector * source)
  3897. {
  3898. BuildCtx subctx(ctx);
  3899. IHqlExpression * sourceRecord = ::queryRecord(source->queryType());
  3900. IHqlExpression * targetRecord = ::queryRecord(target->queryType());
  3901. //if record structures are identical, then we must just be able to block copy the information across.
  3902. bool useMemcpy = (sourceRecord == targetRecord) && source->isBinary() && !source->isConditional() &&
  3903. !recordRequiresLinkCount(sourceRecord);
  3904. if (useMemcpy)
  3905. {
  3906. if (source->queryRootRow()->isConditional())
  3907. {
  3908. IHqlStmt * ifStmt = subctx.addFilter(source->queryRootRow()->queryBound());
  3909. target->setRow(subctx, source);
  3910. subctx.selectElse(ifStmt);
  3911. target->buildClear(subctx, 0);
  3912. }
  3913. else
  3914. target->setRow(subctx, source);
  3915. }
  3916. else
  3917. buildCompoundAssign(subctx, targetRecord, target, sourceRecord, source->queryExpr());
  3918. }
  3919. //---------------------------------------------------------------------------
  3920. // Dataset selection
  3921. IReferenceSelector * HqlCppTranslator::doBuildRowSelectTop(BuildCtx & ctx, IHqlExpression * expr)
  3922. {
  3923. //create a temporary
  3924. Owned<ITypeInfo> rowType = makeReferenceModifier(expr->getType());
  3925. OwnedHqlExpr rowExpr = ctx.getTempDeclare(rowType, NULL);
  3926. Owned<BoundRow> row = createBoundRow(expr, rowExpr);
  3927. ctx.associate(*row); // associate here because it is compared inside the loop
  3928. CHqlBoundExpr boundCleared;
  3929. #ifdef CREATE_DEAULT_ROW_IF_NULL
  3930. buildDefaultRow(ctx, expr, boundCleared);
  3931. #else
  3932. buildNullRow(ctx, expr, boundCleared);
  3933. #endif
  3934. OwnedHqlExpr defaultRowPtr = getPointer(boundCleared.expr);
  3935. //Declare row for final level, iterate the appropriate number of times, and then assign and break.
  3936. BuildCtx initctx(ctx);
  3937. initctx.addGroup(); // add a group to allow a temporary to be declared later.
  3938. initctx.addAssign(rowExpr, defaultRowPtr);
  3939. HqlExprAssociation * savedMarker = ctx.associateExpr(queryConditionalRowMarker(), rowExpr);
  3940. BuildCtx iterctx(ctx);
  3941. IHqlExpression * sort = expr->queryChild(0);
  3942. IHqlExpression * dataset = sort->queryChild(0);
  3943. IHqlExpression * sortList = sort->queryChild(1);
  3944. BoundRow * chooseCursor = buildDatasetIterate(iterctx, dataset, false);
  3945. //if (!best) { best=row; } else { if (next < best) best = row; } Must short-circuit the test of best
  3946. OwnedHqlExpr testBest = createBoolExpr(no_eq, LINK(rowExpr), LINK(defaultRowPtr));
  3947. IHqlStmt * ifStmt = iterctx.addFilter(testBest);
  3948. {
  3949. OwnedHqlExpr source = ensureIteratedRowIsLive(initctx, ctx, iterctx, chooseCursor, dataset, expr);
  3950. OwnedHqlExpr castLeftRow = createValue(no_implicitcast, LINK(rowType), LINK(source));//chooseCursor->queryBound()));
  3951. iterctx.addAssign(rowExpr, castLeftRow);
  3952. }
  3953. iterctx.selectElse(ifStmt);
  3954. CHqlBoundExpr bound;
  3955. buildOrderedCompare(iterctx, dataset, sortList, bound, dataset, expr);
  3956. OwnedHqlExpr compare = createBoolExpr(no_lt, LINK(bound.expr), getZero());
  3957. iterctx.addFilter(compare);
  3958. {
  3959. OwnedHqlExpr source = ensureIteratedRowIsLive(initctx, ctx, iterctx, chooseCursor, dataset, expr);
  3960. OwnedHqlExpr castLeftRow = createValue(no_implicitcast, LINK(rowType), LINK(source));//chooseCursor->queryBound()));
  3961. iterctx.addAssign(rowExpr, castLeftRow);
  3962. }
  3963. ctx.removeAssociation(savedMarker);
  3964. //Set conditional later on, so test in main loop is explicit
  3965. #ifndef CREATE_DEAULT_ROW_IF_NULL
  3966. row->setConditional(true);
  3967. #endif
  3968. return createReferenceSelector(row);
  3969. }
  3970. BoundRow * HqlCppTranslator::buildOptimizeSelectFirstRow(BuildCtx & ctx, IHqlExpression * expr)
  3971. {
  3972. BoundRow * parentRow = NULL;
  3973. node_operator op = expr->getOperator();
  3974. switch (op)
  3975. {
  3976. case no_compound_childaggregate:
  3977. return buildOptimizeSelectFirstRow(ctx, expr->queryChild(0));
  3978. case no_hqlproject:
  3979. case no_newusertable:
  3980. {
  3981. parentRow = buildOptimizeSelectFirstRow(ctx, expr->queryChild(0));
  3982. if (!parentRow)
  3983. return NULL;
  3984. }
  3985. //fall through
  3986. case no_newaggregate:
  3987. {
  3988. Owned<BoundRow> tempRow = declareTempAnonRow(ctx, ctx, expr);
  3989. Owned<BoundRow> rowBuilder = createRowBuilder(ctx, tempRow);
  3990. Owned<IReferenceSelector> createdRef = createReferenceSelector(rowBuilder);
  3991. BuildCtx subctx(ctx);
  3992. subctx.addGroup();
  3993. if (parentRow)
  3994. {
  3995. if (op == no_hqlproject)
  3996. bindTableCursor(ctx, expr->queryChild(0), tempRow->queryBound(), no_left, querySelSeq(expr));
  3997. else
  3998. bindTableCursor(ctx, expr->queryChild(0), tempRow->queryBound(), no_none, NULL);
  3999. }
  4000. doBuildRowAssignAggregate(subctx, createdRef, expr);
  4001. finalizeTempRow(ctx, tempRow, rowBuilder);
  4002. return tempRow;
  4003. }
  4004. //
  4005. default:
  4006. return NULL;
  4007. }
  4008. }
  4009. void HqlCppTranslator::convertBoundDatasetToFirstRow(IHqlExpression * expr, CHqlBoundExpr & bound)
  4010. {
  4011. Owned<ITypeInfo> type = makeReferenceModifier(expr->getType());
  4012. ITypeInfo * boundType = bound.queryType();
  4013. if (isArrayRowset(boundType))
  4014. {
  4015. Linked<ITypeInfo> rowType = queryUnqualifiedType(queryRowType(boundType));
  4016. rowType.setown(makeReferenceModifier(LINK(rowType)));
  4017. if (hasLinkedRow(boundType))
  4018. type.setown(setLinkCountedAttr(type, true));
  4019. bound.expr.setown(createValue(no_deref, LINK(rowType), LINK(bound.expr)));
  4020. }
  4021. else if (bound.queryType()->isReference())
  4022. bound.expr.setown(createValue(no_typetransfer, LINK(type), bound.expr.getClear()));
  4023. else
  4024. bound.expr.setown(createValue(no_implicitcast, LINK(type), bound.expr.getClear()));
  4025. }
  4026. void HqlCppTranslator::convertBoundRowToDataset(BuildCtx & ctx, CHqlBoundExpr & bound, const BoundRow * row, ExpressionFormat preferredFormat)
  4027. {
  4028. IHqlExpression * boundRow = row->queryBound();
  4029. IHqlExpression * record = row->queryDataset()->queryRecord();
  4030. Owned<ITypeInfo> type = makeTableType(makeRowType(LINK(record->queryType())));
  4031. Owned<ITypeInfo> refType = makeReferenceModifier(LINK(type));
  4032. if (hasLinkCountedModifier(boundRow->queryType()) && (preferredFormat != FormatBlockedDataset))
  4033. {
  4034. OwnedHqlExpr curActivityId = getCurrentActivityId(ctx);
  4035. StringBuffer allocatorName;
  4036. ensureRowAllocator(allocatorName, ctx, record, curActivityId);
  4037. OwnedHqlExpr src = getPointer(boundRow);
  4038. //We can't just take the address of the link counted row, have to create a temporary dataset
  4039. //could be fixed once the link counting is tracked on rows and datasets
  4040. CHqlBoundTarget target;
  4041. createTempFor(ctx, type, target, typemod_none, FormatLinkedDataset);
  4042. StringBuffer s;
  4043. generateExprCpp(s, target.expr).append(".setRow(").append(allocatorName).append(",");
  4044. generateExprCpp(s, src).append(");");
  4045. ctx.addQuoted(s);
  4046. bound.setFromTarget(target);
  4047. }
  4048. else if (boundRow->queryType()->isReference())
  4049. bound.expr.setown(createValue(no_typetransfer, LINK(refType), LINK(boundRow)));
  4050. else
  4051. bound.expr.setown(createValue(no_implicitcast, LINK(refType), LINK(boundRow)));
  4052. bound.count.setown(getSizetConstant(1));
  4053. }
  4054. IHqlExpression * HqlCppTranslator::ensureIteratedRowIsLive(BuildCtx & initctx, BuildCtx & searchctx, BuildCtx & iterctx, BoundRow * row, IHqlExpression * dataset, IHqlExpression * rowExpr)
  4055. {
  4056. //The problem is that we are iterating through the rows in a dataset, and we need to access the "best" row outside of the loop
  4057. //However subsequent iterations of the loop might invalidate the current row, so we need to ensure the best row is retained.
  4058. //There should really be a better way, but it isn't too bad with link counted rows.
  4059. bool needToPreserve = false;
  4060. IHqlExpression * ds = dataset;
  4061. while (ds && !needToPreserve)
  4062. {
  4063. if (ds->isDatarow())
  4064. {
  4065. if (initctx.queryAssociation(ds, AssocRow, NULL))
  4066. break;
  4067. }
  4068. else
  4069. {
  4070. if (initctx.queryMatchExpr(ds))
  4071. break;
  4072. }
  4073. switch (ds->getOperator())
  4074. {
  4075. case no_filter:
  4076. case no_grouped:
  4077. case no_stepped:
  4078. case no_sorted:
  4079. case no_distributed:
  4080. case no_preservemeta:
  4081. case no_choosen:
  4082. case no_selectnth: // can occur as the lhs of no_select
  4083. case no_compound_childnormalize:
  4084. case no_compound_selectnew:
  4085. case no_compound_childread:
  4086. case no_dataset_alias:
  4087. ds = ds->queryChild(0);
  4088. break;
  4089. case no_select:
  4090. if (ds->isDataset())
  4091. {
  4092. if (ds->hasAttribute(newAtom))
  4093. {
  4094. ds = ds->queryChild(0);
  4095. //don't walk complexds[1].childDataset<new> since the [1] will be generated as a temporary
  4096. // if (!ds->isDataset() && (ds->getOperator() != no_select))
  4097. // ds = NULL;
  4098. }
  4099. else
  4100. ds = NULL;
  4101. }
  4102. else
  4103. {
  4104. //ds.x.y, always walk to to ds.x
  4105. ds = ds->queryChild(0);
  4106. }
  4107. break;
  4108. case no_rows:
  4109. case no_call:
  4110. case no_externalcall:
  4111. case no_getresult:
  4112. case no_getgraphresult:
  4113. case no_alias:
  4114. ds = NULL;
  4115. break;
  4116. default:
  4117. needToPreserve = true;
  4118. break;
  4119. }
  4120. }
  4121. OwnedHqlExpr source = getPointer(row->queryBound());
  4122. if (!needToPreserve || initctx.hasAssociation(*row, false))
  4123. return source.getClear();
  4124. //If link counted, then declare a member that is a link counted row to ensure this row remains linked.
  4125. ITypeInfo * rowType = rowExpr->queryType();
  4126. if (hasLinkCountedModifier(row->queryBound()))
  4127. {
  4128. CHqlBoundTarget saveTarget;
  4129. createTempFor(initctx, rowType, saveTarget, typemod_wrapper, FormatLinkedDataset);
  4130. StringBuffer s;
  4131. generateExprCpp(s, saveTarget.expr);
  4132. s.append(".set(");
  4133. generateExprCpp(s, source).append(");");
  4134. iterctx.addQuoted(s);
  4135. return getPointer(saveTarget.expr);
  4136. }
  4137. BuildCtx childctx(iterctx);
  4138. childctx.addGroup();
  4139. Owned<BoundRow> tempRow = declareTempRow(childctx, childctx, rowExpr);
  4140. Owned<BoundRow> rowBuilder = createRowBuilder(childctx, tempRow);
  4141. OwnedHqlExpr sourceSelector = ensureActiveRow(row->querySelector());
  4142. buildAssign(childctx, rowBuilder->querySelector(), sourceSelector);
  4143. finalizeTempRow(childctx, tempRow, rowBuilder);
  4144. return getPointer(tempRow->queryBound());
  4145. }
  4146. IReferenceSelector * HqlCppTranslator::buildDatasetIndexViaIterator(BuildCtx & ctx, IHqlExpression * expr)
  4147. {
  4148. OwnedHqlExpr dataset = normalizeAnyDatasetAliases(querySkipDatasetMeta(expr->queryChild(0)));
  4149. IHqlExpression * index = expr->queryChild(1);
  4150. IHqlExpression * childDataset = dataset;
  4151. switch (dataset->getOperator())
  4152. {
  4153. case no_hqlproject:
  4154. //optimize selectnth(project(rows, t), n) to projectrow(selectnth(rows, n), t)
  4155. IHqlExpression * transform = dataset->queryChild(1);
  4156. if (!containsSkip(transform) && !expr->hasAttribute(_countProject_Atom))
  4157. childDataset = dataset->queryChild(0);
  4158. break;
  4159. }
  4160. //create a temporary
  4161. //Following works because rows are created as temporaries in the class, so still in scope outside the iterate loop.
  4162. //Not a strictly correct assumption - e.g., if ever done in the main process() code.
  4163. Owned<ITypeInfo> rowType = makeReferenceModifier(expr->getType());
  4164. OwnedHqlExpr rowExpr = ctx.getTempDeclare(rowType, NULL);
  4165. Owned<BoundRow> row = createBoundRow(expr, rowExpr);
  4166. CHqlBoundExpr boundCleared;
  4167. #ifdef CREATE_DEAULT_ROW_IF_NULL
  4168. buildDefaultRow(ctx, expr, boundCleared);
  4169. #else
  4170. buildNullRow(ctx, expr, boundCleared);
  4171. row->setConditional(true);
  4172. #endif
  4173. OwnedHqlExpr defaultRowPtr = getPointer(boundCleared.expr);
  4174. //Declare row for final level, iterate the appropriate number of times, and then assign and break.
  4175. BuildCtx initctx(ctx);
  4176. initctx.addGroup(); // add a group to allow a temporary to be declared later.
  4177. initctx.addAssign(rowExpr, defaultRowPtr);
  4178. HqlExprAssociation * savedMarker = ctx.associateExpr(queryConditionalRowMarker(), rowExpr);
  4179. BuildCtx iterctx(ctx);
  4180. bool done = false;
  4181. if (childDataset->getOperator() == no_rows) //hasOutOfLineModifier(dataset->queryType()))
  4182. {
  4183. CHqlBoundExpr boundDs;
  4184. buildDataset(ctx, childDataset, boundDs, FormatNatural);
  4185. if (boundDs.count && isArrayRowset(boundDs.expr->queryType()))
  4186. {
  4187. OwnedHqlExpr castIndex = ensureExprType(index, unsignedType);
  4188. OwnedHqlExpr adjustedIndex = adjustValue(castIndex, -1);
  4189. CHqlBoundExpr boundIndex;
  4190. buildExpr(ctx, adjustedIndex, boundIndex);
  4191. OwnedHqlExpr count = getBoundCount(boundDs); // could be serialized, so can't assume bound.count is set
  4192. OwnedHqlExpr test = createValue(no_gt, makeBoolType(), LINK(count), LINK(boundIndex.expr));
  4193. iterctx.addFilter(test);
  4194. if (dataset != childDataset)
  4195. {
  4196. Owned<ITypeInfo> datasetRowType = makeRowReferenceType(boundDs);
  4197. OwnedHqlExpr selectedRow = createValue(no_index, LINK(datasetRowType), LINK(boundDs.expr), LINK(boundIndex.expr));
  4198. OwnedHqlExpr projected = createRow(no_projectrow, createTranslated(selectedRow), createComma(LINK(dataset->queryChild(1)), LINK(querySelSeq(dataset))));
  4199. Owned<IReferenceSelector> newRow = buildNewRow(iterctx, projected);
  4200. OwnedHqlExpr newPtr = getPointer(newRow->queryRootRow()->queryBound());
  4201. iterctx.addAssign(rowExpr, newPtr);
  4202. }
  4203. else
  4204. {
  4205. OwnedHqlExpr selectedRow = createValue(no_index, LINK(rowType), LINK(boundDs.expr), LINK(boundIndex.expr));
  4206. iterctx.addAssign(rowExpr, selectedRow);
  4207. }
  4208. done = true;
  4209. }
  4210. }
  4211. if (!done)
  4212. {
  4213. BoundRow * chooseCursor;
  4214. //If choosing the first element, then no need to maintain a counter...
  4215. IValue * indexValue = index->queryValue();
  4216. if (indexValue && (indexValue->getIntValue() == 1))
  4217. chooseCursor = buildDatasetIterate(iterctx, dataset, true);
  4218. else
  4219. chooseCursor = buildDatasetIterate(iterctx, expr, true);
  4220. if (chooseCursor)
  4221. {
  4222. OwnedHqlExpr source = getPointer(chooseCursor->queryBound());
  4223. //MORE: Need casts because cursor may be (probably are) constant, but temporary isn't
  4224. //should somehow fnd out by looking at the cursors.
  4225. OwnedHqlExpr castLeftRow = createValue(no_implicitcast, LINK(rowType), LINK(source));
  4226. iterctx.addAssign(rowExpr, castLeftRow);
  4227. iterctx.addBreak();
  4228. }
  4229. }
  4230. ctx.removeAssociation(savedMarker);
  4231. ctx.associate(*row);
  4232. return createReferenceSelector(row);
  4233. }
  4234. IReferenceSelector * HqlCppTranslator::buildDatasetIndex(BuildCtx & ctx, IHqlExpression * expr)
  4235. {
  4236. HqlExprAssociation * match = ctx.queryAssociation(expr, AssocRow, NULL);
  4237. if (match)
  4238. return createReferenceSelector(static_cast<BoundRow *>(match));
  4239. #if 0
  4240. //Causes some queries (ncf10) to run out of memory, so disable for the moment.
  4241. OwnedHqlExpr optimized = optimizeHqlExpression(expr, getOptimizeFlags()|HOOcompoundproject);
  4242. if (optimized != expr)
  4243. return buildNewRow(ctx, optimized);
  4244. #endif
  4245. OwnedHqlExpr dataset = normalizeAnyDatasetAliases(expr->queryChild(0));
  4246. //Special cases:
  4247. //i) selecting row [1] from something that only has a single row
  4248. //ii) selecting row [n] from something that can be iterated.
  4249. //iii) row[1] from something sorted that can be iterated.
  4250. BoundRow * row = NULL;
  4251. if (isTrivialSelectN(expr))
  4252. {
  4253. BoundRow * row = NULL;
  4254. #if 0
  4255. //This could be a good idea - but again it can mess up cse since dataset never gets bound.
  4256. //Could enable if I implement cse on datasets within transforms.
  4257. // if (canIterateInline(&ctx, dataset))
  4258. // row = buildOptimizeSelectFirstRow(ctx, dataset);
  4259. #endif
  4260. if (!row)
  4261. {
  4262. CHqlBoundExpr bound;
  4263. buildDataset(ctx, dataset, bound, FormatNatural);
  4264. convertBoundDatasetToFirstRow(expr, bound);
  4265. row = bindRow(ctx, expr, bound.expr);
  4266. }
  4267. return createReferenceSelector(row);
  4268. }
  4269. else if (canIterateInline(&ctx, dataset))
  4270. {
  4271. //MORE? Following doesn't work for implicit normalize which iterates multiple levels
  4272. bool specialCase = false;
  4273. dataset.set(querySkipDatasetMeta(dataset));
  4274. switch (dataset->getOperator())
  4275. {
  4276. case no_select:
  4277. specialCase = !isMultiLevelDatasetSelector(expr, false);
  4278. break;
  4279. case no_if:
  4280. case no_createdictionary:
  4281. case no_inlinetable:
  4282. case no_join:
  4283. //Always creates a temporary, so don't use an iterator
  4284. specialCase = true;
  4285. break;
  4286. default:
  4287. specialCase = alwaysEvaluatesToBound(dataset);
  4288. break;
  4289. }
  4290. if (!specialCase)
  4291. return buildDatasetIndexViaIterator(ctx, expr);
  4292. }
  4293. else if (isSelectSortedTop(expr) && canIterateInline(&ctx, dataset->queryChild(0)))
  4294. {
  4295. return doBuildRowSelectTop(ctx, expr);
  4296. }
  4297. //MORE: Is this a good idea???
  4298. else if (!canProcessInline(&ctx, expr))
  4299. {
  4300. CHqlBoundExpr bound;
  4301. OwnedHqlExpr dsExpr = expr->isDatarow() ? createDatasetFromRow(LINK(expr)) : LINK(expr);
  4302. buildDataset(ctx, dsExpr, bound, FormatNatural);
  4303. convertBoundDatasetToFirstRow(expr, bound);
  4304. row = bindRow(ctx, expr, bound.expr);
  4305. }
  4306. if (!row)
  4307. {
  4308. Owned<IHqlCppDatasetCursor> cursor = createDatasetSelector(ctx, dataset);
  4309. row = cursor->buildSelectNth(ctx, expr);
  4310. if (!row)
  4311. {
  4312. CHqlBoundExpr boundCleared;
  4313. buildDefaultRow(ctx, dataset, boundCleared);
  4314. OwnedHqlExpr defaultRowPtr = getPointer(boundCleared.expr);
  4315. row = bindRow(ctx, expr, defaultRowPtr);
  4316. }
  4317. }
  4318. return createReferenceSelector(row);
  4319. }
  4320. IReferenceSelector * HqlCppTranslator::buildDatasetSelectMap(BuildCtx & ctx, IHqlExpression * expr)
  4321. {
  4322. HqlExprAssociation * match = ctx.queryAssociation(expr, AssocRow, NULL);
  4323. if (match)
  4324. return createReferenceSelector(static_cast<BoundRow *>(match));
  4325. OwnedHqlExpr dictionary = normalizeAnyDatasetAliases(expr->queryChild(0));
  4326. //MORE: This should really be a createDictionarySelector call.
  4327. Owned<IHqlCppDatasetCursor> cursor = createDatasetSelector(ctx, dictionary);
  4328. Owned<BoundRow> row = cursor->buildSelectMap(ctx, expr);
  4329. if (!row)
  4330. {
  4331. CHqlBoundExpr boundCleared;
  4332. buildDefaultRow(ctx, dictionary, boundCleared);
  4333. OwnedHqlExpr defaultRowPtr = getPointer(boundCleared.expr);
  4334. row.setown(bindRow(ctx, expr, defaultRowPtr));
  4335. }
  4336. return createReferenceSelector(row);
  4337. }
  4338. //---------------------------------------------------------------------------
  4339. IHqlExpression * HqlCppTranslator::buildGetLocalResult(BuildCtx & ctx, IHqlExpression * expr)
  4340. {
  4341. IHqlExpression * graphId = expr->queryChild(1);
  4342. IHqlExpression * resultNum = expr->queryChild(2);
  4343. Linked<ITypeInfo> exprType = queryUnqualifiedType(expr->queryType());
  4344. if (!hasLinkCountedModifier(exprType))
  4345. exprType.setown(makeAttributeModifier(LINK(exprType), getLinkCountedAttr()));
  4346. if (expr->hasAttribute(externalAtom))
  4347. {
  4348. IHqlExpression * resultInstance = queryAttributeChild(expr, externalAtom, 0);
  4349. HqlExprAssociation * matchedResults = ctx.queryMatchExpr(resultInstance);
  4350. if (!matchedResults)
  4351. {
  4352. //Very unusual - a result is required from a child query, but that child query is actually in
  4353. //the parent/grandparent. We need to evaluate in the parent instead.
  4354. CHqlBoundExpr match;
  4355. if (!buildExprInCorrectContext(ctx, expr, match, false))
  4356. throwUnexpected();
  4357. return match.getTranslatedExpr();
  4358. }
  4359. HqlExprArray args;
  4360. args.append(*LINK(matchedResults->queryExpr()));
  4361. args.append(*LINK(resultNum));
  4362. if (expr->isDictionary())
  4363. return bindFunctionCall(getChildQueryDictionaryResultId, args, exprType);
  4364. if (expr->isDatarow())
  4365. return bindFunctionCall(getChildQueryLinkedRowResultId, args, exprType);
  4366. return bindFunctionCall(getChildQueryLinkedResultId, args, exprType);
  4367. }
  4368. assertex(activeActivities.ordinality());
  4369. queryAddResultDependancy(activeActivities.tos(), graphId, resultNum);
  4370. SubGraphInfo * activeSubgraph = queryActiveSubGraph(ctx);
  4371. assertex(activeSubgraph && graphId == activeSubgraph->graphTag);
  4372. unique_id_t id = activeSubgraph->graphId;
  4373. EvalContext * instance = queryEvalContext(ctx);
  4374. OwnedHqlExpr retInstanceExpr;
  4375. if (instance && !insideOnCreate(ctx))
  4376. retInstanceExpr.setown(instance->createGraphLookup(id, false));
  4377. else
  4378. retInstanceExpr.setown(doCreateGraphLookup(ctx, ctx, id, "this", true));
  4379. HqlExprArray args;
  4380. args.append(*LINK(retInstanceExpr));
  4381. args.append(*LINK(resultNum));
  4382. if (expr->isDictionary())
  4383. return bindFunctionCall(getLocalDictionaryResultId, args, exprType);
  4384. if (expr->isDatarow())
  4385. return bindFunctionCall(getLocalLinkedRowResultId, args, exprType);
  4386. return bindFunctionCall(getLocalLinkedResultId, args, exprType);
  4387. }
  4388. void HqlCppTranslator::doBuildAssignGetGraphResult(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  4389. {
  4390. if (expr->hasAttribute(_streaming_Atom))
  4391. {
  4392. if (insideLibrary())
  4393. throwError(HQLERR_StreamInputUsedDirectly);
  4394. else
  4395. throwError(HQLERR_LoopTooComplexForParallel);
  4396. }
  4397. if (expr->hasAttribute(externalAtom))
  4398. {
  4399. OwnedHqlExpr call = buildGetLocalResult(ctx, expr);
  4400. buildExprAssign(ctx, target, call);
  4401. return;
  4402. }
  4403. if (!isCurrentActiveGraph(ctx, expr->queryChild(1)))
  4404. {
  4405. CHqlBoundExpr match;
  4406. if (!buildExprInCorrectContext(ctx, expr, match, false))
  4407. throwError(HQLERR_GraphContextNotFound);
  4408. assign(ctx, target, match);
  4409. return;
  4410. }
  4411. OwnedHqlExpr call = buildGetLocalResult(ctx, expr);
  4412. buildExprAssign(ctx, target, call);
  4413. }
  4414. void HqlCppTranslator::doBuildExprGetGraphResult(BuildCtx & ctx, IHqlExpression * expr, CHqlBoundExpr & tgt, ExpressionFormat format)
  4415. {
  4416. if (!expr->hasAttribute(externalAtom) && (!isCurrentActiveGraph(ctx, expr->queryChild(1)) || !insideOnStart(ctx)))
  4417. {
  4418. doBuildAliasValue(ctx, expr, tgt);
  4419. return;
  4420. if (!isCurrentActiveGraph(ctx, expr->queryChild(1)))
  4421. {
  4422. if (!buildExprInCorrectContext(ctx, expr, tgt, false))
  4423. throwError(HQLERR_GraphContextNotFound);
  4424. return;
  4425. }
  4426. }
  4427. OwnedHqlExpr call = buildGetLocalResult(ctx, expr);
  4428. switch (expr->queryType()->getTypeCode())
  4429. {
  4430. case type_dictionary:
  4431. case type_table:
  4432. case type_groupedtable:
  4433. buildTempExpr(ctx, call, tgt);
  4434. break;
  4435. default:
  4436. buildExpr(ctx, call, tgt);
  4437. break;
  4438. }
  4439. }
  4440. ABoundActivity * HqlCppTranslator::doBuildActivityGetGraphResult(BuildCtx & ctx, IHqlExpression * expr)
  4441. {
  4442. IHqlExpression * graphId = expr->queryChild(1);
  4443. IHqlExpression * resultNum = expr->queryChild(2);
  4444. ThorActivityKind activityKind = (expr->hasAttribute(_streaming_Atom) ? TAKlocalstreamread : TAKlocalresultread);
  4445. bool useImplementationClass = options.minimizeActivityClasses && (resultNum->getOperator() == no_constant);
  4446. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, activityKind, expr, "LocalResultRead");
  4447. if (useImplementationClass)
  4448. instance->setImplementationClass(newLocalResultReadArgId);
  4449. if (expr->hasAttribute(_loop_Atom))
  4450. {
  4451. if (isCurrentActiveGraph(ctx, graphId))
  4452. instance->graphLabel.set("Begin Loop");
  4453. else
  4454. instance->graphLabel.set("Outer Loop Input");
  4455. }
  4456. buildActivityFramework(instance);
  4457. buildInstancePrefix(instance);
  4458. if (!useImplementationClass)
  4459. doBuildUnsignedFunction(instance->classctx, "querySequence", resultNum);
  4460. else
  4461. instance->addConstructorParameter(resultNum);
  4462. addGraphIdAttribute(instance, ctx, graphId);
  4463. buildInstanceSuffix(instance);
  4464. queryAddResultDependancy(*instance->queryBoundActivity(), graphId, resultNum);
  4465. return instance->getBoundActivity();
  4466. }
  4467. ABoundActivity * HqlCppTranslator::doBuildActivitySetGraphDictionaryResult(BuildCtx & ctx, IHqlExpression * expr, bool isRoot)
  4468. {
  4469. IHqlExpression * dictionary = expr->queryChild(0);
  4470. IHqlExpression * dataset = dictionary->queryChild(0);
  4471. IHqlExpression * graphId = expr->queryChild(1);
  4472. IHqlExpression * resultNum = expr->queryChild(2);
  4473. bool isSpill = expr->hasAttribute(_spill_Atom);
  4474. ABoundActivity * parentActivity = activeActivities.ordinality() ? &activeActivities.tos() : NULL;
  4475. Owned<ABoundActivity> boundDataset = buildCachedActivity(ctx, dataset);
  4476. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, TAKdictionaryresultwrite, expr, "DictionaryResultWrite");
  4477. buildActivityFramework(instance, isRoot && !isSpill);
  4478. buildInstancePrefix(instance);
  4479. doBuildUnsignedFunction(instance->classctx, "querySequence", resultNum);
  4480. doBuildBoolFunction(instance->classctx, "usedOutsideGraph", !isSpill);
  4481. if (parentActivity && !insideRemoteGraph(ctx) && !isSpill)
  4482. {
  4483. addDependency(ctx, instance->queryBoundActivity(), parentActivity, childAtom, "Child");
  4484. }
  4485. buildDictionaryHashMember(instance->createctx, dictionary, "queryHashLookupInfo");
  4486. instance->addAttributeBool("_isSpill", isSpill);
  4487. if (targetRoxie())
  4488. addGraphIdAttribute(instance, ctx, graphId);
  4489. buildInstanceSuffix(instance);
  4490. buildConnectInputOutput(ctx, instance, boundDataset, 0, 0);
  4491. associateRemoteResult(*instance, graphId, resultNum);
  4492. return instance->getBoundActivity();
  4493. }
  4494. ABoundActivity * HqlCppTranslator::doBuildActivitySetGraphResult(BuildCtx & ctx, IHqlExpression * expr, bool isRoot)
  4495. {
  4496. IHqlExpression * dataset = expr->queryChild(0);
  4497. if (dataset->isDictionary())
  4498. return doBuildActivitySetGraphDictionaryResult(ctx, expr, isRoot);
  4499. IHqlExpression * graphId = expr->queryChild(1);
  4500. IHqlExpression * resultNum = expr->queryChild(2);
  4501. bool isSpill = expr->hasAttribute(_spill_Atom);
  4502. ABoundActivity * parentActivity = activeActivities.ordinality() ? &activeActivities.tos() : NULL;
  4503. Owned<ABoundActivity> boundDataset = buildCachedActivity(ctx, dataset);
  4504. bool useImplementationClass = options.minimizeActivityClasses;
  4505. Owned<ActivityInstance> instance;
  4506. if (expr->getOperator() == no_spillgraphresult)
  4507. {
  4508. instance.setown(new ActivityInstance(*this, ctx, TAKlocalresultspill, expr, "LocalResultSpill"));
  4509. }
  4510. else
  4511. {
  4512. instance.setown(new ActivityInstance(*this, ctx, TAKlocalresultwrite, expr, "LocalResultWrite"));
  4513. }
  4514. if (useImplementationClass)
  4515. instance->setImplementationClass(newLocalResultSpillArgId);
  4516. if (expr->hasAttribute(_loop_Atom))
  4517. instance->graphLabel.set("End Loop");
  4518. buildActivityFramework(instance, isRoot && !isSpill);
  4519. buildInstancePrefix(instance);
  4520. if (!useImplementationClass)
  4521. {
  4522. doBuildUnsignedFunction(instance->classctx, "querySequence", resultNum);
  4523. doBuildBoolFunction(instance->classctx, "usedOutsideGraph", !isSpill);
  4524. }
  4525. else
  4526. {
  4527. instance->addConstructorParameter(resultNum);
  4528. instance->addConstructorParameter(queryBoolExpr(!isSpill));
  4529. }
  4530. if (parentActivity && !insideRemoteGraph(ctx) && !isSpill)
  4531. {
  4532. const char * relationship;
  4533. if (expr->hasAttribute(_loop_Atom))
  4534. relationship = "Body";
  4535. else if (insideRemoteGraph(ctx))
  4536. relationship = "Remote";
  4537. else
  4538. relationship = "Child";
  4539. addDependency(ctx, instance->queryBoundActivity(), parentActivity, childAtom, relationship);
  4540. }
  4541. instance->addAttributeBool("_isSpill", isSpill);
  4542. instance->addAttributeBool("_fromChild", expr->hasAttribute(_accessedFromChild_Atom));
  4543. if (targetRoxie())
  4544. addGraphIdAttribute(instance, ctx, graphId);
  4545. buildInstanceSuffix(instance);
  4546. buildConnectInputOutput(ctx, instance, boundDataset, 0, 0);
  4547. associateRemoteResult(*instance, graphId, resultNum);
  4548. return instance->getBoundActivity();
  4549. }
  4550. ABoundActivity * HqlCppTranslator::doBuildActivityReturnResult(BuildCtx & ctx, IHqlExpression * expr, bool isRoot)
  4551. {
  4552. IHqlExpression * dataset = expr->queryChild(0);
  4553. ABoundActivity * parentActivity = activeActivities.ordinality() ? &activeActivities.tos() : NULL;
  4554. Owned<ABoundActivity> boundDataset = buildCachedActivity(ctx, dataset);
  4555. ThorActivityKind kind;
  4556. const char * helper;
  4557. if (dataset->isDataset())
  4558. {
  4559. kind = TAKdatasetresult;
  4560. helper = "DatasetResult";
  4561. }
  4562. else
  4563. {
  4564. kind = TAKrowresult;
  4565. helper = "RowResult";
  4566. }
  4567. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, kind, expr, helper);
  4568. buildActivityFramework(instance, isRoot);
  4569. buildInstancePrefix(instance);
  4570. if (parentActivity && !insideRemoteGraph(ctx))
  4571. addDependency(ctx, instance->queryBoundActivity(), parentActivity, childAtom, "Child");
  4572. buildInstanceSuffix(instance);
  4573. buildConnectInputOutput(ctx, instance, boundDataset, 0, 0);
  4574. return instance->getBoundActivity();
  4575. }
  4576. void HqlCppTranslator::doBuildAssignLoopCounter(BuildCtx & ctx, const CHqlBoundTarget & target, IHqlExpression * expr)
  4577. {
  4578. if (!isCurrentActiveGraph(ctx, expr->queryChild(0)))
  4579. {
  4580. CHqlBoundExpr match;
  4581. if (!buildExprInCorrectContext(ctx, expr, match, false))
  4582. throwError(HQLERR_GraphContextNotFound);
  4583. assign(ctx, target, match);
  4584. return;
  4585. }
  4586. HqlExprArray args;
  4587. OwnedHqlExpr call = bindFunctionCall(getGraphLoopCounterId, args);
  4588. buildExprAssign(ctx, target, call);
  4589. }
  4590. //---------------------------------------------------------------------------
  4591. ABoundActivity * HqlCppTranslator::doBuildActivityGetGraphLoopResult(BuildCtx & ctx, IHqlExpression * expr)
  4592. {
  4593. IHqlExpression * graphId = expr->queryChild(1);
  4594. IHqlExpression * resultNum = expr->queryChild(2);
  4595. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, TAKgraphloopresultread, expr, "GraphLoopResultRead");
  4596. buildActivityFramework(instance);
  4597. buildInstancePrefix(instance);
  4598. doBuildUnsignedFunction(instance->startctx, "querySequence", resultNum);
  4599. addGraphIdAttribute(instance, ctx, graphId);
  4600. buildInstanceSuffix(instance);
  4601. return instance->getBoundActivity();
  4602. }
  4603. ABoundActivity * HqlCppTranslator::doBuildActivitySetGraphLoopResult(BuildCtx & ctx, IHqlExpression * expr)
  4604. {
  4605. IHqlExpression * dataset = expr->queryChild(0);
  4606. IHqlExpression * graphId = expr->queryChild(1);
  4607. bool isSpill = expr->hasAttribute(_spill_Atom);
  4608. ABoundActivity * parentActivity = activeActivities.ordinality() ? &activeActivities.tos() : NULL;
  4609. Owned<ABoundActivity> boundDataset = buildCachedActivity(ctx, dataset);
  4610. bool useImplementationClass = options.minimizeActivityClasses;
  4611. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, TAKgraphloopresultwrite, expr, "GraphLoopResultWrite");
  4612. if (useImplementationClass)
  4613. instance->setImplementationClass(newGraphLoopResultWriteArgId);
  4614. buildActivityFramework(instance, true);
  4615. buildInstancePrefix(instance);
  4616. if (parentActivity && !insideRemoteGraph(ctx) && !isSpill)
  4617. addDependency(ctx, instance->queryBoundActivity(), parentActivity, childAtom, "Body");
  4618. if (targetRoxie())
  4619. addGraphIdAttribute(instance, ctx, graphId);
  4620. buildInstanceSuffix(instance);
  4621. buildConnectInputOutput(ctx, instance, boundDataset, 0, 0);
  4622. return instance->getBoundActivity();
  4623. }
  4624. //---------------------------------------------------------------------------
  4625. static IHqlExpression * queryResultExpr(IHqlExpression * expr)
  4626. {
  4627. loop
  4628. {
  4629. switch (expr->getOperator())
  4630. {
  4631. case no_compound:
  4632. expr = expr->queryChild(1);
  4633. break;
  4634. case no_subgraph:
  4635. expr = expr->queryChild(0);
  4636. break;
  4637. case no_returnresult:
  4638. return expr;
  4639. default:
  4640. throwUnexpectedOp(expr->getOperator());
  4641. }
  4642. }
  4643. }
  4644. ABoundActivity * HqlCppTranslator::doBuildActivityForceLocal(BuildCtx & ctx, IHqlExpression * expr)
  4645. {
  4646. IHqlExpression * child = expr->queryChild(0);
  4647. if (targetHThor() || (targetThor() && !insideChildQuery(ctx)))
  4648. {
  4649. WARNING(HQLWRN_LocalHasNoEffect);
  4650. return buildCachedActivity(ctx, child);
  4651. }
  4652. OwnedHqlExpr result = createValue(no_returnresult, makeVoidType(), LINK(child));
  4653. OwnedHqlExpr remote = resourceThorGraph(*this, result, RoxieCluster, 1, NULL);
  4654. unique_id_t localId = doBuildThorSubGraph(ctx, remote, SubGraphRemote);
  4655. Owned<ActivityInstance> instance = new ActivityInstance(*this, ctx, TAKlocalgraph, expr, "Null");
  4656. buildActivityFramework(instance);
  4657. buildInstancePrefix(instance);
  4658. instance->addAttributeInt("_subgraph", localId);
  4659. ActivityAssociation * match = static_cast<ActivityAssociation *>(ctx.queryAssociation(queryResultExpr(remote), AssocActivity, NULL));
  4660. assertex(match);
  4661. addDependency(ctx, match->activity, instance->queryBoundActivity(), childAtom);
  4662. buildInstanceSuffix(instance);
  4663. return instance->getBoundActivity();
  4664. }
  4665. void HqlCppTranslator::doBuildStmtApply(BuildCtx & ctx, IHqlExpression * expr)
  4666. {
  4667. IHqlExpression * dataset = expr->queryChild(0);
  4668. IHqlExpression * start = expr->queryAttribute(beforeAtom);
  4669. IHqlExpression * end = expr->queryAttribute(afterAtom);
  4670. if (start)
  4671. buildStmt(ctx, start->queryChild(0));
  4672. BuildCtx condctx(ctx);
  4673. buildDatasetIterate(condctx, dataset, false);
  4674. unsigned max = expr->numChildren();
  4675. for (unsigned i=1; i < max; i++)
  4676. {
  4677. IHqlExpression * cur = expr->queryChild(i);
  4678. if (!cur->isAttribute())
  4679. buildStmt(condctx, cur);
  4680. }
  4681. if (end)
  4682. buildStmt(ctx, end->queryChild(0));
  4683. }