yql_opt_utils.cpp 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310
  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. || TCoPartitionsByKeys::Match(node.Get());
  1577. }
  1578. );
  1579. for (auto candidate: candidates) {
  1580. if (TCoCollect::Match(candidate.Get()) || TCoForwardList::Match(candidate.Get())) {
  1581. if (depensOnFlow(candidate->HeadPtr())) {
  1582. return candidate;
  1583. }
  1584. } else if (TCoApply::Match(candidate.Get())) {
  1585. if (AnyOf(candidate->Children().begin() + 1, candidate->Children().end(), depensOnFlow)) {
  1586. if (!IsFlowOrStream(*candidate)) {
  1587. while (TCoApply::Match(candidate.Get())) {
  1588. candidate = candidate->HeadPtr();
  1589. }
  1590. return candidate;
  1591. }
  1592. if (!udfSupportsYield) {
  1593. while (TCoApply::Match(candidate.Get())) {
  1594. candidate = candidate->HeadPtr();
  1595. }
  1596. if (TCoScriptUdf::Match(candidate.Get())) {
  1597. return candidate;
  1598. }
  1599. }
  1600. }
  1601. } else if (TCoSwitch::Match(candidate.Get())) {
  1602. for (size_t i = 3; i < candidate->ChildrenSize(); i += 2) {
  1603. if (auto node = FindNonYieldTransparentNodeImpl(candidate->Child(i)->TailPtr(), udfSupportsYield, TNodeSet{&candidate->Child(i)->Head().Head()})) {
  1604. return node;
  1605. }
  1606. }
  1607. } else if (candidate->IsCallable("DqReplicate")) {
  1608. for (size_t i = 1; i < candidate->ChildrenSize(); ++i) {
  1609. if (auto node = FindNonYieldTransparentNodeImpl(candidate->Child(i)->TailPtr(), udfSupportsYield, TNodeSet{&candidate->Child(i)->Head().Head()})) {
  1610. return node;
  1611. }
  1612. }
  1613. } else if (TCoPartitionsByKeys::Match(candidate.Get())) {
  1614. const auto handlerChild = candidate->Child(TCoPartitionsByKeys::idx_ListHandlerLambda);
  1615. if (auto node = FindNonYieldTransparentNodeImpl(handlerChild->TailPtr(), udfSupportsYield, TNodeSet{&handlerChild->Head().Head()})) {
  1616. return node;
  1617. }
  1618. }
  1619. }
  1620. return {};
  1621. }
  1622. TExprNode::TPtr FindNonYieldTransparentNode(const TExprNode::TPtr& root, const TTypeAnnotationContext& typeCtx, TNodeSet flowSources) {
  1623. TExprNode::TPtr from = root;
  1624. if (root->IsLambda()) {
  1625. if (IsIdentityLambda(*root)) {
  1626. return {};
  1627. }
  1628. from = root->TailPtr();
  1629. // Add all flow lambda args
  1630. root->Head().ForEachChild([&flowSources](const TExprNode& arg) {
  1631. if (IsFlowOrStream(arg)) {
  1632. flowSources.insert(&arg);
  1633. }
  1634. });
  1635. }
  1636. static const THashSet<TStringBuf> WHITE_LIST = {"EmptyIterator"sv, TCoToStream::CallableName(), TCoIterator::CallableName(),
  1637. TCoToFlow::CallableName(), TCoApply::CallableName(), TCoNth::CallableName(), TCoMux::CallableName()};
  1638. // Find all other flow sources (readers)
  1639. auto sources = FindNodes(from,
  1640. [](const TExprNode::TPtr& node) {
  1641. return !node->IsCallable(WHITE_LIST)
  1642. && node->IsCallable()
  1643. && IsFlowOrStream(*node)
  1644. && (node->ChildrenSize() == 0 || !IsFlowOrStream(node->Head()));
  1645. }
  1646. );
  1647. std::for_each(sources.cbegin(), sources.cend(), [&flowSources](const TExprNode::TPtr& node) { flowSources.insert(node.Get()); });
  1648. if (flowSources.empty()) {
  1649. return {};
  1650. }
  1651. return FindNonYieldTransparentNodeImpl(from, typeCtx.UdfSupportsYield, flowSources);
  1652. }
  1653. bool IsYieldTransparent(const TExprNode::TPtr& root, const TTypeAnnotationContext& typeCtx) {
  1654. return !FindNonYieldTransparentNode(root, typeCtx);
  1655. }
  1656. TMaybe<bool> IsStrictNoRecurse(const TExprNode& node) {
  1657. if (node.IsCallable({"Unwrap", "Ensure", "ScriptUdf", "Error", "ErrorType"})) {
  1658. return false;
  1659. }
  1660. if (node.IsCallable("Udf")) {
  1661. return HasSetting(*node.Child(TCoUdf::idx_Settings), "strict");
  1662. }
  1663. return {};
  1664. }
  1665. bool IsStrict(const TExprNode::TPtr& root) {
  1666. // TODO: add TExprNode::IsStrict() method (with corresponding flag). Fill it as part of type annotation pass
  1667. bool isStrict = true;
  1668. VisitExpr(root, [&](const TExprNode::TPtr& node) {
  1669. if (node->IsCallable("AssumeStrict")) {
  1670. return false;
  1671. }
  1672. if (node->IsCallable("AssumeNonStrict")) {
  1673. isStrict = false;
  1674. return false;
  1675. }
  1676. auto maybeStrict = IsStrictNoRecurse(*node);
  1677. if (maybeStrict.Defined() && !*maybeStrict) {
  1678. isStrict = false;
  1679. }
  1680. return isStrict;
  1681. });
  1682. return isStrict;
  1683. }
  1684. bool HasDependsOn(const TExprNode::TPtr& root, const TExprNode::TPtr& arg) {
  1685. bool withDependsOn = false;
  1686. size_t insideDependsOn = 0;
  1687. VisitExpr(root, [&](const TExprNode::TPtr& node) {
  1688. if (node->IsCallable("DependsOn")) {
  1689. ++insideDependsOn;
  1690. } else if (insideDependsOn && node == arg) {
  1691. withDependsOn = true;
  1692. }
  1693. return !withDependsOn;
  1694. }, [&](const TExprNode::TPtr& node) {
  1695. if (node->IsCallable("DependsOn")) {
  1696. YQL_ENSURE(insideDependsOn > 0);
  1697. --insideDependsOn;
  1698. }
  1699. return true;
  1700. });
  1701. return withDependsOn;
  1702. }
  1703. template<bool Assume>
  1704. TExprNode::TPtr MakeSortConstraintImpl(TExprNode::TPtr node, const TSortedConstraintNode* sorted, const TTypeAnnotationNode* rowType, TExprContext& ctx) {
  1705. if (!(sorted && rowType))
  1706. return node;
  1707. const auto& constent = sorted->GetContent();
  1708. return ctx.Builder(node->Pos())
  1709. .Callable(Assume ? "AssumeSorted" : "Sort")
  1710. .Add(0, std::move(node))
  1711. .List(1)
  1712. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1713. size_t index = 0;
  1714. for (const auto& c : constent) {
  1715. parent.Callable(index++, "Bool")
  1716. .Atom(0, ToString(c.second), TNodeFlags::Default)
  1717. .Seal();
  1718. }
  1719. return parent;
  1720. })
  1721. .Seal()
  1722. .Lambda(2)
  1723. .Param("item")
  1724. .List()
  1725. .Do([&](TExprNodeBuilder& parent) -> TExprNodeBuilder& {
  1726. size_t index = 0;
  1727. for (const auto& c : constent)
  1728. GetterBuilder(parent, index++, *rowType, c.first.front());
  1729. return parent;
  1730. })
  1731. .Seal()
  1732. .Seal()
  1733. .Seal()
  1734. .Build();
  1735. }
  1736. TExprNode::TPtr KeepSortedConstraint(TExprNode::TPtr node, const TSortedConstraintNode* sorted, const TTypeAnnotationNode* rowType, TExprContext& ctx) {
  1737. return MakeSortConstraintImpl<true>(std::move(node), sorted, rowType, ctx);
  1738. }
  1739. TExprNode::TPtr MakeSortByConstraint(TExprNode::TPtr node, const TSortedConstraintNode* sorted, const TTypeAnnotationNode* rowType, TExprContext& ctx) {
  1740. return MakeSortConstraintImpl<false>(std::move(node), sorted, rowType, ctx);
  1741. }
  1742. TExprNode::TPtr KeepConstraints(TExprNode::TPtr node, const TExprNode& src, TExprContext& ctx) {
  1743. auto res = KeepSortedConstraint(node, src.GetConstraint<TSortedConstraintNode>(), GetSeqItemType(src.GetTypeAnn()), ctx);
  1744. res = KeepChoppedConstraint(std::move(res), src, ctx);
  1745. res = KeepUniqueConstraint<true>(std::move(res), src, ctx);
  1746. res = KeepUniqueConstraint<false>(std::move(res), src, ctx);
  1747. return res;
  1748. }
  1749. bool HasOnlyOneJoinType(const TExprNode& joinTree, TStringBuf joinType) {
  1750. if (joinTree.IsAtom()) {
  1751. return true;
  1752. }
  1753. YQL_ENSURE(joinTree.Child(0)->IsAtom());
  1754. if (joinTree.Child(0)->Content() != joinType) {
  1755. return false;
  1756. }
  1757. return HasOnlyOneJoinType(*joinTree.Child(1), joinType) && HasOnlyOneJoinType(*joinTree.Child(2), joinType);
  1758. }
  1759. void OptimizeSubsetFieldsForNodeWithMultiUsage(const TExprNode::TPtr& node, const TParentsMap& parentsMap,
  1760. TNodeOnNodeOwnedMap& toOptimize, TExprContext& ctx,
  1761. std::function<TExprNode::TPtr(const TExprNode::TPtr&, const TExprNode::TPtr&, const TParentsMap&, TExprContext&)> handler)
  1762. {
  1763. // Ignore stream input, because it cannot be used multiple times
  1764. if (node->GetTypeAnn()->GetKind() != ETypeAnnotationKind::List) {
  1765. return;
  1766. }
  1767. auto itemType = node->GetTypeAnn()->Cast<TListExprType>()->GetItemType();
  1768. if (itemType->GetKind() != ETypeAnnotationKind::Struct) {
  1769. return;
  1770. }
  1771. auto structType = itemType->Cast<TStructExprType>();
  1772. auto it = parentsMap.find(node.Get());
  1773. if (it == parentsMap.cend() || it->second.size() <= 1) {
  1774. return;
  1775. }
  1776. TSet<TStringBuf> usedFields;
  1777. for (auto parent: it->second) {
  1778. if (auto maybeFlatMap = TMaybeNode<TCoFlatMapBase>(parent)) {
  1779. auto flatMap = maybeFlatMap.Cast();
  1780. TSet<TStringBuf> lambdaSubset;
  1781. if (!HaveFieldsSubset(flatMap.Lambda().Body().Ptr(), flatMap.Lambda().Args().Arg(0).Ref(), lambdaSubset, parentsMap)) {
  1782. return;
  1783. }
  1784. usedFields.insert(lambdaSubset.cbegin(), lambdaSubset.cend());
  1785. }
  1786. else if (auto maybeExtractMembers = TMaybeNode<TCoExtractMembers>(parent)) {
  1787. auto extractMembers = maybeExtractMembers.Cast();
  1788. for (auto member: extractMembers.Members()) {
  1789. usedFields.insert(member.Value());
  1790. }
  1791. }
  1792. else {
  1793. return;
  1794. }
  1795. if (usedFields.size() == structType->GetSize()) {
  1796. return;
  1797. }
  1798. }
  1799. TExprNode::TListType members;
  1800. for (auto column : usedFields) {
  1801. members.push_back(ctx.NewAtom(node->Pos(), column));
  1802. }
  1803. auto newInput = handler(node, ctx.NewList(node->Pos(), std::move(members)), parentsMap, ctx);
  1804. if (!newInput || newInput == node) {
  1805. return;
  1806. }
  1807. for (auto parent: it->second) {
  1808. if (TCoExtractMembers::Match(parent)) {
  1809. if (parent->GetTypeAnn()->Cast<TListExprType>()->GetItemType()->Cast<TStructExprType>()->GetSize() == usedFields.size()) {
  1810. toOptimize[parent] = newInput;
  1811. } else {
  1812. toOptimize[parent] = ctx.ChangeChild(*parent, 0, TExprNode::TPtr(newInput));
  1813. }
  1814. } else {
  1815. toOptimize[parent] = ctx.Builder(parent->Pos())
  1816. .Callable(parent->Content())
  1817. .Add(0, newInput)
  1818. .Lambda(1)
  1819. .Param("item")
  1820. .Apply(parent->ChildPtr(1)).With(0, "item").Seal()
  1821. .Seal()
  1822. .Seal()
  1823. .Build();
  1824. }
  1825. }
  1826. }
  1827. template<bool Ordered>
  1828. std::optional<std::pair<TPartOfConstraintBase::TPathType, ui32>> GetPathToKey(const TExprNode& body, const TExprNode::TChildrenType& args) {
  1829. if (body.IsArgument()) {
  1830. for (auto i = 0U; i < args.size(); ++i)
  1831. if (&body == args[i].Get())
  1832. return std::make_pair(TPartOfConstraintBase::TPathType(), i);
  1833. } else if (body.IsCallable({"Member","Nth"})) {
  1834. if (auto path = GetPathToKey<Ordered>(body.Head(), args)) {
  1835. path->first.emplace_back(body.Tail().Content());
  1836. return path;
  1837. } else if (const auto& head = SkipCallables(body.Head(), {"CastStruct","FilterMembers"}); head.IsCallable("AsStruct") && body.IsCallable("Member")) {
  1838. return GetPathToKey<Ordered>(GetLiteralStructMember(head, body.Tail()), args);
  1839. } else if (body.IsCallable("Nth") && body.Head().IsList()) {
  1840. return GetPathToKey<Ordered>(*body.Head().Child(FromString<ui32>(body.Tail().Content())), args);
  1841. } else if (body.IsCallable({"CastStruct","FilterMembers"})) {
  1842. return GetPathToKey<Ordered>(body.Head(), args);
  1843. }
  1844. } else if constexpr (!Ordered) {
  1845. if (body.IsCallable("StablePickle")) {
  1846. return GetPathToKey<Ordered>(body.Head(), args);
  1847. }
  1848. }
  1849. return std::nullopt;
  1850. }
  1851. template std::optional<std::pair<TPartOfConstraintBase::TPathType, ui32>> GetPathToKey<true>(const TExprNode& body, const TExprNode::TChildrenType& args);
  1852. template std::optional<std::pair<TPartOfConstraintBase::TPathType, ui32>> GetPathToKey<false>(const TExprNode& body, const TExprNode::TChildrenType& args);
  1853. template<bool Ordered>
  1854. std::optional<TPartOfConstraintBase::TPathType> GetPathToKey(const TExprNode& body, const TExprNode& arg) {
  1855. if (&body == &arg)
  1856. return TPartOfConstraintBase::TPathType();
  1857. if (body.IsCallable({"Member","Nth"})) {
  1858. if (auto path = GetPathToKey(body.Head(), arg)) {
  1859. path->emplace_back(body.Tail().Content());
  1860. return path;
  1861. }
  1862. }
  1863. if (body.IsCallable({"CastStruct","FilterMembers","Just","Unwrap"}))
  1864. return GetPathToKey<Ordered>(body.Head(), arg);
  1865. if (body.IsCallable("Member") && body.Head().IsCallable("AsStruct"))
  1866. return GetPathToKey<Ordered>(GetLiteralStructMember(body.Head(), body.Tail()), arg);
  1867. if (body.IsCallable("Nth") && body.Head().IsList())
  1868. return GetPathToKey<Ordered>(*body.Head().Child(FromString<ui32>(body.Tail().Content())), arg);
  1869. if (body.IsList() && 1U == body.ChildrenSize() && body.Head().IsCallable("Nth") && body.Head().Tail().IsAtom("0") &&
  1870. 1U == RemoveOptionality(*body.Head().Head().GetTypeAnn()).Cast<TTupleExprType>()->GetSize())
  1871. // Especialy for "Extract single item tuple from Condense1" optimizer.
  1872. return GetPathToKey(body.Head().Head(), arg);
  1873. if (body.IsCallable("AsStruct") && 1U == body.ChildrenSize() && body.Head().Tail().IsCallable("Member") &&
  1874. body.Head().Head().Content() == body.Head().Tail().Tail().Content() &&
  1875. 1U == RemoveOptionality(*body.Head().Tail().Head().GetTypeAnn()).Cast<TStructExprType>()->GetSize())
  1876. // Especialy for "Extract single item struct from Condense1" optimizer.
  1877. return GetPathToKey<Ordered>(body.Head().Tail().Head(), arg);
  1878. if (IsTransparentIfPresent(body) && &body.Head() == &arg)
  1879. return GetPathToKey<Ordered>(body.Child(1)->Tail().Head(), body.Child(1)->Head().Head());
  1880. if constexpr (!Ordered)
  1881. if (body.IsCallable("StablePickle"))
  1882. return GetPathToKey<Ordered>(body.Head(), arg);
  1883. return std::nullopt;
  1884. }
  1885. template<bool Ordered>
  1886. TPartOfConstraintBase::TSetType GetPathsToKeys(const TExprNode& body, const TExprNode& arg) {
  1887. TPartOfConstraintBase::TSetType keys;
  1888. if (body.IsList()) {
  1889. if (const auto size = body.ChildrenSize()) {
  1890. keys.reserve(size);
  1891. for (auto i = 0U; i < size; ++i)
  1892. if (auto path = GetPathToKey<Ordered>(*body.Child(i), arg))
  1893. keys.insert_unique(std::move(*path));
  1894. }
  1895. } else if constexpr (!Ordered) {
  1896. if (body.IsCallable("StablePickle")) {
  1897. return GetPathsToKeys<Ordered>(body.Head(), arg);
  1898. }
  1899. }
  1900. if (auto path = GetPathToKey<Ordered>(body, arg)) {
  1901. keys.insert_unique(std::move(*path));
  1902. }
  1903. return keys;
  1904. }
  1905. template TPartOfConstraintBase::TSetType GetPathsToKeys<true>(const TExprNode& body, const TExprNode& arg);
  1906. template TPartOfConstraintBase::TSetType GetPathsToKeys<false>(const TExprNode& body, const TExprNode& arg);
  1907. TVector<TString> GenNoClashColumns(const TStructExprType& source, TStringBuf prefix, size_t count) {
  1908. YQL_ENSURE(prefix.StartsWith("_yql"));
  1909. TSet<size_t> existing;
  1910. for (auto& item : source.GetItems()) {
  1911. TStringBuf column = item->GetName();
  1912. if (column.SkipPrefix(prefix)) {
  1913. size_t idx;
  1914. if (TryFromString(column, idx)) {
  1915. existing.insert(idx);
  1916. }
  1917. }
  1918. }
  1919. size_t current = 0;
  1920. TVector<TString> result;
  1921. auto it = existing.cbegin();
  1922. while (count) {
  1923. if (it == existing.cend() || current < *it) {
  1924. result.push_back(TStringBuilder() << prefix << current);
  1925. --count;
  1926. } else {
  1927. ++it;
  1928. }
  1929. YQL_ENSURE(!count || (current + 1 > current));
  1930. ++current;
  1931. }
  1932. return result;
  1933. }
  1934. bool CheckSupportedTypes(const TTypeAnnotationNode::TListType& typesToCheck, const TSet<TString>& supportedTypes, const TSet<NUdf::EDataSlot>& supportedDataTypes, std::function<void(const TString&)> unsupportedTypeHandler) {
  1935. TSet<ETypeAnnotationKind> supported;
  1936. for (const auto &e: supportedTypes) {
  1937. if (e == "pg") {
  1938. supported.insert(ETypeAnnotationKind::Pg);
  1939. } else if (e == "tuple") {
  1940. supported.emplace(ETypeAnnotationKind::Tuple);
  1941. } else if (e == "struct") {
  1942. supported.emplace(ETypeAnnotationKind::Struct);
  1943. } else if (e == "dict") {
  1944. supported.emplace(ETypeAnnotationKind::Dict);
  1945. } else if (e == "list") {
  1946. supported.emplace(ETypeAnnotationKind::List);
  1947. } else if (e == "variant") {
  1948. supported.emplace(ETypeAnnotationKind::Variant);
  1949. } else {
  1950. // Unknown type
  1951. unsupportedTypeHandler(TStringBuilder() << "unknown type: " << e);
  1952. return false;
  1953. }
  1954. }
  1955. if (supportedDataTypes.size()) {
  1956. supported.emplace(ETypeAnnotationKind::Data);
  1957. }
  1958. auto checkType = [&] (const TTypeAnnotationNode* type) {
  1959. if (type->GetKind() == ETypeAnnotationKind::Data) {
  1960. if (!supported.contains(ETypeAnnotationKind::Data)) {
  1961. unsupportedTypeHandler(TStringBuilder() << "unsupported data types");
  1962. return false;
  1963. }
  1964. if (!supportedDataTypes.contains(type->Cast<TDataExprType>()->GetSlot())) {
  1965. unsupportedTypeHandler(TStringBuilder() << "unsupported data type: " << type->Cast<TDataExprType>()->GetSlot());
  1966. return false;
  1967. }
  1968. } else if (type->GetKind() == ETypeAnnotationKind::Pg) {
  1969. if (!supported.contains(ETypeAnnotationKind::Pg)) {
  1970. unsupportedTypeHandler(TStringBuilder() << "unsupported pg");
  1971. return false;
  1972. }
  1973. auto name = type->Cast<TPgExprType>()->GetName();
  1974. if (name == "float4" && !supportedDataTypes.contains(NUdf::EDataSlot::Float)) {
  1975. unsupportedTypeHandler(TStringBuilder() << "PgFloat4 unsupported yet since float is no supported");
  1976. return false;
  1977. }
  1978. } else {
  1979. unsupportedTypeHandler(TStringBuilder() << "unsupported annotation kind: " << type->GetKind());
  1980. return false;
  1981. }
  1982. return true;
  1983. };
  1984. TVector<const TTypeAnnotationNode*> stack(typesToCheck.begin(), typesToCheck.end());
  1985. while (!stack.empty()) {
  1986. auto el = stack.back();
  1987. stack.pop_back();
  1988. if (el->GetKind() == ETypeAnnotationKind::Optional) {
  1989. stack.push_back(el->Cast<TOptionalExprType>()->GetItemType());
  1990. continue;
  1991. }
  1992. if (!supported.contains(el->GetKind())) {
  1993. unsupportedTypeHandler(TStringBuilder() << "unsupported " << el->GetKind());
  1994. return false;
  1995. }
  1996. if (el->GetKind() == ETypeAnnotationKind::Tuple) {
  1997. for (auto e: el->Cast<TTupleExprType>()->GetItems()) {
  1998. stack.push_back(e);
  1999. }
  2000. continue;
  2001. } else if (el->GetKind() == ETypeAnnotationKind::Struct) {
  2002. for (auto e: el->Cast<TStructExprType>()->GetItems()) {
  2003. stack.push_back(e->GetItemType());
  2004. }
  2005. continue;
  2006. } else if (el->GetKind() == ETypeAnnotationKind::List) {
  2007. stack.push_back(el->Cast<TListExprType>()->GetItemType());
  2008. continue;
  2009. } else if (el->GetKind() == ETypeAnnotationKind::Dict) {
  2010. stack.push_back(el->Cast<TDictExprType>()->GetKeyType());
  2011. stack.push_back(el->Cast<TDictExprType>()->GetPayloadType());
  2012. continue;
  2013. } else if (el->GetKind() == ETypeAnnotationKind::Variant) {
  2014. stack.push_back(el->Cast<TVariantExprType>()->GetUnderlyingType());
  2015. continue;
  2016. }
  2017. if (!checkType(el)) {
  2018. return false;
  2019. }
  2020. }
  2021. return true;
  2022. }
  2023. }