hqlcppds.cpp 165 KB

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