hqlcppds.cpp 181 KB

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