yql_opt_utils.cpp 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335
  1. #include "yql_opt_utils.h"
  2. #include "yql_expr_optimize.h"
  3. #include "yql_expr_type_annotation.h"
  4. #include "yql_type_annotation.h"
  5. #include "yql_type_helpers.h"
  6. #include <yql/essentials/ast/yql_constraint.h>
  7. #include <yql/essentials/parser/pg_catalog/catalog.h>
  8. #include <yql/essentials/utils/log/log.h>
  9. #include <util/generic/set.h>
  10. #include <util/string/type.h>
  11. #include <limits>
  12. namespace NYql {
  13. using namespace NNodes;
  14. namespace {
  15. template<bool Distinct>
  16. TExprNode::TPtr KeepUniqueConstraint(TExprNode::TPtr node, const TExprNode& src, TExprContext& ctx) {
  17. if (const auto constraint = src.GetConstraint<TUniqueConstraintNodeBase<Distinct>>()) {
  18. const auto pos = node->Pos();
  19. TExprNode::TListType children(1U, std::move(node));
  20. for (const auto& sets : constraint->GetContent()) {
  21. TExprNode::TListType lists;
  22. lists.reserve(sets.size());
  23. for (const auto& set : sets) {
  24. TExprNode::TListType columns;
  25. columns.reserve(set.size());
  26. for (const auto& path : set) {
  27. if (1U == path.size())
  28. columns.emplace_back(ctx.NewAtom(pos, path.front()));
  29. else {
  30. TExprNode::TListType atoms(path.size());
  31. std::transform(path.cbegin(), path.cend(), atoms.begin(), [&](const std::string_view& name) { return ctx.NewAtom(pos, name); });
  32. columns.emplace_back(ctx.NewList(pos, std::move(atoms)));
  33. }
  34. }
  35. lists.emplace_back(ctx.NewList(pos, std::move(columns)));
  36. }
  37. children.emplace_back(ctx.NewList(pos, std::move(lists)));
  38. }
  39. return ctx.NewCallable(pos, TString("Assume") += TUniqueConstraintNodeBase<Distinct>::Name(), std::move(children));
  40. }
  41. return node;
  42. }
  43. TExprNode::TPtr KeepChoppedConstraint(TExprNode::TPtr node, const TExprNode& src, TExprContext& ctx) {
  44. if (const auto constraint = src.GetConstraint<TChoppedConstraintNode>()) {
  45. const auto pos = node->Pos();
  46. TExprNode::TListType children(1U, std::move(node));
  47. for (const auto& set : constraint->GetContent()) {
  48. TExprNode::TListType columns;
  49. columns.reserve(set.size());
  50. for (const auto& path : set) {
  51. if (1U == path.size())
  52. columns.emplace_back(ctx.NewAtom(pos, path.front()));
  53. else {
  54. TExprNode::TListType atoms(path.size());
  55. std::transform(path.cbegin(), path.cend(), atoms.begin(), [&](const std::string_view& name) { return ctx.NewAtom(pos, name); });
  56. columns.emplace_back(ctx.NewList(pos, std::move(atoms)));
  57. }
  58. }
  59. children.emplace_back(ctx.NewList(pos, std::move(columns)));
  60. }
  61. return ctx.NewCallable(pos, TString("Assume") += TChoppedConstraintNode::Name(), std::move(children));
  62. }
  63. return node;
  64. }
  65. TExprNodeBuilder GetterBuilder(TExprNodeBuilder parent, ui32 index, const TTypeAnnotationNode& type, TPartOfConstraintBase::TPathType path) {
  66. if (path.empty())
  67. return parent.Arg(index, "item");
  68. const auto& name = path.back();
  69. path.pop_back();
  70. const auto parentType = TPartOfConstraintBase::GetSubTypeByPath(path, type);
  71. YQL_ENSURE(parentType, "Wrong path '" << path << "' to component of: " << type);
  72. return GetterBuilder(parent.Callable(index, ETypeAnnotationKind::Struct == parentType->GetKind() ? "Member" : "Nth"), 0U, type, path).Atom(1, name).Seal();
  73. }
  74. const TExprNode& GetLiteralStructMember(const TExprNode& literal, const TExprNode& member) {
  75. for (const auto& child : literal.Children())
  76. if (&child->Head() == &member || child->Head().Content() == member.Content())
  77. return child->Tail();
  78. ythrow yexception() << "Member '" << member.Content() << "' not found in literal struct.";
  79. }
  80. }
  81. TExprNode::TPtr MakeBoolNothing(TPositionHandle position, TExprContext& ctx) {
  82. return ctx.NewCallable(position, "Nothing", {
  83. ctx.NewCallable(position, "OptionalType", {
  84. ctx.NewCallable(position, "DataType", {
  85. ctx.NewAtom(position, "Bool", TNodeFlags::Default) }) }) });
  86. }
  87. TExprNode::TPtr MakeNull(TPositionHandle position, TExprContext& ctx) {
  88. return ctx.NewCallable(position, "Null", {});
  89. }
  90. TExprNode::TPtr MakeConstMap(TPositionHandle position, const TExprNode::TPtr& input,
  91. const TExprNode::TPtr& value, TExprContext& ctx) {
  92. return ctx.Builder(position)
  93. .Callable("Map")
  94. .Add(0, input)
  95. .Lambda(1)
  96. .Param("x")
  97. .Set(value)
  98. .Seal()
  99. .Seal()
  100. .Build();
  101. }
  102. template <bool Bool>
  103. TExprNode::TPtr MakeBool(TPositionHandle position, TExprContext& ctx) {
  104. return ctx.NewCallable(position, "Bool", { ctx.NewAtom(position, Bool ? "true" : "false", TNodeFlags::Default) });
  105. }
  106. TExprNode::TPtr MakeBool(TPositionHandle position, bool value, TExprContext& ctx) {
  107. return value ? MakeBool<true>(position, ctx) : MakeBool<false>(position, ctx);
  108. }
  109. TExprNode::TPtr MakeOptionalBool(TPositionHandle position, bool value, TExprContext& ctx) {
  110. return ctx.NewCallable(position, "Just", { MakeBool(position, value, ctx)});
  111. }
  112. TExprNode::TPtr MakePgBool(TPositionHandle position, bool value, TExprContext& ctx) {
  113. return ctx.NewCallable(position, "PgConst", {
  114. ctx.NewAtom(position, value ? "t" : "f", TNodeFlags::Default),
  115. ctx.NewCallable(position, "PgType", { ctx.NewAtom(position, "bool")})
  116. });
  117. }
  118. TExprNode::TPtr MakeIdentityLambda(TPositionHandle position, TExprContext& ctx) {
  119. return ctx.Builder(position)
  120. .Lambda()
  121. .Param("arg")
  122. .Arg("arg")
  123. .Seal()
  124. .Build();
  125. }
  126. bool IsJustOrSingleAsList(const TExprNode& node) {
  127. return node.ChildrenSize() == 1U && node.IsCallable({"Just", "AsList"});
  128. }
  129. bool IsTransparentIfPresent(const TExprNode& node) {
  130. return (node.IsCallable("FlatMap") || (3U == node.ChildrenSize() && node.IsCallable("IfPresent") && node.Tail().IsCallable({"Nothing", "EmptyFrom"})))
  131. && node.Child(1U)->Tail().IsCallable("Just");
  132. }
  133. bool IsPredicateFlatMap(const TExprNode& node) {
  134. return node.IsCallable({"FlatListIf", "ListIf", "OptionalIf", "FlatOptionalIf"});
  135. }
  136. bool IsFilterFlatMap(const NNodes::TCoLambda& lambda) {
  137. const auto& arg = lambda.Args().Arg(0);
  138. const auto& body = lambda.Body();
  139. if (body.Maybe<TCoOptionalIf>() || body.Maybe<TCoListIf>()) {
  140. if (body.Ref().Child(1) == arg.Raw()) {
  141. return true;
  142. }
  143. }
  144. return false;
  145. }
  146. bool IsListReorder(const TExprNode& node) {
  147. return node.IsCallable({"Sort", "Reverse"});
  148. }
  149. // Check if the flat map is a simple rename flat map
  150. bool IsRenameFlatMap(const NNodes::TCoFlatMapBase& node, TExprNode::TPtr& structNode) {
  151. auto lambda = node.Lambda();
  152. if (!IsJustOrSingleAsList(lambda.Body().Ref())) {
  153. return false;
  154. }
  155. structNode = lambda.Body().Ref().Child(0);
  156. auto asStruct = TExprBase(structNode);
  157. if (!asStruct.Maybe<TCoAsStruct>()) {
  158. return false;
  159. }
  160. for (auto child : asStruct.Cast<TCoAsStruct>()) {
  161. if (!child.Item(1).Maybe<TCoMember>()) {
  162. return false;
  163. }
  164. auto member = child.Item(1).Cast<TCoMember>();
  165. if(member.Struct().Raw() != lambda.Args().Arg(0).Raw()) {
  166. return false;
  167. }
  168. }
  169. return true;
  170. }
  171. // Check if the flat map is a simple rename flat map and compute the mapping from new names to original ones
  172. bool IsRenameFlatMapWithMapping(const NNodes::TCoFlatMapBase& node, TExprNode::TPtr& structNode,
  173. THashMap<TString, TString> & mapping) {
  174. auto lambda = node.Lambda();
  175. if (!IsJustOrSingleAsList(lambda.Body().Ref())) {
  176. return false;
  177. }
  178. structNode = lambda.Body().Ref().Child(0);
  179. auto asStruct = TExprBase(structNode);
  180. if (!asStruct.Maybe<TCoAsStruct>()) {
  181. return false;
  182. }
  183. for (auto child : asStruct.Cast<TCoAsStruct>()) {
  184. if (!child.Item(1).Maybe<TCoMember>()) {
  185. return false;
  186. }
  187. auto member = child.Item(1).Cast<TCoMember>();
  188. if(member.Struct().Raw() != lambda.Args().Arg(0).Raw()) {
  189. return false;
  190. }
  191. auto to = child.Item(0).Cast<TCoAtom>();
  192. auto from = member.Name();
  193. if (to != from){
  194. mapping[to.StringValue()] = from.StringValue();
  195. }
  196. }
  197. return true;
  198. }
  199. // Check if the flat map is a simple rename flat map or a flatmap that also computes some
  200. // values in 1-1 fashion
  201. bool IsRenameOrApplyFlatMapWithMapping(const NNodes::TCoFlatMapBase& node, TExprNode::TPtr& structNode,
  202. THashMap<TString, TString> & mapping, TSet<TString> & apply) {
  203. auto lambda = node.Lambda();
  204. if (!IsJustOrSingleAsList(lambda.Body().Ref())) {
  205. return false;
  206. }
  207. structNode = lambda.Body().Ref().Child(0);
  208. auto asStruct = TExprBase(structNode);
  209. if (!asStruct.Maybe<TCoAsStruct>()) {
  210. return false;
  211. }
  212. for (auto child : asStruct.Cast<TCoAsStruct>()) {
  213. if (!child.Item(1).Maybe<TCoMember>()) {
  214. apply.insert(child.Item(0).Cast<TCoAtom>().StringValue());
  215. continue;
  216. }
  217. auto member = child.Item(1).Cast<TCoMember>();
  218. if(member.Struct().Raw() != lambda.Args().Arg(0).Raw()) {
  219. return false;
  220. }
  221. auto to = child.Item(0).Cast<TCoAtom>();
  222. auto from = member.Name();
  223. if (to != from){
  224. mapping[to.StringValue()] = from.StringValue();
  225. }
  226. }
  227. return true;
  228. }
  229. bool IsPassthroughFlatMap(const TCoFlatMapBase& flatmap, TMaybe<THashSet<TStringBuf>>* passthroughFields, bool analyzeJustMember) {
  230. return IsPassthroughLambda(flatmap.Lambda(), passthroughFields, analyzeJustMember);
  231. }
  232. bool IsPassthroughLambda(const TCoLambda& lambda, TMaybe<THashSet<TStringBuf>>* passthroughFields, bool analyzeJustMember) {
  233. auto body = lambda.Body();
  234. auto arg = lambda.Args().Arg(0);
  235. TMaybeNode<TExprBase> outItem;
  236. if (IsJustOrSingleAsList(body.Ref())) {
  237. outItem = body.Ref().Child(0);
  238. }
  239. if (body.Maybe<TCoOptionalIf>() || body.Maybe<TCoListIf>()) {
  240. outItem = body.Cast<TCoConditionalValueBase>().Value();
  241. }
  242. if (!outItem) {
  243. return false;
  244. }
  245. if (outItem.Cast().Raw() == arg.Raw()) {
  246. return true;
  247. }
  248. if (auto maybeStruct = outItem.Maybe<TCoAsStruct>()) {
  249. if (passthroughFields) {
  250. passthroughFields->ConstructInPlace();
  251. }
  252. for (auto child : maybeStruct.Cast()) {
  253. auto tuple = child.Cast<TCoNameValueTuple>();
  254. auto value = tuple.Value();
  255. if (analyzeJustMember && value.Maybe<TCoJust>()) {
  256. value = value.Cast<TCoJust>().Input();
  257. }
  258. if (!value.Maybe<TCoMember>()) {
  259. if (!passthroughFields) {
  260. return false;
  261. }
  262. continue;
  263. }
  264. auto member = value.Cast<TCoMember>();
  265. if (member.Struct().Raw() != arg.Raw() || member.Name().Value() != tuple.Name().Value()) {
  266. if (!passthroughFields) {
  267. return false;
  268. }
  269. } else {
  270. if (passthroughFields) {
  271. (*passthroughFields)->insert(member.Name().Value());
  272. }
  273. }
  274. }
  275. return true;
  276. }
  277. return false;
  278. }
  279. bool IsTablePropsDependent(const TExprNode& node) {
  280. bool found = false;
  281. VisitExpr(node, [&found](const TExprNode& n) {
  282. found = found || TCoTablePropBase::Match(&n) || (TCoMember::Match(&n) && TCoMember(&n).Name().Value().StartsWith("_yql_sys_"));
  283. return !found;
  284. });
  285. return found;
  286. }
  287. TExprNode::TPtr KeepColumnOrder(const TExprNode::TPtr& node, const TExprNode& src, TExprContext& ctx, const TTypeAnnotationContext& typeCtx) {
  288. auto columnOrder = typeCtx.LookupColumnOrder(src);
  289. if (!columnOrder) {
  290. return node;
  291. }
  292. return KeepColumnOrder(*columnOrder, node, ctx);
  293. }
  294. TExprNode::TPtr KeepColumnOrder(const TColumnOrder& order, const TExprNode::TPtr& node, TExprContext& ctx) {
  295. return ctx.Builder(node->Pos())
  296. .Callable("AssumeColumnOrder")
  297. .Add(0, node)
  298. .List(1)
  299. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  300. size_t index = 0;
  301. for (auto& [col, gen_col] : order) {
  302. parent
  303. .Atom(index++, gen_col);
  304. }
  305. return parent;
  306. })
  307. .Seal()
  308. .Seal()
  309. .Build();
  310. }
  311. template<class TFieldsSet>
  312. bool HaveFieldsSubset(const TExprNode::TPtr& start, const TExprNode& arg, TFieldsSet& usedFields, const TParentsMap& parentsMap, bool allowDependsOn) {
  313. const TTypeAnnotationNode* argType = RemoveOptionalType(arg.GetTypeAnn());
  314. if (argType->GetKind() != ETypeAnnotationKind::Struct) {
  315. return false;
  316. }
  317. if (&arg == start.Get()) {
  318. return false;
  319. }
  320. const auto inputStructType = argType->Cast<TStructExprType>();
  321. if (!IsDepended(*start, arg)) {
  322. return inputStructType->GetSize() > 0;
  323. }
  324. TNodeSet nodes;
  325. VisitExpr(start, [&](const TExprNode::TPtr& node) {
  326. nodes.insert(node.Get());
  327. return true;
  328. });
  329. const auto parents = parentsMap.find(&arg);
  330. YQL_ENSURE(parents != parentsMap.cend());
  331. for (const auto& parent : parents->second) {
  332. if (nodes.cend() == nodes.find(parent)) {
  333. continue;
  334. }
  335. if (parent->IsCallable("Member")) {
  336. if constexpr (std::is_same_v<typename TFieldsSet::key_type, typename TFieldsSet::value_type>)
  337. usedFields.emplace(parent->Tail().Content());
  338. else
  339. usedFields.emplace(parent->Tail().Content(), parent->TailPtr());
  340. } else if (allowDependsOn && parent->IsCallable("DependsOn")) {
  341. continue;
  342. } else {
  343. // unknown node
  344. usedFields.clear();
  345. return false;
  346. }
  347. }
  348. return usedFields.size() < inputStructType->GetSize();
  349. }
  350. template bool HaveFieldsSubset(const TExprNode::TPtr& start, const TExprNode& arg, TSet<TStringBuf>& usedFields, const TParentsMap& parentsMap,
  351. bool allowDependsOn);
  352. template bool HaveFieldsSubset(const TExprNode::TPtr& start, const TExprNode& arg, TSet<TString>& usedFields, const TParentsMap& parentsMap,
  353. bool allowDependsOn);
  354. template bool HaveFieldsSubset(const TExprNode::TPtr& start, const TExprNode& arg, std::map<std::string_view, TExprNode::TPtr>& usedFields,
  355. const TParentsMap& parentsMap, bool allowDependsOn);
  356. TExprNode::TPtr AddMembersUsedInside(const TExprNode::TPtr& start, const TExprNode& arg, TExprNode::TPtr&& members, const TParentsMap& parentsMap, TExprContext& ctx) {
  357. if (!members || !start || &arg == start.Get()) {
  358. return {};
  359. }
  360. if (RemoveOptionalType(arg.GetTypeAnn())->GetKind() != ETypeAnnotationKind::Struct) {
  361. return {};
  362. }
  363. if (!IsDepended(*start, arg)) {
  364. return std::move(members);
  365. }
  366. TNodeSet nodes;
  367. VisitExpr(start, [&](const TExprNode::TPtr& node) {
  368. if (!node->IsCallable("DependsOn"))
  369. nodes.emplace(node.Get());
  370. return true;
  371. });
  372. std::unordered_set<std::string_view> names(members->ChildrenSize());
  373. members->ForEachChild([&names](const TExprNode& name){ names.emplace(name.Content()); });
  374. const auto parents = parentsMap.find(&arg);
  375. YQL_ENSURE(parents != parentsMap.cend());
  376. TExprNode::TListType extra;
  377. for (const auto& parent : parents->second) {
  378. if (nodes.cend() == nodes.find(parent))
  379. continue;
  380. if (!parent->IsCallable("Member"))
  381. return {};
  382. if (names.emplace(parent->Tail().Content()).second)
  383. extra.emplace_back(parent->TailPtr());
  384. }
  385. if (!extra.empty()) {
  386. auto children = members->ChildrenList();
  387. std::move(extra.begin(), extra.end(), std::back_inserter(children));
  388. members = ctx.ChangeChildren(*members, std::move(children));
  389. }
  390. return std::move(members);
  391. }
  392. template<class TFieldsSet>
  393. TExprNode::TPtr FilterByFields(TPositionHandle position, const TExprNode::TPtr& input, const TFieldsSet& subsetFields,
  394. TExprContext& ctx, bool singleValue) {
  395. TExprNode::TListType fields;
  396. fields.reserve(subsetFields.size());
  397. for (const auto& x : subsetFields) {
  398. fields.emplace_back(ctx.NewAtom(position, x));
  399. }
  400. return ctx.NewCallable(position, singleValue ? "FilterMembers" : "ExtractMembers", { input, ctx.NewList(position, std::move(fields)) });
  401. }
  402. template TExprNode::TPtr FilterByFields(TPositionHandle position, const TExprNode::TPtr& input, const TSet<TStringBuf>& subsetFields, TExprContext& ctx, bool singleValue);
  403. template TExprNode::TPtr FilterByFields(TPositionHandle position, const TExprNode::TPtr& input, const TSet<TString>& subsetFields, TExprContext& ctx, bool singleValue);
  404. bool IsDependedImpl(const TExprNode* from, const TExprNode* to, TNodeMap<bool>& deps) {
  405. if (from == to)
  406. return true;
  407. auto [it, inserted] = deps.emplace(from, false);
  408. if (!inserted) {
  409. return it->second;
  410. }
  411. for (const auto& child : from->Children()) {
  412. if (IsDependedImpl(child.Get(), to, deps)) {
  413. return it->second = true;
  414. }
  415. }
  416. return false;
  417. }
  418. bool IsDepended(const TExprNode& from, const TExprNode& to) {
  419. TNodeMap<bool> deps;
  420. return IsDependedImpl(&from, &to, deps);
  421. }
  422. bool MarkDepended(const TExprNode& from, const TExprNode& to, TNodeMap<bool>& deps) {
  423. return IsDependedImpl(&from, &to, deps);
  424. }
  425. bool IsEmpty(const TExprNode& node, const TTypeAnnotationContext& typeCtx) {
  426. return typeCtx.IsConstraintCheckEnabled<TEmptyConstraintNode>() && node.Type() != TExprNode::Argument && node.GetConstraint<TEmptyConstraintNode>() != nullptr;
  427. }
  428. bool IsEmptyContainer(const TExprNode& node) {
  429. return node.IsCallable({"EmptyList", "EmptyDict"})
  430. || (1U == node.ChildrenSize() && node.IsCallable({"List", "Nothing", "EmptyIterator", "Dict", "EmptyFrom"}));
  431. }
  432. const TTypeAnnotationNode* RemoveOptionalType(const TTypeAnnotationNode* type) {
  433. if (!type || type->GetKind() != ETypeAnnotationKind::Optional) {
  434. return type;
  435. }
  436. return type->Cast<TOptionalExprType>()->GetItemType();
  437. }
  438. const TTypeAnnotationNode* RemoveAllOptionals(const TTypeAnnotationNode* type) {
  439. while (type && type->GetKind() == ETypeAnnotationKind::Optional) {
  440. type = type->Cast<TOptionalExprType>()->GetItemType();
  441. }
  442. return type;
  443. }
  444. TExprNode::TPtr GetSetting(const TExprNode& settings, const TStringBuf& name) {
  445. for (auto& setting : settings.Children()) {
  446. if (setting->ChildrenSize() != 0 && setting->Child(0)->Content() == name) {
  447. return setting;
  448. }
  449. }
  450. return nullptr;
  451. }
  452. TExprNode::TPtr FilterSettings(const TExprNode& settings, const THashSet<TStringBuf>& names, TExprContext& ctx) {
  453. TExprNode::TListType children;
  454. for (auto setting : settings.Children()) {
  455. if (setting->ChildrenSize() != 0 && names.contains(setting->Head().Content())) {
  456. children.push_back(setting);
  457. }
  458. }
  459. return ctx.NewList(settings.Pos(), std::move(children));
  460. }
  461. bool HasSetting(const TExprNode& settings, const TStringBuf& name) {
  462. return GetSetting(settings, name) != nullptr;
  463. }
  464. bool HasAnySetting(const TExprNode& settings, const THashSet<TString>& names) {
  465. for (auto& setting : settings.Children()) {
  466. if (setting->ChildrenSize() != 0 && names.contains(setting->Head().Content())) {
  467. return true;
  468. }
  469. }
  470. return false;
  471. }
  472. TExprNode::TPtr RemoveSetting(const TExprNode& settings, const TStringBuf& name, TExprContext& ctx) {
  473. TExprNode::TListType children;
  474. for (auto setting : settings.Children()) {
  475. if (setting->ChildrenSize() != 0 && setting->Head().Content() == name) {
  476. continue;
  477. }
  478. children.push_back(setting);
  479. }
  480. return ctx.NewList(settings.Pos(), std::move(children));
  481. }
  482. TExprNode::TPtr ReplaceSetting(const TExprNode& settings, TPositionHandle pos, const TString& name, const TExprNode::TPtr& value, TExprContext& ctx) {
  483. auto newSetting = value ? ctx.NewList(pos, { ctx.NewAtom(pos, name), value }) : ctx.NewList(pos, { ctx.NewAtom(pos, name) });
  484. return ReplaceSetting(settings, newSetting, ctx);
  485. }
  486. TExprNode::TPtr ReplaceSetting(const TExprNode& settings, const TExprNode::TPtr& newSetting, TExprContext& ctx) {
  487. TExprNode::TListType newChildren;
  488. const TStringBuf name = newSetting->Head().Content();
  489. for (auto setting : settings.Children()) {
  490. if (setting->ChildrenSize() != 0 && setting->Head().Content() == name) {
  491. continue;
  492. }
  493. newChildren.push_back(setting);
  494. }
  495. newChildren.push_back(newSetting);
  496. auto ret = ctx.NewList(settings.Pos(), std::move(newChildren));
  497. return ret;
  498. }
  499. TExprNode::TPtr AddSetting(const TExprNode& settings, TPositionHandle pos, const TString& name, const TExprNode::TPtr& value, TExprContext& ctx) {
  500. auto newSetting = value ? ctx.NewList(pos, { ctx.NewAtom(pos, name), value }) : ctx.NewList(pos, { ctx.NewAtom(pos, name) });
  501. return AddSetting(settings, newSetting, ctx);
  502. }
  503. TExprNode::TPtr AddSetting(const TExprNode& settings, const TExprNode::TPtr& newSetting, TExprContext& ctx) {
  504. auto newChildren = settings.ChildrenList();
  505. newChildren.push_back(newSetting);
  506. auto ret = ctx.NewList(settings.Pos(), std::move(newChildren));
  507. return ret;
  508. }
  509. TExprNode::TPtr MergeSettings(const TExprNode& settings1, const TExprNode& settings2, TExprContext& ctx) {
  510. auto newChildren = settings1.ChildrenList();
  511. newChildren.insert(
  512. newChildren.cend(),
  513. settings2.Children().begin(),
  514. settings2.Children().end());
  515. auto ret = ctx.NewList(settings1.Pos(), std::move(newChildren));
  516. return ret;
  517. }
  518. TMaybe<TIssue> ParseToDictSettings(const TExprNode& input, TExprContext& ctx, TMaybe<EDictType>& type, TMaybe<bool>& isMany, TMaybe<ui64>& itemsCount, bool& isCompact) {
  519. isCompact = false;
  520. auto settings = input.Child(3);
  521. if (settings->Type() != TExprNode::List) {
  522. return TIssue(ctx.GetPosition(settings->Pos()), TStringBuilder() << "Expected tuple, but got: " << input.Type());
  523. }
  524. for (auto& child : settings->Children()) {
  525. if (child->Type() == TExprNode::Atom) {
  526. if (child->Content() == "One") {
  527. isMany = false;
  528. }
  529. else if (child->Content() == "Many") {
  530. isMany = true;
  531. }
  532. else if (child->Content() == "Sorted") {
  533. type = EDictType::Sorted;
  534. }
  535. else if (child->Content() == "Hashed") {
  536. type = EDictType::Hashed;
  537. }
  538. else if (child->Content() == "Auto") {
  539. type = EDictType::Auto;
  540. }
  541. else if (child->Content() == "Compact") {
  542. isCompact = true;
  543. }
  544. else {
  545. return TIssue(ctx.GetPosition(child->Pos()), TStringBuilder() << "Unsupported option: " << child->Content());
  546. }
  547. } else if (child->Type() == TExprNode::List) {
  548. if (child->ChildrenSize() != 2) {
  549. return TIssue(ctx.GetPosition(child->Pos()), TStringBuilder() << "Expected list with 2 elemenst");
  550. }
  551. if (child->Child(0)->Content() == "ItemsCount") {
  552. ui64 count = 0;
  553. if (TryFromString(child->Child(1)->Content(), count)) {
  554. itemsCount = count;
  555. } else {
  556. return TIssue(ctx.GetPosition(child->Pos()), TStringBuilder() << "Bad 'ItemsCount' value: " << child->Child(1)->Content());
  557. }
  558. }
  559. else {
  560. return TIssue(ctx.GetPosition(child->Pos()), TStringBuilder() << "Bad option: " << child->Child(0)->Content());
  561. }
  562. } else {
  563. return TIssue(ctx.GetPosition(child->Pos()), TStringBuilder() << "Expected atom or list, but got: " << input.Type());
  564. }
  565. }
  566. if (!type || !isMany) {
  567. return TIssue(ctx.GetPosition(input.Pos()), TStringBuilder() << "Both options must be specified: Sorted/Hashed/Auto and Many/One");
  568. }
  569. return TMaybe<TIssue>();
  570. }
  571. EDictType SelectDictType(EDictType type, const TTypeAnnotationNode* keyType) {
  572. if (type != EDictType::Auto) {
  573. return type;
  574. }
  575. if (keyType->IsHashable() && keyType->IsEquatable()) {
  576. return EDictType::Hashed;
  577. }
  578. YQL_ENSURE(keyType->IsComparableInternal());
  579. return EDictType::Sorted;
  580. }
  581. TExprNode::TPtr MakeSingleGroupRow(const TExprNode& aggregateNode, TExprNode::TPtr reduced, TExprContext& ctx) {
  582. auto pos = aggregateNode.Pos();
  583. auto aggregatedColumns = aggregateNode.Child(2);
  584. auto opt = ctx.NewCallable(pos, "ToOptional", { reduced });
  585. TExprNode::TListType finalRowNodes;
  586. for (ui32 index = 0; index < aggregatedColumns->ChildrenSize(); ++index) {
  587. auto column = aggregatedColumns->Child(index);
  588. auto trait = column->Child(1);
  589. auto defVal = trait->Child(7);
  590. if (column->Child(0)->IsAtom()) {
  591. finalRowNodes.push_back(ctx.Builder(pos)
  592. .List()
  593. .Atom(0, column->Child(0)->Content())
  594. .Callable(1, "Coalesce")
  595. .Callable(0, "Member")
  596. .Add(0, opt)
  597. .Atom(1, column->Child(0)->Content())
  598. .Seal()
  599. .Add(1, defVal)
  600. .Seal()
  601. .Seal()
  602. .Build());
  603. } else {
  604. const auto& multiFields = column->Child(0)->Children();
  605. for (ui32 field = 0; field < multiFields.size(); ++field) {
  606. finalRowNodes.push_back(ctx.Builder(pos)
  607. .List()
  608. .Atom(0, multiFields[field]->Content())
  609. .Callable(1, "Member")
  610. .Add(0, opt)
  611. .Atom(1, multiFields[field]->Content())
  612. .Seal()
  613. .Seal()
  614. .Build());
  615. }
  616. }
  617. }
  618. return ctx.Builder(pos)
  619. .Callable("AsList")
  620. .Add(0, ctx.NewCallable(pos, "AsStruct", std::move(finalRowNodes)))
  621. .Seal()
  622. .Build();
  623. }
  624. bool UpdateStructMembers(TExprContext& ctx, const TExprNode::TPtr& node, const TStringBuf& goal, TExprNode::TListType& members, MemberUpdaterFunc updaterFunc, const TTypeAnnotationNode* nodeType) {
  625. if (!nodeType) {
  626. nodeType = node->GetTypeAnn();
  627. Y_DEBUG_ABORT_UNLESS(nodeType || !"Unset node type for UpdateStructMembers");
  628. }
  629. bool filtered = false;
  630. if (node->IsCallable("AsStruct")) {
  631. YQL_CLOG(DEBUG, Core) << "Enumerate struct literal for " << goal;
  632. for (ui32 i = 0; i < node->ChildrenSize(); ++i) {
  633. const auto memberNode = node->ChildPtr(i);
  634. const auto& memberName = memberNode->Child(0)->Content();
  635. TString useName = TString(memberName);
  636. if (updaterFunc && !updaterFunc(useName, memberNode->GetTypeAnn())) {
  637. filtered = true;
  638. continue;
  639. }
  640. if (useName == memberName) {
  641. members.push_back(memberNode);
  642. } else {
  643. auto useNameNode = ctx.NewAtom(node->Pos(), useName);
  644. members.push_back(ctx.NewList(node->Pos(), { useNameNode, memberNode->ChildPtr(1) }));
  645. }
  646. }
  647. } else if (nodeType->GetKind() == ETypeAnnotationKind::Optional) {
  648. YQL_CLOG(DEBUG, Core) << "Enumerate optional struct for " << goal;
  649. auto itemType = nodeType->Cast<TOptionalExprType>()->GetItemType();
  650. return UpdateStructMembers(ctx, node, goal, members, updaterFunc, itemType);
  651. } else {
  652. YQL_CLOG(DEBUG, Core) << "Enumerate struct object for " << goal;
  653. auto structType = nodeType->Cast<TStructExprType>();
  654. for (auto item : structType->GetItems()) {
  655. TString useName = TString(item->GetName());
  656. if (updaterFunc && !updaterFunc(useName, item->GetItemType())) {
  657. filtered = true;
  658. continue;
  659. }
  660. members.push_back(ctx.Builder(node->Pos())
  661. .List()
  662. .Atom(0, useName)
  663. .Callable(1, "Member")
  664. .Add(0, node)
  665. .Atom(1, item->GetName())
  666. .Seal()
  667. .Seal()
  668. .Build());
  669. }
  670. }
  671. return filtered;
  672. }
  673. TExprNode::TPtr ExpandRemoveMember(const TExprNode::TPtr& node, TExprContext& ctx) {
  674. const bool force = node->Content() == "ForceRemoveMember";
  675. const auto& removeMemberName = node->Child(1)->Content();
  676. MemberUpdaterFunc removeFunc = [&removeMemberName](TString& memberName, const TTypeAnnotationNode*) {
  677. return memberName != removeMemberName;
  678. };
  679. TExprNode::TListType members;
  680. if (!UpdateStructMembers(ctx, node->ChildPtr(0), node->Content(), members, removeFunc)) {
  681. if (!force) {
  682. YQL_ENSURE(false, "Unexpected member name: " << removeMemberName);
  683. }
  684. return node->ChildPtr(0);
  685. }
  686. return ctx.NewCallable(node->Pos(), "AsStruct", std::move(members));
  687. }
  688. TExprNode::TPtr ExpandRemoveMembers(const TExprNode::TPtr& node, TExprContext& ctx) {
  689. const auto& membersToRemove = node->Child(1);
  690. MemberUpdaterFunc removeFunc = [&membersToRemove](TString& memberName, const TTypeAnnotationNode*) {
  691. for (const auto& x : membersToRemove->Children()) {
  692. if (memberName == x->Content()) {
  693. return false;
  694. }
  695. }
  696. return true;
  697. };
  698. TExprNode::TListType members;
  699. if (!UpdateStructMembers(ctx, node->ChildPtr(0), node->Content(), members, removeFunc)) {
  700. return node->ChildPtr(0);
  701. }
  702. return ctx.NewCallable(node->Pos(), "AsStruct", std::move(members));
  703. }
  704. TExprNode::TPtr ExpandRemovePrefixMembers(const TExprNode::TPtr& node, TExprContext& ctx) {
  705. YQL_CLOG(DEBUG, Core) << "Expand " << node->Content();
  706. const TTypeAnnotationNode* targetItemType = GetSeqItemType(node->GetTypeAnn());
  707. bool isSequence = true;
  708. if (!targetItemType) {
  709. targetItemType = node->GetTypeAnn();
  710. isSequence = false;
  711. }
  712. auto rebuildStruct = [&](const TExprNode::TPtr& srcStruct, const TStructExprType* targetType) -> TExprNode::TPtr {
  713. TExprNode::TListType nonSystemMembers;
  714. for (auto item : targetType->GetItems()) {
  715. nonSystemMembers.push_back(
  716. Build<TCoNameValueTuple>(ctx, srcStruct->Pos())
  717. .Name()
  718. .Value(item->GetName())
  719. .Build()
  720. .Value<TCoMember>()
  721. .Struct(srcStruct)
  722. .Name()
  723. .Value(item->GetName())
  724. .Build()
  725. .Build()
  726. .Done().Ptr()
  727. );
  728. }
  729. return Build<TCoAsStruct>(ctx, srcStruct->Pos())
  730. .Add(std::move(nonSystemMembers))
  731. .Done()
  732. .Ptr();
  733. };
  734. if (targetItemType->GetKind() == ETypeAnnotationKind::Struct) {
  735. if (isSequence) {
  736. TExprNode::TListType nonSystemMembers;
  737. for (auto item : targetItemType->Cast<TStructExprType>()->GetItems()) {
  738. nonSystemMembers.push_back(ctx.NewAtom(node->Pos(), item->GetName()));
  739. }
  740. return Build<TCoExtractMembers>(ctx, node->Pos())
  741. .Input(node->HeadPtr())
  742. .Members()
  743. .Add(nonSystemMembers)
  744. .Build()
  745. .Done().Ptr();
  746. }
  747. return rebuildStruct(node->HeadPtr(), targetItemType->Cast<TStructExprType>());
  748. }
  749. YQL_ENSURE(targetItemType->GetKind() == ETypeAnnotationKind::Variant);
  750. const auto targetUnderType = targetItemType->Cast<TVariantExprType>()->GetUnderlyingType();
  751. TExprNode::TListType variants;
  752. TTypeAnnotationNode::TListType types;
  753. switch (targetUnderType->GetKind()) {
  754. case ETypeAnnotationKind::Tuple: {
  755. types = targetUnderType->Cast<TTupleExprType>()->GetItems();
  756. variants.resize(types.size());
  757. for (ui32 i = 0U; i < variants.size(); ++i) {
  758. variants[i] = ctx.NewAtom(node->Pos(), ToString(i), TNodeFlags::Default);
  759. }
  760. break;
  761. }
  762. case ETypeAnnotationKind::Struct: {
  763. const auto& items = targetUnderType->Cast<TStructExprType>()->GetItems();
  764. types.resize(items.size());
  765. variants.resize(items.size());
  766. for (ui32 i = 0U; i < items.size(); ++i) {
  767. types[i] = items[i]->GetItemType();
  768. variants[i] = ctx.NewAtom(node->Pos(), items[i]->GetName());
  769. }
  770. break;
  771. }
  772. default: break;
  773. }
  774. const auto type = ExpandType(node->Pos(), *targetItemType, ctx);
  775. if (isSequence) {
  776. return ctx.Builder(node->Pos())
  777. .Callable("Map")
  778. .Add(0, node->HeadPtr())
  779. .Lambda(1)
  780. .Param("varItem")
  781. .Callable("Visit")
  782. .Arg(0, "varItem")
  783. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  784. for (ui32 i = 0U; i < variants.size(); ++i) {
  785. parent.Add(1 + 2 * i, variants[i]);
  786. parent.Lambda(2 + 2 * i)
  787. .Param("item")
  788. .Callable("Variant")
  789. .Callable(0, "AsStruct")
  790. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  791. auto targetStructType = types[i]->Cast<TStructExprType>();
  792. for (size_t j = 0; j < targetStructType->GetItems().size(); ++j) {
  793. auto name = targetStructType->GetItems()[j]->GetName();
  794. parent.List(j)
  795. .Atom(0, name)
  796. .Callable(1, "Member")
  797. .Arg(0, "item")
  798. .Atom(1, name)
  799. .Seal()
  800. .Seal();
  801. }
  802. return parent;
  803. })
  804. .Seal()
  805. .Add(1, std::move(variants[i]))
  806. .Add(2, type)
  807. .Seal()
  808. .Seal();
  809. }
  810. return parent;
  811. })
  812. .Seal()
  813. .Seal()
  814. .Seal()
  815. .Build();
  816. }
  817. return ctx.Builder(node->Pos())
  818. .Callable("Visit")
  819. .Add(0, node->HeadPtr())
  820. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  821. for (ui32 i = 0U; i < variants.size(); ++i) {
  822. parent.Add(1 + 2 * i, variants[i]);
  823. parent.Lambda(2 + 2 * i)
  824. .Param("item")
  825. .Callable("Variant")
  826. .Callable(0, "AsStruct")
  827. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  828. auto targetStructType = types[i]->Cast<TStructExprType>();
  829. for (size_t j = 0; j < targetStructType->GetItems().size(); ++j) {
  830. auto name = targetStructType->GetItems()[j]->GetName();
  831. parent.List(j)
  832. .Atom(0, name)
  833. .Callable(1, "Member")
  834. .Arg(0, "item")
  835. .Atom(1, name)
  836. .Seal()
  837. .Seal();
  838. }
  839. return parent;
  840. })
  841. .Seal()
  842. .Add(1, std::move(variants[i]))
  843. .Add(2, type)
  844. .Seal()
  845. .Seal();
  846. }
  847. return parent;
  848. })
  849. .Seal()
  850. .Build();
  851. }
  852. TExprNode::TPtr ExpandFlattenMembers(const TExprNode::TPtr& node, TExprContext& ctx) {
  853. TExprNode::TListType members;
  854. for (auto& child : node->Children()) {
  855. auto prefix = child->Child(0)->Content();
  856. MemberUpdaterFunc addPrefixFunc = [&prefix](TString& memberName, const TTypeAnnotationNode*) {
  857. memberName = prefix + memberName;
  858. return true;
  859. };
  860. UpdateStructMembers(ctx, child->ChildPtr(1), "FlattenMembers", members, addPrefixFunc);
  861. }
  862. return ctx.NewCallable(node->Pos(), "AsStruct", std::move(members));
  863. }
  864. TExprNode::TPtr ExpandFlattenStructs(const TExprNode::TPtr& node, TExprContext& ctx) {
  865. TExprNode::TListType members;
  866. auto structObj = node->Child(0);
  867. for (auto& x : structObj->GetTypeAnn()->Cast<TStructExprType>()->GetItems()) {
  868. auto subMember = ctx.Builder(node->Pos())
  869. .Callable("Member")
  870. .Add(0, structObj)
  871. .Atom(1, x->GetName())
  872. .Seal()
  873. .Build();
  874. auto itemType = x->GetItemType();
  875. if (itemType->GetKind() == ETypeAnnotationKind::Optional) {
  876. itemType = itemType->Cast<TOptionalExprType>()->GetItemType();
  877. }
  878. if (itemType->GetKind() != ETypeAnnotationKind::Struct) {
  879. members.push_back(ctx.Builder(node->Pos())
  880. .List()
  881. .Atom(0, x->GetName())
  882. .Add(1, subMember)
  883. .Seal()
  884. .Build());
  885. continue;
  886. }
  887. UpdateStructMembers(ctx, subMember, "FlattenStructs", members, {}, x->GetItemType());
  888. }
  889. return ctx.NewCallable(node->Pos(), "AsStruct", std::move(members));
  890. }
  891. TExprNode::TPtr ExpandDivePrefixMembers(const TExprNode::TPtr& node, TExprContext& ctx) {
  892. auto prefixes = node->Child(1)->Children();
  893. MemberUpdaterFunc filterAndCutByPrefixFunc = [&prefixes](TString& memberName, const TTypeAnnotationNode*) {
  894. for (const auto& p : prefixes) {
  895. auto prefix = p->Content();
  896. if (memberName.StartsWith(prefix)) {
  897. memberName = memberName.substr(prefix.length());
  898. return true;
  899. }
  900. }
  901. return false;
  902. };
  903. TExprNode::TListType members;
  904. UpdateStructMembers(ctx, node->ChildPtr(0), "DivePrefixMembers", members, filterAndCutByPrefixFunc);
  905. auto ret = ctx.NewCallable(node->Pos(), "AsStruct", std::move(members));
  906. return ret;
  907. }
  908. TExprNode::TPtr ExpandAddMember(const TExprNode::TPtr& node, TExprContext& ctx) {
  909. TExprNode::TListType members;
  910. UpdateStructMembers(ctx, node->ChildPtr(0), "AddMember", members);
  911. members.push_back(ctx.NewList(node->Pos(), { node->ChildPtr(1), node->ChildPtr(2) }));
  912. return ctx.NewCallable(node->Pos(), "AsStruct", std::move(members));
  913. }
  914. TExprNode::TPtr ExpandReplaceMember(const TExprNode::TPtr& node, TExprContext& ctx) {
  915. const auto& removeMemberName = node->Child(1)->Content();
  916. MemberUpdaterFunc cloneFunc = [&removeMemberName](TString& memberName, const TTypeAnnotationNode*) {
  917. return memberName != removeMemberName;
  918. };
  919. TExprNode::TListType members;
  920. UpdateStructMembers(ctx, node->ChildPtr(0), "ReplaceMember", members, cloneFunc);
  921. members.push_back(ctx.NewList(node->Pos(), { node->ChildPtr(1), node->ChildPtr(2) }));
  922. auto ret = ctx.NewCallable(node->Pos(), "AsStruct", std::move(members));
  923. return ret;
  924. }
  925. TExprNode::TPtr ExpandFlattenByColumns(const TExprNode::TPtr& node, TExprContext& ctx) {
  926. ui32 shift = 0;
  927. TStringBuf mode = "auto";
  928. if (node->Child(0)->IsAtom()) {
  929. mode = node->Child(0)->Content();
  930. shift = 1;
  931. }
  932. auto structObj = node->ChildPtr(shift);
  933. TExprNode::TListType members;
  934. struct TFlattenInfo {
  935. const TTypeAnnotationNode* Type = nullptr;
  936. TExprNode::TPtr ArgNode = nullptr;
  937. TExprNode::TPtr ListMember = nullptr;
  938. TExprNode::TPtr ColumnNode = nullptr;
  939. bool ReplaceName = false;
  940. };
  941. TVector<TFlattenInfo> flattens;
  942. TMap<TString, size_t> name2Info;
  943. size_t flattenIndex = 0;
  944. for (auto iter = node->Children().begin() + 1 + shift; iter != node->Children().end(); ++iter) {
  945. auto flattenColumnNode = *iter;
  946. const bool haveAlias = flattenColumnNode->ChildrenSize() == 2;
  947. const TString flattenItemName = (haveAlias) ? TString(flattenColumnNode->Child(1)->Content()) : TString(flattenColumnNode->Content());
  948. TFlattenInfo flattenInfo;
  949. if (haveAlias) {
  950. flattenColumnNode = flattenColumnNode->Child(0);
  951. }
  952. else {
  953. flattenInfo.ReplaceName = true;
  954. }
  955. const auto useNameNode = ctx.NewAtom(node->Pos(), flattenItemName);
  956. flattenInfo.ArgNode = ctx.NewArgument(node->Pos(), flattenItemName);
  957. flattenInfo.ColumnNode = flattenColumnNode;
  958. members.push_back(ctx.NewList(node->Pos(), { useNameNode, flattenInfo.ArgNode }));
  959. flattens.emplace_back(std::move(flattenInfo));
  960. name2Info.insert({ TString(flattenColumnNode->Content()), flattenIndex++ });
  961. }
  962. MemberUpdaterFunc removeAndInfosUpdateFunc = [&flattens, &name2Info](TString& memberName, const TTypeAnnotationNode* type) {
  963. const auto iter = name2Info.find(memberName);
  964. if (iter == name2Info.end()) {
  965. return true;
  966. }
  967. TFlattenInfo& flattenInfo = flattens[iter->second];
  968. flattenInfo.Type = type;
  969. return !flattenInfo.ReplaceName;
  970. };
  971. UpdateStructMembers(ctx, structObj, "FlattenByColumns", members, removeAndInfosUpdateFunc);
  972. auto internalResult = ctx.NewCallable(node->Pos(), "AsStruct", std::move(members));
  973. TDeque<const TFlattenInfo*> flattenPriority;
  974. for (auto& flattenInfo : flattens) {
  975. bool isDict = false;
  976. bool isList = false;
  977. flattenInfo.ListMember = ctx.Builder(structObj->Pos())
  978. .Callable("Member")
  979. .Add(0, structObj)
  980. .Add(1, flattenInfo.ColumnNode)
  981. .Seal().Build();
  982. if (mode == "list" && flattenInfo.Type->GetKind() == ETypeAnnotationKind::Optional) {
  983. isList = true;
  984. flattenInfo.ListMember = ctx.Builder(structObj->Pos())
  985. .Callable("Coalesce")
  986. .Add(0, flattenInfo.ListMember)
  987. .Callable(1, "List")
  988. .Add(0, ExpandType(structObj->Pos(), *flattenInfo.Type->Cast<TOptionalExprType>()->GetItemType(), ctx))
  989. .Seal()
  990. .Seal()
  991. .Build();
  992. } else if (mode == "dict" && flattenInfo.Type->GetKind() == ETypeAnnotationKind::Optional) {
  993. isDict = true;
  994. flattenInfo.ListMember = ctx.Builder(structObj->Pos())
  995. .Callable("Coalesce")
  996. .Add(0, flattenInfo.ListMember)
  997. .Callable(1, "Dict")
  998. .Add(0, ExpandType(structObj->Pos(), *flattenInfo.Type->Cast<TOptionalExprType>()->GetItemType(), ctx))
  999. .Seal()
  1000. .Seal()
  1001. .Build();
  1002. } else {
  1003. isList = flattenInfo.Type->GetKind() == ETypeAnnotationKind::List;
  1004. isDict = flattenInfo.Type->GetKind() == ETypeAnnotationKind::Dict;
  1005. }
  1006. if (isDict) {
  1007. flattenInfo.ListMember = ctx.Builder(structObj->Pos())
  1008. .Callable("DictItems")
  1009. .Add(0, flattenInfo.ListMember)
  1010. .Seal().Build();
  1011. }
  1012. if (!isDict && !isList) {
  1013. flattenPriority.push_back(&flattenInfo);
  1014. } else {
  1015. flattenPriority.push_front(&flattenInfo);
  1016. }
  1017. }
  1018. TString operation = "OrderedMap";
  1019. for (const auto& infoPtr : flattenPriority) {
  1020. const TFlattenInfo& flattenInfo = *infoPtr;
  1021. auto mapLambda = ctx.NewLambda(node->Pos(), ctx.NewArguments(node->Pos(), { flattenInfo.ArgNode }), std::move(internalResult));
  1022. internalResult = ctx.Builder(node->Pos())
  1023. .Callable(operation)
  1024. .Add(0, flattenInfo.ListMember)
  1025. .Add(1, mapLambda)
  1026. .Seal().Build();
  1027. operation = "OrderedFlatMap";
  1028. }
  1029. return internalResult;
  1030. }
  1031. TExprNode::TPtr ExpandCastStruct(const TExprNode::TPtr& node, TExprContext& ctx) {
  1032. YQL_CLOG(DEBUG, Core) << "Expand " << node->Content();
  1033. auto targetType = node->Tail().GetTypeAnn()->Cast<TTypeExprType>()->GetType()->Cast<TStructExprType>();
  1034. TExprNode::TListType items;
  1035. for (auto item : targetType->GetItems()) {
  1036. auto nameAtom = ctx.NewAtom(node->Pos(), item->GetName());
  1037. auto tuple = ctx.NewList(node->Pos(), {
  1038. nameAtom, ctx.NewCallable(node->Pos(), "Member", { node->HeadPtr(), nameAtom }) });
  1039. items.push_back(std::move(tuple));
  1040. }
  1041. return ctx.NewCallable(node->Pos(), "AsStruct", std::move(items));
  1042. }
  1043. TExprNode::TListType GetOptionals(const TPositionHandle& pos, const TStructExprType& type, TExprContext& ctx) {
  1044. TExprNode::TListType result;
  1045. for (const auto& item : type.GetItems())
  1046. if (ETypeAnnotationKind::Optional == item->GetItemType()->GetKind())
  1047. result.emplace_back(ctx.NewAtom(pos, item->GetName()));
  1048. return result;
  1049. }
  1050. TExprNode::TListType GetOptionals(const TPositionHandle& pos, const TTupleExprType& type, TExprContext& ctx) {
  1051. TExprNode::TListType result;
  1052. if (const auto& items = type.GetItems(); !items.empty())
  1053. for (ui32 i = 0U; i < items.size(); ++i)
  1054. if (ETypeAnnotationKind::Optional == items[i]->GetKind())
  1055. result.emplace_back(ctx.NewAtom(pos, i));
  1056. return result;
  1057. }
  1058. TExprNode::TPtr ExpandSkipNullFields(const TExprNode::TPtr& node, TExprContext& ctx) {
  1059. YQL_ENSURE(node->IsCallable({"SkipNullMembers", "SkipNullElements"}));
  1060. YQL_CLOG(DEBUG, Core) << "Expand " << node->Content();
  1061. const bool isTuple = node->IsCallable("SkipNullElements");
  1062. TExprNode::TListType fields;
  1063. if (node->ChildrenSize() > 1) {
  1064. fields = node->Child(1)->ChildrenList();
  1065. } else if (isTuple) {
  1066. fields = GetOptionals(node->Pos(), *GetSeqItemType(node->Head().GetTypeAnn())->Cast<TTupleExprType>(), ctx);
  1067. } else {
  1068. fields = GetOptionals(node->Pos(), *GetSeqItemType(node->Head().GetTypeAnn())->Cast<TStructExprType>(), ctx);
  1069. }
  1070. if (fields.empty()) {
  1071. return node->HeadPtr();
  1072. }
  1073. return ctx.Builder(node->Pos())
  1074. .Callable("OrderedFilter")
  1075. .Add(0, node->HeadPtr())
  1076. .Lambda(1)
  1077. .Param("item")
  1078. .Callable("And")
  1079. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1080. for (ui32 i = 0U; i < fields.size(); ++i) {
  1081. parent
  1082. .Callable(i, "Exists")
  1083. .Callable(0, isTuple ? "Nth" : "Member")
  1084. .Arg(0, "item")
  1085. .Add(1, std::move(fields[i]))
  1086. .Seal()
  1087. .Seal();
  1088. }
  1089. return parent;
  1090. })
  1091. .Seal()
  1092. .Seal()
  1093. .Seal().Build();
  1094. }
  1095. void ExtractSimpleKeys(const TExprNode* keySelectorBody, const TExprNode* keySelectorArg, TVector<TStringBuf>& columns) {
  1096. if (keySelectorBody->IsList()) {
  1097. for (auto& child: keySelectorBody->Children()) {
  1098. if (child->IsCallable("Member") && child->Child(0) == keySelectorArg) {
  1099. columns.push_back(child->Child(1)->Content());
  1100. } else {
  1101. break;
  1102. }
  1103. }
  1104. } else if (keySelectorBody->IsCallable("Member") && keySelectorBody->Child(0) == keySelectorArg) {
  1105. columns.push_back(keySelectorBody->Child(1)->Content());
  1106. }
  1107. }
  1108. const TExprNode& SkipCallables(const TExprNode& node, const std::initializer_list<std::string_view>& skipCallables) {
  1109. const TExprNode* p = &node;
  1110. while (p->IsCallable(skipCallables)) {
  1111. p = &p->Head();
  1112. }
  1113. return *p;
  1114. }
  1115. namespace {
  1116. TExprNode::TPtr ApplyWithCastStructForFirstArg(const TExprNode::TPtr& node, const TTypeAnnotationNode& targetType, TExprContext& ctx) {
  1117. YQL_ENSURE(node->IsLambda());
  1118. TCoLambda lambda(node);
  1119. YQL_ENSURE(lambda.Args().Size() >= 1);
  1120. TPositionHandle pos = lambda.Pos();
  1121. TExprNodeList args = lambda.Args().Ref().ChildrenList();
  1122. TExprNode::TPtr body = lambda.Body().Ptr();
  1123. auto newArg = ctx.NewArgument(pos, "row");
  1124. auto cast = ctx.NewCallable(pos, "CastStruct", { newArg, ExpandType(pos, targetType, ctx) });
  1125. body = ctx.ReplaceNodes(std::move(body), {{ args.front().Get(), cast }});
  1126. args.front() = newArg;
  1127. auto result = ctx.NewLambda(pos, ctx.NewArguments(pos, std::move(args)), std::move(body));
  1128. return ctx.DeepCopyLambda(*result);
  1129. }
  1130. }
  1131. void ExtractSortKeyAndOrder(TPositionHandle pos, const TExprNode::TPtr& sortTraitsNode, TSortParams& sortParams, TExprContext& ctx)
  1132. {
  1133. ExtractSortKeyAndOrder(pos, sortTraitsNode, sortParams.Key, sortParams.Order, ctx);
  1134. }
  1135. void ExtractSortKeyAndOrder(TPositionHandle pos, const TExprNode::TPtr& sortTraitsNode, TExprNode::TPtr& sortKey, TExprNode::TPtr& sortOrder, TExprContext& ctx) {
  1136. if (sortTraitsNode->IsCallable("SortTraits")) {
  1137. TCoSortTraits sortTraits(sortTraitsNode);
  1138. auto lambdaInputType =
  1139. sortTraits.ListType().Ref().GetTypeAnn()->Cast<TTypeExprType>()->GetType()->Cast<TListExprType>()->GetItemType();
  1140. sortOrder = sortTraits.SortDirections().Ptr();
  1141. sortKey = ApplyWithCastStructForFirstArg(sortTraits.SortKeySelectorLambda().Ptr(), *lambdaInputType, ctx);
  1142. } else {
  1143. YQL_ENSURE(sortTraitsNode->IsCallable("Void"));
  1144. sortOrder = sortKey = ctx.NewCallable(pos, "Void", {});
  1145. }
  1146. }
  1147. void ExtractSessionWindowParams(TPositionHandle pos, TSessionWindowParams& sessionParams, TExprContext& ctx)
  1148. {
  1149. ExtractSessionWindowParams(pos, sessionParams.Traits, sessionParams.Key,
  1150. sessionParams.KeyType, sessionParams.ParamsType, sessionParams.SortTraits, sessionParams.Init,
  1151. sessionParams.Update, ctx);
  1152. }
  1153. void ExtractSessionWindowParams(TPositionHandle pos, const TExprNode::TPtr& sessionTraits, TExprNode::TPtr& sessionKey,
  1154. const TTypeAnnotationNode*& sessionKeyType, const TTypeAnnotationNode*& sessionParamsType, TExprNode::TPtr& sessionSortTraits, TExprNode::TPtr& sessionInit,
  1155. TExprNode::TPtr& sessionUpdate, TExprContext& ctx)
  1156. {
  1157. sessionKey = sessionSortTraits = sessionInit = sessionUpdate = {};
  1158. sessionKeyType = nullptr;
  1159. sessionParamsType = nullptr;
  1160. if (sessionTraits && sessionTraits->IsCallable("SessionWindowTraits")) {
  1161. TCoSessionWindowTraits swt(sessionTraits);
  1162. auto lambdaInputType =
  1163. swt.ListType().Ref().GetTypeAnn()->Cast<TTypeExprType>()->GetType()->Cast<TListExprType>()->GetItemType();
  1164. sessionKeyType = swt.Calculate().Ref().GetTypeAnn();
  1165. TVector<const TItemExprType*> sessionParamItems;
  1166. sessionParamItems.push_back(ctx.MakeType<TItemExprType>("start", sessionKeyType));
  1167. sessionParamItems.push_back(ctx.MakeType<TItemExprType>("state", swt.InitState().Ref().GetTypeAnn()));
  1168. sessionParamsType = ctx.MakeType<TStructExprType>(sessionParamItems);
  1169. sessionSortTraits = swt.SortSpec().Ptr();
  1170. sessionKey = ApplyWithCastStructForFirstArg(swt.Calculate().Ptr(), *lambdaInputType, ctx);
  1171. sessionInit = ApplyWithCastStructForFirstArg(swt.InitState().Ptr(), *lambdaInputType, ctx);
  1172. sessionUpdate = ApplyWithCastStructForFirstArg(swt.UpdateState().Ptr(), *lambdaInputType, ctx);
  1173. } else {
  1174. YQL_ENSURE(!sessionTraits || sessionTraits->IsCallable("Void"));
  1175. sessionSortTraits = ctx.NewCallable(pos, "Void", {});
  1176. }
  1177. }
  1178. TExprNode::TPtr BuildKeySelector(TPositionHandle pos, const TStructExprType& rowType, const TExprNode::TPtr& keyColumns, TExprContext& ctx) {
  1179. auto keyExtractorArg = ctx.NewArgument(pos, "item");
  1180. TExprNode::TListType tupleItems;
  1181. for (auto column : keyColumns->Children()) {
  1182. auto itemType = rowType.GetItems()[*rowType.FindItem(column->Content())]->GetItemType();
  1183. auto keyValue = ctx.NewCallable(pos, "Member", { keyExtractorArg, column });
  1184. if (RemoveOptionalType(itemType)->GetKind() != ETypeAnnotationKind::Data) {
  1185. keyValue = ctx.NewCallable(pos, "StablePickle", { keyValue });
  1186. }
  1187. tupleItems.push_back(keyValue);
  1188. }
  1189. TExprNode::TPtr tuple;
  1190. if (tupleItems.size() == 0) {
  1191. tuple = ctx.Builder(pos).Callable("Uint32").Atom(0, 0U).Seal().Build();
  1192. } else if (tupleItems.size() == 1) {
  1193. tuple = tupleItems[0];
  1194. } else {
  1195. tuple = ctx.NewList(pos, std::move(tupleItems));
  1196. }
  1197. return ctx.NewLambda(pos, ctx.NewArguments(pos, {keyExtractorArg}), std::move(tuple));
  1198. }
  1199. template <bool Cannonize, bool EnableNewOptimizers>
  1200. TExprNode::TPtr OptimizeIfPresent(const TExprNode::TPtr& node, TExprContext& ctx) {
  1201. auto optionals = node->ChildrenList();
  1202. optionals.resize(optionals.size() - 2U);
  1203. const auto& lambda = *node->Child(optionals.size());
  1204. if (lambda.Tail().GetDependencyScope()->second != &lambda) {
  1205. YQL_CLOG(DEBUG, Core) << node->Content() << " where then branch isn't depended on optional";
  1206. if (1U == optionals.size()) {
  1207. return ctx.Builder(node->Pos())
  1208. .Callable("If")
  1209. .Callable(0, "Exists")
  1210. .Add(0, std::move(optionals.front()))
  1211. .Seal()
  1212. .Add(1, lambda.TailPtr())
  1213. .Add(2, node->TailPtr())
  1214. .Seal().Build();
  1215. }
  1216. std::for_each(optionals.begin(), optionals.end(), [&ctx](TExprNode::TPtr& node) {
  1217. const auto p = node->Pos();
  1218. node = ctx.NewCallable(p, "Exists", {std::move(node)});
  1219. });
  1220. return ctx.Builder(node->Pos())
  1221. .Callable("If")
  1222. .Callable(0, "And")
  1223. .Add(std::move(optionals))
  1224. .Seal()
  1225. .Add(1, lambda.TailPtr())
  1226. .Add(2, node->TailPtr())
  1227. .Seal().Build();
  1228. }
  1229. if (std::any_of(optionals.cbegin(), optionals.cend(), [](const TExprNode::TPtr& node) { return node->IsCallable({"Nothing","EmptyFrom"}); })) {
  1230. YQL_CLOG(DEBUG, Core) << node->Content() << " over Nothing.";
  1231. return node->TailPtr();
  1232. }
  1233. if (std::any_of(optionals.cbegin(), optionals.cend(), [](const TExprNode::TPtr& node) { return node->IsCallable("Just"); })) {
  1234. YQL_CLOG(DEBUG, Core) << node->Content() << " over Just.";
  1235. TExprNode::TListType args;
  1236. args.reserve(optionals.size());
  1237. std::for_each(optionals.begin(), optionals.end(), [&args](TExprNode::TPtr& arg) {
  1238. if (arg->IsCallable("Just"))
  1239. arg = arg->HeadPtr();
  1240. else
  1241. args.emplace_back(std::move(arg));
  1242. });
  1243. if (args.empty()) {
  1244. TNodeOnNodeOwnedMap replaces(optionals.size());
  1245. for (ui32 i = 0U; i < optionals.size(); ++i)
  1246. replaces.emplace(lambda.Head().Child(i), std::move(optionals[i]));
  1247. return ctx.ReplaceNodes(lambda.TailPtr(), replaces);
  1248. }
  1249. auto simplify = ctx.Builder(node->Pos())
  1250. .Lambda()
  1251. .Params("items", args.size())
  1252. .Apply(lambda)
  1253. .Do([&](TExprNodeReplaceBuilder& parent) -> TExprNodeReplaceBuilder& {
  1254. for (auto i = 0U, j = 0U; i < optionals.size(); ++i) {
  1255. if (auto opt = std::move(optionals[i]))
  1256. parent.With(i, std::move(opt));
  1257. else
  1258. parent.With(i, "items", j++);
  1259. }
  1260. return parent;
  1261. })
  1262. .Seal()
  1263. .Seal().Build();
  1264. args.emplace_back(std::move(simplify));
  1265. args.emplace_back(node->TailPtr());
  1266. return ctx.ChangeChildren(*node, std::move(args));
  1267. }
  1268. if (3U == node->ChildrenSize()) {
  1269. if (&lambda.Tail() == &lambda.Head().Head()) {
  1270. YQL_CLOG(DEBUG, Core) << "Simplify " << node->Content() << " as Coalesce";
  1271. return ctx.NewCallable(node->Pos(), "Coalesce", {node->HeadPtr(), node->TailPtr()});
  1272. }
  1273. if (const auto& input = node->Head(); IsTransparentIfPresent(input)) {
  1274. YQL_CLOG(DEBUG, Core) << node->Content() << " over transparent " << input.Content();
  1275. return ctx.Builder(node->Pos())
  1276. .Callable(node->Content())
  1277. .Add(0, input.HeadPtr())
  1278. .Lambda(1)
  1279. .Param("item")
  1280. .Apply(*node->Child(1))
  1281. .With(0)
  1282. .ApplyPartial(input.Child(1)->HeadPtr(), input.Child(1)->Tail().HeadPtr())
  1283. .With(0, "item")
  1284. .Seal()
  1285. .Done()
  1286. .Seal()
  1287. .Seal()
  1288. .Add(2, node->TailPtr())
  1289. .Seal().Build();
  1290. }
  1291. if (lambda.Tail().IsCallable({"SafeCast", "StrictCast"}) && node->Tail().IsCallable({"Nothing","EmptyFrom"}) && &lambda.Tail().Head() == &lambda.Head().Head() &&
  1292. ETypeAnnotationKind::Optional != node->Head().GetTypeAnn()->Cast<TOptionalExprType>()->GetItemType()->GetKind()) {
  1293. YQL_CLOG(DEBUG, Core) << "Drop " << node->Content() << " with " << lambda.Tail().Content() << " and " << node->Tail().Content();
  1294. return ctx.ChangeChild(lambda.Tail(), 0U, node->HeadPtr());
  1295. }
  1296. if constexpr (Cannonize) {
  1297. if (node->Tail().IsCallable({"Nothing","EmptyFrom"}) && node->Tail().GetTypeAnn()->GetKind() != ETypeAnnotationKind::Pg) {
  1298. YQL_CLOG(DEBUG, Core) << node->Content() << " with else " << node->Tail().Content();
  1299. return ctx.NewCallable(node->Pos(), "FlatMap", { node->HeadPtr(), node->ChildPtr(1) });
  1300. }
  1301. }
  1302. }
  1303. if constexpr (!Cannonize && EnableNewOptimizers) {
  1304. if (lambda.Tail().IsCallable("IfPresent") && &node->Tail() == &lambda.Tail().Tail() && lambda.Tail().Head().GetDependencyScope()->second != &lambda) {
  1305. auto innerOptionals = lambda.Tail().ChildrenList();
  1306. innerOptionals.resize(innerOptionals.size() - 2U);
  1307. const auto find = std::find_if(innerOptionals.cbegin(), innerOptionals.cend(), [l = &lambda] (const TExprNode::TPtr& child) {
  1308. return child->GetDependencyScope()->second == l;
  1309. });
  1310. const auto count = std::distance(innerOptionals.cbegin(), find);
  1311. YQL_CLOG(DEBUG, Core) << node->Content() << " pull " << count << " arg(s) from inner " << lambda.Tail().Content();
  1312. auto& innerLambda = *lambda.Tail().Child(innerOptionals.size());
  1313. auto args = lambda.Head().ChildrenList();
  1314. auto innerArgs = innerLambda.Head().ChildrenList();
  1315. const auto splitter = [count](TExprNode::TListType& src, TExprNode::TListType& dst) {
  1316. dst.reserve(dst.size() + count);
  1317. auto it = src.begin();
  1318. std::advance(it, count);
  1319. std::move(src.begin(), it, std::back_inserter(dst));
  1320. src.erase(src.cbegin(), it);
  1321. };
  1322. splitter(innerArgs, args);
  1323. splitter(innerOptionals, optionals);
  1324. auto body = innerLambda.TailPtr();
  1325. if (!(innerArgs.empty() || innerOptionals.empty())) {
  1326. innerOptionals.emplace_back(ctx.DeepCopyLambda(*ctx.NewLambda(innerLambda.Pos(), ctx.NewArguments(innerLambda.Head().Pos(), std::move(innerArgs)), std::move(body))));
  1327. innerOptionals.emplace_back(lambda.Tail().TailPtr());
  1328. body = ctx.ChangeChildren(lambda.Tail(), std::move(innerOptionals));
  1329. }
  1330. optionals.emplace_back(ctx.DeepCopyLambda(*ctx.NewLambda(lambda.Pos(), ctx.NewArguments(lambda.Head().Pos(), std::move(args)), std::move(body))));
  1331. optionals.emplace_back(node->TailPtr());
  1332. return ctx.ChangeChildren(*node, std::move(optionals));
  1333. }
  1334. }
  1335. return node;
  1336. }
  1337. template TExprNode::TPtr OptimizeIfPresent<true, true>(const TExprNode::TPtr& node, TExprContext& ctx);
  1338. template TExprNode::TPtr OptimizeIfPresent<false, true>(const TExprNode::TPtr& node, TExprContext& ctx);
  1339. template TExprNode::TPtr OptimizeIfPresent<false, false>(const TExprNode::TPtr& node, TExprContext& ctx);
  1340. TExprNode::TPtr OptimizeExists(const TExprNode::TPtr& node, TExprContext& ctx) {
  1341. if (HasError(node->Head().GetTypeAnn(), ctx)) {
  1342. return TExprNode::TPtr();
  1343. }
  1344. if (node->Head().GetTypeAnn()->GetKind() == ETypeAnnotationKind::Void) {
  1345. YQL_CLOG(DEBUG, Core) << node->Content() << " over " << node->Head().Content();
  1346. return MakeBool<false>(node->Pos(), ctx);
  1347. }
  1348. if (node->Head().GetTypeAnn()->GetKind() == ETypeAnnotationKind::Null) {
  1349. YQL_CLOG(DEBUG, Core) << node->Content() << " over " << node->Head().Content();
  1350. return MakeBool<false>(node->Pos(), ctx);
  1351. }
  1352. if (node->Head().IsCallable({"Just", "PgConst"})) {
  1353. YQL_CLOG(DEBUG, Core) << node->Content() << " over " << node->Head().Content();
  1354. return MakeBool<true>(node->Pos(), ctx);
  1355. }
  1356. if (node->Head().IsCallable({"Nothing","EmptyFrom"})) {
  1357. YQL_CLOG(DEBUG, Core) << node->Content() << " over " << node->Head().Content();
  1358. return MakeBool<false>(node->Pos(), ctx);
  1359. }
  1360. if (node->Head().GetTypeAnn()->GetKind() != ETypeAnnotationKind::Optional &&
  1361. node->Head().GetTypeAnn()->GetKind() != ETypeAnnotationKind::Pg) {
  1362. YQL_CLOG(DEBUG, Core) << node->Content() << " over non-optional";
  1363. return MakeBool<true>(node->Pos(), ctx);
  1364. }
  1365. if (const auto& input = node->Head(); IsTransparentIfPresent(input)) {
  1366. YQL_CLOG(DEBUG, Core) << node->Content() << " over transparent " << input.Content();
  1367. return ctx.ChangeChildren(*node, {input.HeadPtr()});
  1368. }
  1369. return node;
  1370. }
  1371. bool WarnUnroderedSubquery(const TExprNode& unourderedSubquery, TExprContext& ctx) {
  1372. YQL_ENSURE(unourderedSubquery.IsCallable("UnorderedSubquery"));
  1373. auto issueCode = EYqlIssueCode::TIssuesIds_EIssueCode_YQL_ORDER_BY_WITHOUT_LIMIT_IN_SUBQUERY;
  1374. auto issue = TIssue(ctx.GetPosition(unourderedSubquery.Head().Pos()), "ORDER BY in subquery will be ignored");
  1375. auto subIssue = TIssue(ctx.GetPosition(unourderedSubquery.Pos()), "When used here");
  1376. SetIssueCode(issueCode, issue);
  1377. SetIssueCode(issueCode, subIssue);
  1378. issue.AddSubIssue(MakeIntrusive<TIssue>(subIssue));
  1379. return ctx.AddWarning(issue);
  1380. }
  1381. std::pair<TExprNode::TPtr, TExprNode::TPtr> ReplaceDependsOn(TExprNode::TPtr lambda, TExprContext& ctx, TTypeAnnotationContext* typeCtx) {
  1382. auto placeHolder = ctx.NewArgument(lambda->Pos(), "placeholder");
  1383. auto status = OptimizeExpr(lambda, lambda, [&placeHolder, arg = &lambda->Head().Head()](const TExprNode::TPtr& node, TExprContext& ctx) -> TExprNode::TPtr {
  1384. if (TCoDependsOn::Match(node.Get()) && &node->Head() == arg) {
  1385. return ctx.ChangeChild(*node, 0, TExprNode::TPtr(placeHolder));
  1386. }
  1387. return node;
  1388. }, ctx, TOptimizeExprSettings{typeCtx});
  1389. if (status.Level == IGraphTransformer::TStatus::Error) {
  1390. return std::pair<TExprNode::TPtr, TExprNode::TPtr>{};
  1391. }
  1392. return {placeHolder, lambda};
  1393. }
  1394. TStringBuf GetEmptyCollectionName(ETypeAnnotationKind kind) {
  1395. switch (kind) {
  1396. case ETypeAnnotationKind::Flow:
  1397. case ETypeAnnotationKind::Stream: return "EmptyIterator";
  1398. case ETypeAnnotationKind::List: return "List";
  1399. case ETypeAnnotationKind::Optional: return "Nothing";
  1400. case ETypeAnnotationKind::Dict: return "Dict";
  1401. case ETypeAnnotationKind::Pg: return "Nothing";
  1402. default: break;
  1403. }
  1404. return {};
  1405. }
  1406. namespace {
  1407. constexpr ui64 MaxWeight = std::numeric_limits<ui64>::max();
  1408. constexpr ui64 UnknownWeight = std::numeric_limits<ui32>::max();
  1409. ui64 GetTypeWeight(const TTypeAnnotationNode& type) {
  1410. switch (type.GetKind()) {
  1411. case ETypeAnnotationKind::Data:
  1412. switch (type.Cast<TDataExprType>()->GetSlot()) {
  1413. case NUdf::EDataSlot::Bool:
  1414. case NUdf::EDataSlot::Int8:
  1415. case NUdf::EDataSlot::Uint8: return 1;
  1416. case NUdf::EDataSlot::Int16:
  1417. case NUdf::EDataSlot::Uint16:
  1418. case NUdf::EDataSlot::Date: return 2;
  1419. case NUdf::EDataSlot::TzDate: return 3;
  1420. case NUdf::EDataSlot::Int32:
  1421. case NUdf::EDataSlot::Uint32:
  1422. case NUdf::EDataSlot::Float:
  1423. case NUdf::EDataSlot::Date32:
  1424. case NUdf::EDataSlot::Datetime: return 4;
  1425. case NUdf::EDataSlot::TzDatetime: return 5;
  1426. case NUdf::EDataSlot::Int64:
  1427. case NUdf::EDataSlot::Uint64:
  1428. case NUdf::EDataSlot::Double:
  1429. case NUdf::EDataSlot::Datetime64:
  1430. case NUdf::EDataSlot::Timestamp64:
  1431. case NUdf::EDataSlot::Interval64:
  1432. case NUdf::EDataSlot::Timestamp:
  1433. case NUdf::EDataSlot::Interval: return 8;
  1434. case NUdf::EDataSlot::TzTimestamp: return 9;
  1435. case NUdf::EDataSlot::Decimal: return 15;
  1436. case NUdf::EDataSlot::Uuid: return 16;
  1437. default: return 32;
  1438. }
  1439. case ETypeAnnotationKind::Optional:
  1440. return 1 + GetTypeWeight(*type.Cast<TOptionalExprType>()->GetItemType());
  1441. case ETypeAnnotationKind::Pg: {
  1442. const auto& typeDesc = NPg::LookupType(type.Cast<TPgExprType>()->GetId());
  1443. if (typeDesc.PassByValue) {
  1444. return typeDesc.TypeLen;
  1445. }
  1446. return UnknownWeight;
  1447. }
  1448. default:
  1449. return UnknownWeight;
  1450. }
  1451. }
  1452. } // namespace
  1453. const TItemExprType* GetLightColumn(const TStructExprType& type) {
  1454. ui64 weight = MaxWeight;
  1455. const TItemExprType* field = nullptr;
  1456. for (const auto& item : type.GetItems()) {
  1457. if (const auto w = GetTypeWeight(*item->GetItemType()); w < weight) {
  1458. weight = w;
  1459. field = item;
  1460. }
  1461. }
  1462. return field;
  1463. }
  1464. TVector<TStringBuf> GetCommonKeysFromVariantSelector(const NNodes::TCoLambda& lambda) {
  1465. if (auto maybeVisit = lambda.Body().Maybe<TCoVisit>()) {
  1466. if (maybeVisit.Input().Raw() == lambda.Args().Arg(0).Raw()) {
  1467. TVector<TStringBuf> members;
  1468. for (ui32 index = 1; index < maybeVisit.Raw()->ChildrenSize(); ++index) {
  1469. if (maybeVisit.Raw()->Child(index)->IsAtom()) {
  1470. ++index;
  1471. auto visitLambda = maybeVisit.Raw()->Child(index);
  1472. auto arg = visitLambda->Child(0)->Child(0);
  1473. TVector<TStringBuf> visitMembers;
  1474. if (TMaybeNode<TCoMember>(visitLambda->Child(1)).Struct().Raw() == arg) {
  1475. visitMembers.push_back(TCoMember(visitLambda->Child(1)).Name().Value());
  1476. }
  1477. else if (auto maybeList = TMaybeNode<TExprList>(visitLambda->Child(1))) {
  1478. for (auto item: maybeList.Cast()) {
  1479. if (item.Maybe<TCoMember>().Struct().Raw() == arg) {
  1480. visitMembers.push_back(item.Cast<TCoMember>().Name().Value());
  1481. } else {
  1482. return {};
  1483. }
  1484. }
  1485. }
  1486. if (visitMembers.empty()) {
  1487. return {};
  1488. } else if (members.empty()) {
  1489. members = visitMembers;
  1490. } else if (members != visitMembers) {
  1491. return {};
  1492. }
  1493. } else {
  1494. return {};
  1495. }
  1496. }
  1497. return members;
  1498. }
  1499. return {};
  1500. }
  1501. return {};
  1502. }
  1503. bool IsIdentityLambda(const TExprNode& lambda) {
  1504. return lambda.IsLambda() && lambda.Head().ChildrenSize() == 1 && &lambda.Head().Head() == &lambda.Tail();
  1505. }
  1506. TExprNode::TPtr MakeExpandMap(TPositionHandle pos, const TVector<TString>& columns, const TExprNode::TPtr& input, TExprContext& ctx) {
  1507. return ctx.Builder(pos)
  1508. .Callable("ExpandMap")
  1509. .Add(0, input)
  1510. .Lambda(1)
  1511. .Param("item")
  1512. .Do([&](TExprNodeBuilder& lambda) -> TExprNodeBuilder& {
  1513. ui32 i = 0U;
  1514. for (const auto& col : columns) {
  1515. lambda.Callable(i++, "Member")
  1516. .Arg(0, "item")
  1517. .Atom(1, col)
  1518. .Seal();
  1519. }
  1520. return lambda;
  1521. })
  1522. .Seal()
  1523. .Seal()
  1524. .Build();
  1525. }
  1526. TExprNode::TPtr MakeNarrowMap(TPositionHandle pos, const TVector<TString>& columns, const TExprNode::TPtr& input, TExprContext& ctx) {
  1527. return ctx.Builder(pos)
  1528. .Callable("NarrowMap")
  1529. .Add(0, input)
  1530. .Lambda(1)
  1531. .Params("fields", columns.size())
  1532. .Callable("AsStruct")
  1533. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1534. ui32 i = 0U;
  1535. for (const auto& col : columns) {
  1536. parent.List(i)
  1537. .Atom(0, col)
  1538. .Arg(1, "fields", i)
  1539. .Seal();
  1540. ++i;
  1541. }
  1542. return parent;
  1543. })
  1544. .Seal()
  1545. .Seal()
  1546. .Seal()
  1547. .Build();
  1548. }
  1549. TExprNode::TPtr FindNonYieldTransparentNodeImpl(const TExprNode::TPtr& root, const bool udfSupportsYield, const TNodeSet& flowSources) {
  1550. auto depensOnFlow = [&flowSources](const TExprNode::TPtr& node) {
  1551. return !!FindNode(node,
  1552. [](const TExprNode::TPtr& n) {
  1553. return !TCoDependsOn::Match(n.Get());
  1554. },
  1555. [&flowSources](const TExprNode::TPtr& n) {
  1556. return flowSources.contains(n.Get());
  1557. }
  1558. );
  1559. };
  1560. auto candidates = FindNodes(root,
  1561. [&flowSources](const TExprNode::TPtr& node) {
  1562. if (flowSources.contains(node.Get()) || TCoDependsOn::Match(node.Get())) {
  1563. return false;
  1564. }
  1565. if (node->ChildrenSize() > 0 && node->Head().GetTypeAnn()->GetKind() == ETypeAnnotationKind::World) {
  1566. return false;
  1567. }
  1568. return true;
  1569. },
  1570. [](const TExprNode::TPtr& node) {
  1571. return TCoCollect::Match(node.Get())
  1572. || TCoForwardList::Match(node.Get())
  1573. || TCoApply::Match(node.Get())
  1574. || TCoSwitch::Match(node.Get())
  1575. || node->IsCallable("DqReplicate")
  1576. || TCoPartitionByKeyBase::Match(node.Get())
  1577. || TCoChopper::Match(node.Get());
  1578. }
  1579. );
  1580. for (auto candidate: candidates) {
  1581. if (TCoCollect::Match(candidate.Get()) || TCoForwardList::Match(candidate.Get())) {
  1582. if (depensOnFlow(candidate->HeadPtr())) {
  1583. return candidate;
  1584. }
  1585. } else if (TCoApply::Match(candidate.Get())) {
  1586. if (AnyOf(candidate->Children().begin() + 1, candidate->Children().end(), depensOnFlow)) {
  1587. if (!IsFlowOrStream(*candidate)) {
  1588. while (TCoApply::Match(candidate.Get())) {
  1589. candidate = candidate->HeadPtr();
  1590. }
  1591. return candidate;
  1592. }
  1593. auto callableType = candidate.Get()->Head().GetTypeAnn()->Cast<TCallableExprType>();
  1594. for (const auto& arg : callableType->GetArguments()) {
  1595. if (arg.Type->GetKind() == ETypeAnnotationKind::Stream &&
  1596. arg.Flags & NUdf::ICallablePayload::TArgumentFlags::NoYield) {
  1597. return candidate;
  1598. }
  1599. }
  1600. if (!udfSupportsYield) {
  1601. while (TCoApply::Match(candidate.Get())) {
  1602. candidate = candidate->HeadPtr();
  1603. }
  1604. if (TCoScriptUdf::Match(candidate.Get())) {
  1605. return candidate;
  1606. }
  1607. }
  1608. }
  1609. } else if (TCoSwitch::Match(candidate.Get())) {
  1610. for (size_t i = 3; i < candidate->ChildrenSize(); i += 2) {
  1611. if (auto node = FindNonYieldTransparentNodeImpl(candidate->Child(i)->TailPtr(), udfSupportsYield, TNodeSet{&candidate->Child(i)->Head().Head()})) {
  1612. return node;
  1613. }
  1614. }
  1615. } else if (candidate->IsCallable("DqReplicate")) {
  1616. for (size_t i = 1; i < candidate->ChildrenSize(); ++i) {
  1617. if (auto node = FindNonYieldTransparentNodeImpl(candidate->Child(i)->TailPtr(), udfSupportsYield, TNodeSet{&candidate->Child(i)->Head().Head()})) {
  1618. return node;
  1619. }
  1620. }
  1621. } else if (TCoPartitionByKeyBase::Match(candidate.Get())) {
  1622. const auto handlerChild = candidate->Child(TCoPartitionByKeyBase::idx_ListHandlerLambda);
  1623. if (auto node = FindNonYieldTransparentNodeImpl(handlerChild->TailPtr(), udfSupportsYield, TNodeSet{&handlerChild->Head().Head()})) {
  1624. return node;
  1625. }
  1626. } else if (TCoChopper::Match(candidate.Get())) {
  1627. const auto handlerChild = candidate->Child(TCoChopper::idx_Handler);
  1628. if (auto node = FindNonYieldTransparentNodeImpl(handlerChild->TailPtr(), udfSupportsYield, TNodeSet{&handlerChild->Head().Tail()})) {
  1629. return node;
  1630. }
  1631. }
  1632. }
  1633. return {};
  1634. }
  1635. TExprNode::TPtr FindNonYieldTransparentNode(const TExprNode::TPtr& root, const TTypeAnnotationContext& typeCtx, TNodeSet flowSources) {
  1636. TExprNode::TPtr from = root;
  1637. if (root->IsLambda()) {
  1638. if (IsIdentityLambda(*root)) {
  1639. return {};
  1640. }
  1641. from = root->TailPtr();
  1642. // Add all flow lambda args
  1643. root->Head().ForEachChild([&flowSources](const TExprNode& arg) {
  1644. if (IsFlowOrStream(arg)) {
  1645. flowSources.insert(&arg);
  1646. }
  1647. });
  1648. }
  1649. static const THashSet<TStringBuf> WHITE_LIST = {"EmptyIterator"sv, TCoToStream::CallableName(), TCoIterator::CallableName(),
  1650. TCoToFlow::CallableName(), TCoApply::CallableName(), TCoNth::CallableName(), TCoMux::CallableName()};
  1651. // Find all other flow sources (readers)
  1652. auto sources = FindNodes(from,
  1653. [](const TExprNode::TPtr& node) {
  1654. return !node->IsCallable(WHITE_LIST)
  1655. && node->IsCallable()
  1656. && IsFlowOrStream(*node)
  1657. && (node->ChildrenSize() == 0 || !IsFlowOrStream(node->Head()));
  1658. }
  1659. );
  1660. std::for_each(sources.cbegin(), sources.cend(), [&flowSources](const TExprNode::TPtr& node) { flowSources.insert(node.Get()); });
  1661. if (flowSources.empty()) {
  1662. return {};
  1663. }
  1664. return FindNonYieldTransparentNodeImpl(from, typeCtx.UdfSupportsYield, flowSources);
  1665. }
  1666. bool IsYieldTransparent(const TExprNode::TPtr& root, const TTypeAnnotationContext& typeCtx) {
  1667. return !FindNonYieldTransparentNode(root, typeCtx);
  1668. }
  1669. TMaybe<bool> IsStrictNoRecurse(const TExprNode& node) {
  1670. if (node.IsCallable({"Unwrap", "Ensure", "ScriptUdf", "Error", "ErrorType"})) {
  1671. return false;
  1672. }
  1673. if (node.IsCallable("Udf")) {
  1674. return HasSetting(*node.Child(TCoUdf::idx_Settings), "strict");
  1675. }
  1676. return {};
  1677. }
  1678. bool IsStrict(const TExprNode::TPtr& root) {
  1679. // TODO: add TExprNode::IsStrict() method (with corresponding flag). Fill it as part of type annotation pass
  1680. bool isStrict = true;
  1681. VisitExpr(root, [&](const TExprNode::TPtr& node) {
  1682. if (node->IsCallable("AssumeStrict")) {
  1683. return false;
  1684. }
  1685. if (node->IsCallable("AssumeNonStrict")) {
  1686. isStrict = false;
  1687. return false;
  1688. }
  1689. auto maybeStrict = IsStrictNoRecurse(*node);
  1690. if (maybeStrict.Defined() && !*maybeStrict) {
  1691. isStrict = false;
  1692. }
  1693. return isStrict;
  1694. });
  1695. return isStrict;
  1696. }
  1697. bool HasDependsOn(const TExprNode::TPtr& root, const TExprNode::TPtr& arg) {
  1698. bool withDependsOn = false;
  1699. size_t insideDependsOn = 0;
  1700. VisitExpr(root, [&](const TExprNode::TPtr& node) {
  1701. if (node->IsCallable("DependsOn")) {
  1702. ++insideDependsOn;
  1703. } else if (insideDependsOn && node == arg) {
  1704. withDependsOn = true;
  1705. }
  1706. return !withDependsOn;
  1707. }, [&](const TExprNode::TPtr& node) {
  1708. if (node->IsCallable("DependsOn")) {
  1709. YQL_ENSURE(insideDependsOn > 0);
  1710. --insideDependsOn;
  1711. }
  1712. return true;
  1713. });
  1714. return withDependsOn;
  1715. }
  1716. template<bool Assume>
  1717. TExprNode::TPtr MakeSortConstraintImpl(TExprNode::TPtr node, const TSortedConstraintNode* sorted, const TTypeAnnotationNode* rowType, TExprContext& ctx) {
  1718. if (!(sorted && rowType))
  1719. return node;
  1720. const auto& constent = sorted->GetContent();
  1721. return ctx.Builder(node->Pos())
  1722. .Callable(Assume ? "AssumeSorted" : "Sort")
  1723. .Add(0, std::move(node))
  1724. .List(1)
  1725. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1726. size_t index = 0;
  1727. for (const auto& c : constent) {
  1728. parent.Callable(index++, "Bool")
  1729. .Atom(0, ToString(c.second), TNodeFlags::Default)
  1730. .Seal();
  1731. }
  1732. return parent;
  1733. })
  1734. .Seal()
  1735. .Lambda(2)
  1736. .Param("item")
  1737. .List()
  1738. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1739. size_t index = 0;
  1740. for (const auto& c : constent)
  1741. GetterBuilder(parent, index++, *rowType, c.first.front());
  1742. return parent;
  1743. })
  1744. .Seal()
  1745. .Seal()
  1746. .Seal()
  1747. .Build();
  1748. }
  1749. TExprNode::TPtr KeepSortedConstraint(TExprNode::TPtr node, const TSortedConstraintNode* sorted, const TTypeAnnotationNode* rowType, TExprContext& ctx) {
  1750. return MakeSortConstraintImpl<true>(std::move(node), sorted, rowType, ctx);
  1751. }
  1752. TExprNode::TPtr MakeSortByConstraint(TExprNode::TPtr node, const TSortedConstraintNode* sorted, const TTypeAnnotationNode* rowType, TExprContext& ctx) {
  1753. return MakeSortConstraintImpl<false>(std::move(node), sorted, rowType, ctx);
  1754. }
  1755. TExprNode::TPtr KeepConstraints(TExprNode::TPtr node, const TExprNode& src, TExprContext& ctx) {
  1756. auto res = KeepSortedConstraint(node, src.GetConstraint<TSortedConstraintNode>(), GetSeqItemType(src.GetTypeAnn()), ctx);
  1757. res = KeepChoppedConstraint(std::move(res), src, ctx);
  1758. res = KeepUniqueConstraint<true>(std::move(res), src, ctx);
  1759. res = KeepUniqueConstraint<false>(std::move(res), src, ctx);
  1760. return res;
  1761. }
  1762. bool HasOnlyOneJoinType(const TExprNode& joinTree, TStringBuf joinType) {
  1763. if (joinTree.IsAtom()) {
  1764. return true;
  1765. }
  1766. YQL_ENSURE(joinTree.Child(0)->IsAtom());
  1767. if (joinTree.Child(0)->Content() != joinType) {
  1768. return false;
  1769. }
  1770. return HasOnlyOneJoinType(*joinTree.Child(1), joinType) && HasOnlyOneJoinType(*joinTree.Child(2), joinType);
  1771. }
  1772. void OptimizeSubsetFieldsForNodeWithMultiUsage(const TExprNode::TPtr& node, const TParentsMap& parentsMap,
  1773. TNodeOnNodeOwnedMap& toOptimize, TExprContext& ctx,
  1774. std::function<TExprNode::TPtr(const TExprNode::TPtr&, const TExprNode::TPtr&, const TParentsMap&, TExprContext&)> handler)
  1775. {
  1776. // Ignore stream input, because it cannot be used multiple times
  1777. if (node->GetTypeAnn()->GetKind() != ETypeAnnotationKind::List) {
  1778. return;
  1779. }
  1780. auto itemType = node->GetTypeAnn()->Cast<TListExprType>()->GetItemType();
  1781. if (itemType->GetKind() != ETypeAnnotationKind::Struct) {
  1782. return;
  1783. }
  1784. auto structType = itemType->Cast<TStructExprType>();
  1785. auto it = parentsMap.find(node.Get());
  1786. if (it == parentsMap.cend() || it->second.size() <= 1) {
  1787. return;
  1788. }
  1789. TSet<TStringBuf> usedFields;
  1790. for (auto parent: it->second) {
  1791. if (auto maybeFlatMap = TMaybeNode<TCoFlatMapBase>(parent)) {
  1792. auto flatMap = maybeFlatMap.Cast();
  1793. TSet<TStringBuf> lambdaSubset;
  1794. if (!HaveFieldsSubset(flatMap.Lambda().Body().Ptr(), flatMap.Lambda().Args().Arg(0).Ref(), lambdaSubset, parentsMap)) {
  1795. return;
  1796. }
  1797. usedFields.insert(lambdaSubset.cbegin(), lambdaSubset.cend());
  1798. }
  1799. else if (auto maybeExtractMembers = TMaybeNode<TCoExtractMembers>(parent)) {
  1800. auto extractMembers = maybeExtractMembers.Cast();
  1801. for (auto member: extractMembers.Members()) {
  1802. usedFields.insert(member.Value());
  1803. }
  1804. }
  1805. else {
  1806. return;
  1807. }
  1808. if (usedFields.size() == structType->GetSize()) {
  1809. return;
  1810. }
  1811. }
  1812. TExprNode::TListType members;
  1813. for (auto column : usedFields) {
  1814. members.push_back(ctx.NewAtom(node->Pos(), column));
  1815. }
  1816. auto newInput = handler(node, ctx.NewList(node->Pos(), std::move(members)), parentsMap, ctx);
  1817. if (!newInput || newInput == node) {
  1818. return;
  1819. }
  1820. for (auto parent: it->second) {
  1821. if (TCoExtractMembers::Match(parent)) {
  1822. if (parent->GetTypeAnn()->Cast<TListExprType>()->GetItemType()->Cast<TStructExprType>()->GetSize() == usedFields.size()) {
  1823. toOptimize[parent] = newInput;
  1824. } else {
  1825. toOptimize[parent] = ctx.ChangeChild(*parent, 0, TExprNode::TPtr(newInput));
  1826. }
  1827. } else {
  1828. toOptimize[parent] = ctx.Builder(parent->Pos())
  1829. .Callable(parent->Content())
  1830. .Add(0, newInput)
  1831. .Lambda(1)
  1832. .Param("item")
  1833. .Apply(parent->ChildPtr(1)).With(0, "item").Seal()
  1834. .Seal()
  1835. .Seal()
  1836. .Build();
  1837. }
  1838. }
  1839. }
  1840. template<bool Ordered>
  1841. std::optional<std::pair<TPartOfConstraintBase::TPathType, ui32>> GetPathToKey(const TExprNode& body, const TExprNode::TChildrenType& args) {
  1842. if (body.IsArgument()) {
  1843. for (auto i = 0U; i < args.size(); ++i)
  1844. if (&body == args[i].Get())
  1845. return std::make_pair(TPartOfConstraintBase::TPathType(), i);
  1846. } else if (body.IsCallable({"Member","Nth"})) {
  1847. if (auto path = GetPathToKey<Ordered>(body.Head(), args)) {
  1848. path->first.emplace_back(body.Tail().Content());
  1849. return path;
  1850. } else if (const auto& head = SkipCallables(body.Head(), {"CastStruct","FilterMembers"}); head.IsCallable("AsStruct") && body.IsCallable("Member")) {
  1851. return GetPathToKey<Ordered>(GetLiteralStructMember(head, body.Tail()), args);
  1852. } else if (body.IsCallable("Nth") && body.Head().IsList()) {
  1853. return GetPathToKey<Ordered>(*body.Head().Child(FromString<ui32>(body.Tail().Content())), args);
  1854. } else if (body.IsCallable({"CastStruct","FilterMembers"})) {
  1855. return GetPathToKey<Ordered>(body.Head(), args);
  1856. }
  1857. } else if constexpr (!Ordered) {
  1858. if (body.IsCallable("StablePickle")) {
  1859. return GetPathToKey<Ordered>(body.Head(), args);
  1860. }
  1861. }
  1862. return std::nullopt;
  1863. }
  1864. template std::optional<std::pair<TPartOfConstraintBase::TPathType, ui32>> GetPathToKey<true>(const TExprNode& body, const TExprNode::TChildrenType& args);
  1865. template std::optional<std::pair<TPartOfConstraintBase::TPathType, ui32>> GetPathToKey<false>(const TExprNode& body, const TExprNode::TChildrenType& args);
  1866. template<bool Ordered>
  1867. std::optional<TPartOfConstraintBase::TPathType> GetPathToKey(const TExprNode& body, const TExprNode& arg) {
  1868. if (&body == &arg)
  1869. return TPartOfConstraintBase::TPathType();
  1870. if (body.IsCallable({"Member","Nth"})) {
  1871. if (auto path = GetPathToKey(body.Head(), arg)) {
  1872. path->emplace_back(body.Tail().Content());
  1873. return path;
  1874. }
  1875. }
  1876. if (body.IsCallable({"CastStruct","FilterMembers","Just","Unwrap"}))
  1877. return GetPathToKey<Ordered>(body.Head(), arg);
  1878. if (body.IsCallable("Member") && body.Head().IsCallable("AsStruct"))
  1879. return GetPathToKey<Ordered>(GetLiteralStructMember(body.Head(), body.Tail()), arg);
  1880. if (body.IsCallable("Nth") && body.Head().IsList())
  1881. return GetPathToKey<Ordered>(*body.Head().Child(FromString<ui32>(body.Tail().Content())), arg);
  1882. if (body.IsList() && 1U == body.ChildrenSize() && body.Head().IsCallable("Nth") && body.Head().Tail().IsAtom("0") &&
  1883. 1U == RemoveOptionality(*body.Head().Head().GetTypeAnn()).Cast<TTupleExprType>()->GetSize())
  1884. // Especialy for "Extract single item tuple from Condense1" optimizer.
  1885. return GetPathToKey(body.Head().Head(), arg);
  1886. if (body.IsCallable("AsStruct") && 1U == body.ChildrenSize() && body.Head().Tail().IsCallable("Member") &&
  1887. body.Head().Head().Content() == body.Head().Tail().Tail().Content() &&
  1888. 1U == RemoveOptionality(*body.Head().Tail().Head().GetTypeAnn()).Cast<TStructExprType>()->GetSize())
  1889. // Especialy for "Extract single item struct from Condense1" optimizer.
  1890. return GetPathToKey<Ordered>(body.Head().Tail().Head(), arg);
  1891. if (IsTransparentIfPresent(body) && &body.Head() == &arg)
  1892. return GetPathToKey<Ordered>(body.Child(1)->Tail().Head(), body.Child(1)->Head().Head());
  1893. if constexpr (!Ordered)
  1894. if (body.IsCallable("StablePickle"))
  1895. return GetPathToKey<Ordered>(body.Head(), arg);
  1896. return std::nullopt;
  1897. }
  1898. template<bool Ordered>
  1899. TPartOfConstraintBase::TSetType GetPathsToKeys(const TExprNode& body, const TExprNode& arg) {
  1900. TPartOfConstraintBase::TSetType keys;
  1901. if (body.IsList()) {
  1902. if (const auto size = body.ChildrenSize()) {
  1903. keys.reserve(size);
  1904. for (auto i = 0U; i < size; ++i)
  1905. if (auto path = GetPathToKey<Ordered>(*body.Child(i), arg))
  1906. keys.insert_unique(std::move(*path));
  1907. }
  1908. } else if constexpr (!Ordered) {
  1909. if (body.IsCallable("StablePickle")) {
  1910. return GetPathsToKeys<Ordered>(body.Head(), arg);
  1911. }
  1912. }
  1913. if (auto path = GetPathToKey<Ordered>(body, arg)) {
  1914. keys.insert_unique(std::move(*path));
  1915. }
  1916. return keys;
  1917. }
  1918. template TPartOfConstraintBase::TSetType GetPathsToKeys<true>(const TExprNode& body, const TExprNode& arg);
  1919. template TPartOfConstraintBase::TSetType GetPathsToKeys<false>(const TExprNode& body, const TExprNode& arg);
  1920. TVector<TString> GenNoClashColumns(const TStructExprType& source, TStringBuf prefix, size_t count) {
  1921. YQL_ENSURE(prefix.StartsWith("_yql"));
  1922. TSet<size_t> existing;
  1923. for (auto& item : source.GetItems()) {
  1924. TStringBuf column = item->GetName();
  1925. if (column.SkipPrefix(prefix)) {
  1926. size_t idx;
  1927. if (TryFromString(column, idx)) {
  1928. existing.insert(idx);
  1929. }
  1930. }
  1931. }
  1932. size_t current = 0;
  1933. TVector<TString> result;
  1934. auto it = existing.cbegin();
  1935. while (count) {
  1936. if (it == existing.cend() || current < *it) {
  1937. result.push_back(TStringBuilder() << prefix << current);
  1938. --count;
  1939. } else {
  1940. ++it;
  1941. }
  1942. YQL_ENSURE(!count || (current + 1 > current));
  1943. ++current;
  1944. }
  1945. return result;
  1946. }
  1947. bool CheckSupportedTypes(
  1948. const TTypeAnnotationNode::TListType& typesToCheck,
  1949. const TSet<TString>& supportedTypes,
  1950. const TSet<NUdf::EDataSlot>& supportedDataTypes,
  1951. std::function<void(const TString&)> unsupportedTypeHandler,
  1952. bool allowNestedOptionals
  1953. ) {
  1954. TSet<ETypeAnnotationKind> supported;
  1955. for (const auto &e: supportedTypes) {
  1956. if (e == "pg") {
  1957. supported.insert(ETypeAnnotationKind::Pg);
  1958. } else if (e == "tuple") {
  1959. supported.emplace(ETypeAnnotationKind::Tuple);
  1960. } else if (e == "struct") {
  1961. supported.emplace(ETypeAnnotationKind::Struct);
  1962. } else if (e == "dict") {
  1963. supported.emplace(ETypeAnnotationKind::Dict);
  1964. } else if (e == "list") {
  1965. supported.emplace(ETypeAnnotationKind::List);
  1966. } else if (e == "variant") {
  1967. supported.emplace(ETypeAnnotationKind::Variant);
  1968. } else {
  1969. // Unknown type
  1970. unsupportedTypeHandler(TStringBuilder() << "unknown type: " << e);
  1971. return false;
  1972. }
  1973. }
  1974. if (supportedDataTypes.size()) {
  1975. supported.emplace(ETypeAnnotationKind::Data);
  1976. }
  1977. auto checkType = [&] (const TTypeAnnotationNode* type) {
  1978. if (type->GetKind() == ETypeAnnotationKind::Data) {
  1979. if (!supported.contains(ETypeAnnotationKind::Data)) {
  1980. unsupportedTypeHandler(TStringBuilder() << "unsupported data types");
  1981. return false;
  1982. }
  1983. if (!supportedDataTypes.contains(type->Cast<TDataExprType>()->GetSlot())) {
  1984. unsupportedTypeHandler(TStringBuilder() << "unsupported data type: " << type->Cast<TDataExprType>()->GetSlot());
  1985. return false;
  1986. }
  1987. } else if (type->GetKind() == ETypeAnnotationKind::Pg) {
  1988. if (!supported.contains(ETypeAnnotationKind::Pg)) {
  1989. unsupportedTypeHandler(TStringBuilder() << "unsupported pg");
  1990. return false;
  1991. }
  1992. auto name = type->Cast<TPgExprType>()->GetName();
  1993. if (name == "float4" && !supportedDataTypes.contains(NUdf::EDataSlot::Float)) {
  1994. unsupportedTypeHandler(TStringBuilder() << "PgFloat4 unsupported yet since float is no supported");
  1995. return false;
  1996. }
  1997. } else {
  1998. unsupportedTypeHandler(TStringBuilder() << "unsupported annotation kind: " << type->GetKind());
  1999. return false;
  2000. }
  2001. return true;
  2002. };
  2003. TVector<const TTypeAnnotationNode*> stack(typesToCheck.begin(), typesToCheck.end());
  2004. while (!stack.empty()) {
  2005. auto el = stack.back();
  2006. stack.pop_back();
  2007. if (el->GetKind() == ETypeAnnotationKind::Optional) {
  2008. auto elInnerType = el->Cast<TOptionalExprType>()->GetItemType();
  2009. if (!allowNestedOptionals && elInnerType->GetKind() == ETypeAnnotationKind::Optional) {
  2010. unsupportedTypeHandler(TStringBuilder() << "nested optionals are unsupported");
  2011. }
  2012. stack.push_back(elInnerType);
  2013. continue;
  2014. }
  2015. if (!supported.contains(el->GetKind())) {
  2016. unsupportedTypeHandler(TStringBuilder() << "unsupported " << el->GetKind());
  2017. return false;
  2018. }
  2019. if (el->GetKind() == ETypeAnnotationKind::Tuple) {
  2020. for (auto e: el->Cast<TTupleExprType>()->GetItems()) {
  2021. stack.push_back(e);
  2022. }
  2023. continue;
  2024. } else if (el->GetKind() == ETypeAnnotationKind::Struct) {
  2025. for (auto e: el->Cast<TStructExprType>()->GetItems()) {
  2026. stack.push_back(e->GetItemType());
  2027. }
  2028. continue;
  2029. } else if (el->GetKind() == ETypeAnnotationKind::List) {
  2030. stack.push_back(el->Cast<TListExprType>()->GetItemType());
  2031. continue;
  2032. } else if (el->GetKind() == ETypeAnnotationKind::Dict) {
  2033. stack.push_back(el->Cast<TDictExprType>()->GetKeyType());
  2034. stack.push_back(el->Cast<TDictExprType>()->GetPayloadType());
  2035. continue;
  2036. } else if (el->GetKind() == ETypeAnnotationKind::Variant) {
  2037. stack.push_back(el->Cast<TVariantExprType>()->GetUnderlyingType());
  2038. continue;
  2039. }
  2040. if (!checkType(el)) {
  2041. return false;
  2042. }
  2043. }
  2044. return true;
  2045. }
  2046. }