yql_expr.cpp 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917
  1. #include "yql_expr.h"
  2. #include "yql_ast_annotation.h"
  3. #include "yql_gc_nodes.h"
  4. #include <yql/essentials/utils/utf8.h>
  5. #include <yql/essentials/utils/fetch/fetch.h>
  6. #include <yql/essentials/core/issue/yql_issue.h>
  7. #include <yql/essentials/parser/pg_catalog/catalog.h>
  8. #include <library/cpp/containers/stack_vector/stack_vec.h>
  9. #include <util/generic/hash.h>
  10. #include <util/generic/size_literals.h>
  11. #include <util/string/cast.h>
  12. #include <util/string/join.h>
  13. #include <util/digest/fnv.h>
  14. #include <util/digest/murmur.h>
  15. #include <util/digest/city.h>
  16. #include <util/digest/numeric.h>
  17. #include <util/string/cast.h>
  18. #include <openssl/sha.h>
  19. #include <map>
  20. #include <unordered_set>
  21. namespace NYql {
  22. const TStringBuf ZeroString = "";
  23. const char Dot = '.';
  24. const char Sep = '/';
  25. const TStringBuf PkgPrefix = "pkg";
  26. void ReportError(TExprContext& ctx, const TIssue& issue) {
  27. ctx.AddError(issue);
  28. }
  29. namespace {
  30. template <typename T>
  31. const T* FindType(const T& sample, TExprContext& ctx) {
  32. const auto it = ctx.TypeSet.find(&sample);
  33. return ctx.TypeSet.cend() != it ? static_cast<const T*>(*it) : nullptr;
  34. }
  35. template <typename T, typename... Args>
  36. const T* AddType(TExprContext& ctx, Args&&... args) {
  37. Y_DEBUG_ABORT_UNLESS(!ctx.Frozen);
  38. ctx.TypeNodes.emplace(new T(std::forward<Args>(args)...));
  39. const auto ins = ctx.TypeSet.emplace(ctx.TypeNodes.top().get());
  40. return static_cast<const T*>(*ins.first);
  41. }
  42. void DumpNode(const TExprNode& node, IOutputStream& out, ui32 level, TNodeSet& visited) {
  43. for (ui32 i = 0; i < level; ++i) {
  44. out.Write(' ');
  45. }
  46. out << "#" << node.UniqueId() << " [" << node.Type() << "]";
  47. if (node.Type() == TExprNode::Atom || node.Type() == TExprNode::Callable || node.Type() == TExprNode::Argument) {
  48. out << " <" << node.Content() << ">";
  49. }
  50. constexpr bool WithTypes = false;
  51. constexpr bool WithConstraints = false;
  52. constexpr bool WithScope = false;
  53. if constexpr (WithTypes) {
  54. if (node.GetTypeAnn()) {
  55. out << ", " << *node.GetTypeAnn();
  56. }
  57. }
  58. if constexpr (WithConstraints) {
  59. if (node.GetState() >= TExprNode::EState::ConstrComplete) {
  60. out << ", " << node.GetConstraintSet();
  61. }
  62. }
  63. if constexpr (WithScope) {
  64. if (const auto scope = node.GetDependencyScope()) {
  65. out << ", (";
  66. if (const auto outer = scope->first) {
  67. out << '#' << outer->UniqueId();
  68. } else {
  69. out << "null";
  70. }
  71. out << ',';
  72. if (const auto inner = scope->second) {
  73. out << '#' << inner->UniqueId();
  74. } else {
  75. out << "null";
  76. }
  77. out << ')';
  78. }
  79. }
  80. bool showChildren = true;
  81. if (!visited.emplace(&node).second) {
  82. if (node.Type() == TExprNode::Callable || node.Type() == TExprNode::List
  83. || node.Type() == TExprNode::Lambda || node.Type() == TExprNode::Arguments) {
  84. out << " ...";
  85. showChildren = false;
  86. }
  87. }
  88. out << "\n";
  89. if (showChildren) {
  90. for (auto& child : node.Children()) {
  91. DumpNode(*child, out, level + 1, visited);
  92. }
  93. }
  94. }
  95. struct TContext {
  96. struct TFrame {
  97. THashMap<TString, TExprNode::TListType> Bindings;
  98. THashMap<TString, TString> Imports;
  99. TExprNode::TListType Return;
  100. };
  101. TExprContext& Expr;
  102. TVector<TFrame> Frames;
  103. TLibraryCohesion Cohesion;
  104. std::unordered_set<TString> OverrideLibraries;
  105. TNodeOnNodeOwnedMap DeepClones;
  106. const TAnnotationNodeMap* Annotations = nullptr;
  107. IModuleResolver* ModuleResolver = nullptr;
  108. IUrlListerManager* UrlListerManager = nullptr;
  109. ui32 TypeAnnotationIndex = Max<ui32>();
  110. TString File;
  111. ui16 SyntaxVersion = 0;
  112. TContext(TExprContext& expr)
  113. : Expr(expr)
  114. {
  115. }
  116. void AddError(const TAstNode& node, const TString& message) {
  117. Expr.AddError(TIssue(node.GetPosition(), message));
  118. }
  119. void AddInfo(const TAstNode& node, const TString& message) {
  120. auto issue = TIssue(node.GetPosition(), message);
  121. issue.SetCode(TIssuesIds::INFO, TSeverityIds::S_INFO);
  122. Expr.AddError(issue);
  123. }
  124. TExprNode::TPtr&& ProcessNode(const TAstNode& node, TExprNode::TPtr&& exprNode) {
  125. if (TypeAnnotationIndex != Max<ui32>()) {
  126. exprNode->SetTypeAnn(CompileTypeAnnotation(node));
  127. }
  128. return std::move(exprNode);
  129. }
  130. void PushFrame() {
  131. Frames.push_back(TFrame());
  132. }
  133. void PopFrame() {
  134. Frames.pop_back();
  135. }
  136. TExprNode::TListType FindBinding(const TStringBuf& name) const {
  137. for (auto it = Frames.crbegin(); it != Frames.crend(); ++it) {
  138. const auto r = it->Bindings.find(name);
  139. if (it->Bindings.cend() != r)
  140. return r->second;
  141. }
  142. return {};
  143. }
  144. TString FindImport(const TStringBuf& name) const {
  145. for (auto it = Frames.crbegin(); it != Frames.crend(); ++it) {
  146. const auto r = it->Imports.find(name);
  147. if (it->Imports.cend() != r)
  148. return r->second;
  149. }
  150. return TString();
  151. }
  152. const TTypeAnnotationNode* CompileTypeAnnotation(const TAstNode& node) {
  153. auto ptr = Annotations->FindPtr(&node);
  154. if (!ptr || TypeAnnotationIndex >= ptr->size()) {
  155. AddError(node, "Failed to load type annotation");
  156. return nullptr;
  157. }
  158. return CompileTypeAnnotationNode(*(*ptr)[TypeAnnotationIndex]);
  159. }
  160. const TTypeAnnotationNode* CompileTypeAnnotationNode(const TAstNode& node) {
  161. if (node.IsAtom()) {
  162. if (node.GetContent() == TStringBuf(".")) {
  163. return nullptr;
  164. }
  165. else if (node.GetContent() == TStringBuf("Unit")) {
  166. return Expr.MakeType<TUnitExprType>();
  167. }
  168. else if (node.GetContent() == TStringBuf("World")) {
  169. return Expr.MakeType<TWorldExprType>();
  170. }
  171. else if (node.GetContent() == TStringBuf("Void")) {
  172. return Expr.MakeType<TVoidExprType>();
  173. }
  174. else if (node.GetContent() == TStringBuf("Null")) {
  175. return Expr.MakeType<TNullExprType>();
  176. }
  177. else if (node.GetContent() == TStringBuf("Generic")) {
  178. return Expr.MakeType<TGenericExprType>();
  179. }
  180. else if (node.GetContent() == TStringBuf("EmptyList")) {
  181. return Expr.MakeType<TEmptyListExprType>();
  182. }
  183. else if (node.GetContent() == TStringBuf("EmptyDict")) {
  184. return Expr.MakeType<TEmptyDictExprType>();
  185. }
  186. else {
  187. AddError(node, TStringBuilder() << "Unknown type annotation: " << node.GetContent());
  188. return nullptr;
  189. }
  190. } else {
  191. if (node.GetChildrenCount() == 0) {
  192. AddError(node, "Bad type annotation, expected not empty list");
  193. return nullptr;
  194. }
  195. if (!node.GetChild(0)->IsAtom()) {
  196. AddError(node, "Bad type annotation, first list item must be an atom");
  197. return nullptr;
  198. }
  199. auto content = node.GetChild(0)->GetContent();
  200. if (content == TStringBuf("Data")) {
  201. const auto count = node.GetChildrenCount();
  202. if (!(count == 2 || count == 4) || !node.GetChild(1)->IsAtom()) {
  203. AddError(node, "Bad data type annotation");
  204. return nullptr;
  205. }
  206. auto slot = NUdf::FindDataSlot(node.GetChild(1)->GetContent());
  207. if (!slot) {
  208. AddError(node, "Bad data type annotation");
  209. return nullptr;
  210. }
  211. if (count == 2) {
  212. return Expr.MakeType<TDataExprType>(*slot);
  213. } else {
  214. if (!(node.GetChild(2)->IsAtom() && node.GetChild(3)->IsAtom())) {
  215. AddError(node, "Bad data type annotation");
  216. return nullptr;
  217. }
  218. auto ann = Expr.MakeType<TDataExprParamsType>(*slot, node.GetChild(2)->GetContent(), node.GetChild(3)->GetContent());
  219. if (!ann->Validate(node.GetPosition(), Expr)) {
  220. return nullptr;
  221. }
  222. return ann;
  223. }
  224. } else if (content == TStringBuf("Pg")) {
  225. const auto count = node.GetChildrenCount();
  226. if (count != 2 || !node.GetChild(1)->IsAtom()) {
  227. AddError(node, "Bad data type annotation");
  228. return nullptr;
  229. }
  230. auto typeId = NPg::LookupType(TString(node.GetChild(1)->GetContent())).TypeId;
  231. return Expr.MakeType<TPgExprType>(typeId);
  232. } else if (content == TStringBuf("List")) {
  233. if (node.GetChildrenCount() != 2) {
  234. AddError(node, "Bad list type annotation");
  235. return nullptr;
  236. }
  237. auto r = CompileTypeAnnotationNode(*node.GetChild(1));
  238. if (!r)
  239. return nullptr;
  240. return Expr.MakeType<TListExprType>(r);
  241. } else if (content == TStringBuf("Stream")) {
  242. if (node.GetChildrenCount() != 2) {
  243. AddError(node, "Bad stream type annotation");
  244. return nullptr;
  245. }
  246. auto r = CompileTypeAnnotationNode(*node.GetChild(1));
  247. if (!r)
  248. return nullptr;
  249. return Expr.MakeType<TStreamExprType>(r);
  250. } else if (content == TStringBuf("Struct")) {
  251. TVector<const TItemExprType*> children;
  252. for (size_t index = 1; index < node.GetChildrenCount(); ++index) {
  253. auto r = CompileTypeAnnotationNode(*node.GetChild(index));
  254. if (!r)
  255. return nullptr;
  256. if (r->GetKind() != ETypeAnnotationKind::Item) {
  257. AddError(node, "Expected item type annotation");
  258. return nullptr;
  259. }
  260. children.push_back(r->Cast<TItemExprType>());
  261. }
  262. auto ann = Expr.MakeType<TStructExprType>(children);
  263. if (!ann->Validate(node.GetPosition(), Expr)) {
  264. return nullptr;
  265. }
  266. return ann;
  267. } else if (content == TStringBuf("Multi")) {
  268. TTypeAnnotationNode::TListType children;
  269. for (size_t index = 1; index < node.GetChildrenCount(); ++index) {
  270. auto r = CompileTypeAnnotationNode(*node.GetChild(index));
  271. if (!r)
  272. return nullptr;
  273. children.push_back(r);
  274. }
  275. auto ann = Expr.MakeType<TMultiExprType>(children);
  276. if (!ann->Validate(node.GetPosition(), Expr)) {
  277. return nullptr;
  278. }
  279. return ann;
  280. } else if (content == TStringBuf("Tuple")) {
  281. TTypeAnnotationNode::TListType children;
  282. for (size_t index = 1; index < node.GetChildrenCount(); ++index) {
  283. auto r = CompileTypeAnnotationNode(*node.GetChild(index));
  284. if (!r)
  285. return nullptr;
  286. children.push_back(r);
  287. }
  288. auto ann = Expr.MakeType<TTupleExprType>(children);
  289. if (!ann->Validate(node.GetPosition(), Expr)) {
  290. return nullptr;
  291. }
  292. return ann;
  293. } else if (content == TStringBuf("Item")) {
  294. if (node.GetChildrenCount() != 3 || !node.GetChild(1)->IsAtom()) {
  295. AddError(node, "Bad item type annotation");
  296. return nullptr;
  297. }
  298. auto r = CompileTypeAnnotationNode(*node.GetChild(2));
  299. if (!r)
  300. return nullptr;
  301. return Expr.MakeType<TItemExprType>(TString(node.GetChild(1)->GetContent()), r);
  302. } else if (content == TStringBuf("Optional")) {
  303. if (node.GetChildrenCount() != 2) {
  304. AddError(node, "Bad optional type annotation");
  305. return nullptr;
  306. }
  307. auto r = CompileTypeAnnotationNode(*node.GetChild(1));
  308. if (!r)
  309. return nullptr;
  310. return Expr.MakeType<TOptionalExprType>(r);
  311. } else if (content == TStringBuf("Type")) {
  312. if (node.GetChildrenCount() != 2) {
  313. AddError(node, "Bad type annotation");
  314. return nullptr;
  315. }
  316. auto r = CompileTypeAnnotationNode(*node.GetChild(1));
  317. if (!r)
  318. return nullptr;
  319. return Expr.MakeType<TTypeExprType>(r);
  320. }
  321. else if (content == TStringBuf("Dict")) {
  322. if (node.GetChildrenCount() != 3) {
  323. AddError(node, "Bad dict annotation");
  324. return nullptr;
  325. }
  326. auto r1 = CompileTypeAnnotationNode(*node.GetChild(1));
  327. if (!r1)
  328. return nullptr;
  329. auto r2 = CompileTypeAnnotationNode(*node.GetChild(2));
  330. if (!r2)
  331. return nullptr;
  332. auto ann = Expr.MakeType<TDictExprType>(r1, r2);
  333. if (!ann->Validate(node.GetPosition(), Expr)) {
  334. return nullptr;
  335. }
  336. return ann;
  337. }
  338. else if (content == TStringBuf("Callable")) {
  339. if (node.GetChildrenCount() <= 2) {
  340. AddError(node, "Bad callable annotation");
  341. return nullptr;
  342. }
  343. TVector<TCallableExprType::TArgumentInfo> args;
  344. size_t optCount = 0;
  345. TString payload;
  346. if (!node.GetChild(1)->IsList()) {
  347. AddError(node, "Bad callable annotation - expected list");
  348. return nullptr;
  349. }
  350. if (node.GetChild(1)->GetChildrenCount() > 2) {
  351. AddError(node, "Bad callable annotation - too many settings nodes");
  352. return nullptr;
  353. }
  354. if (node.GetChild(1)->GetChildrenCount() > 0) {
  355. auto optChild = node.GetChild(1)->GetChild(0);
  356. if (!optChild->IsAtom()) {
  357. AddError(node, "Bad callable annotation - expected atom");
  358. return nullptr;
  359. }
  360. if (!TryFromString(optChild->GetContent(), optCount)) {
  361. AddError(node, TStringBuilder() << "Bad callable optional args count: " << node.GetChild(1)->GetContent());
  362. return nullptr;
  363. }
  364. }
  365. if (node.GetChild(1)->GetChildrenCount() > 1) {
  366. auto payloadChild = node.GetChild(1)->GetChild(1);
  367. if (!payloadChild->IsAtom()) {
  368. AddError(node, "Bad callable annotation - expected atom");
  369. return nullptr;
  370. }
  371. payload = payloadChild->GetContent();
  372. }
  373. auto retSettings = node.GetChild(2);
  374. if (!retSettings->IsList() || retSettings->GetChildrenCount() != 1) {
  375. AddError(node, "Bad callable annotation - expected list of size 1");
  376. return nullptr;
  377. }
  378. auto retType = CompileTypeAnnotationNode(*retSettings->GetChild(0));
  379. if (!retType)
  380. return nullptr;
  381. for (size_t index = 3; index < node.GetChildrenCount(); ++index) {
  382. auto argSettings = node.GetChild(index);
  383. if (!argSettings->IsList() || argSettings->GetChildrenCount() < 1 ||
  384. argSettings->GetChildrenCount() > 3) {
  385. AddError(node, "Bad callable annotation - expected list of size 1..3");
  386. return nullptr;
  387. }
  388. auto r = CompileTypeAnnotationNode(*argSettings->GetChild(0));
  389. if (!r)
  390. return nullptr;
  391. TCallableExprType::TArgumentInfo arg;
  392. arg.Type = r;
  393. if (argSettings->GetChildrenCount() > 1) {
  394. auto nameChild = argSettings->GetChild(1);
  395. if (!nameChild->IsAtom()) {
  396. AddError(node, "Bad callable annotation - expected atom");
  397. return nullptr;
  398. }
  399. arg.Name = nameChild->GetContent();
  400. }
  401. if (argSettings->GetChildrenCount() > 2) {
  402. auto flagsChild = argSettings->GetChild(2);
  403. if (!flagsChild->IsAtom()) {
  404. AddError(node, "Bad callable annotation - expected atom");
  405. return nullptr;
  406. }
  407. if (!TryFromString(flagsChild->GetContent(), arg.Flags)) {
  408. AddError(node, "Bad callable annotation - bad integer");
  409. return nullptr;
  410. }
  411. }
  412. args.push_back(arg);
  413. }
  414. auto ann = Expr.MakeType<TCallableExprType>(retType, args, optCount, payload);
  415. if (!ann->Validate(node.GetPosition(), Expr)) {
  416. return nullptr;
  417. }
  418. return ann;
  419. } else if (content == TStringBuf("Resource")) {
  420. if (node.GetChildrenCount() != 2 || !node.GetChild(1)->IsAtom()) {
  421. AddError(node, "Bad resource type annotation");
  422. return nullptr;
  423. }
  424. return Expr.MakeType<TResourceExprType>(TString(node.GetChild(1)->GetContent()));
  425. } else if (content == TStringBuf("Tagged")) {
  426. if (node.GetChildrenCount() != 3 || !node.GetChild(2)->IsAtom()) {
  427. AddError(node, "Bad tagged type annotation");
  428. return nullptr;
  429. }
  430. auto type = CompileTypeAnnotationNode(*node.GetChild(1));
  431. if (!type)
  432. return nullptr;
  433. TString tag(node.GetChild(2)->GetContent());
  434. auto ann = Expr.MakeType<TTaggedExprType>(type, tag);
  435. if (!ann->Validate(node.GetPosition(), Expr)) {
  436. return nullptr;
  437. }
  438. return ann;
  439. } else if (content == TStringBuf("Error")) {
  440. if (node.GetChildrenCount() != 5 || !node.GetChild(1)->IsAtom() ||
  441. !node.GetChild(2)->IsAtom() || !node.GetChild(3)->IsAtom() || !node.GetChild(4)->IsAtom()) {
  442. AddError(node, "Bad error type annotation");
  443. return nullptr;
  444. }
  445. ui32 row;
  446. if (!TryFromString(node.GetChild(1)->GetContent(), row)) {
  447. AddError(node, TStringBuilder() << "Bad integer: " << node.GetChild(1)->GetContent());
  448. return nullptr;
  449. }
  450. ui32 column;
  451. if (!TryFromString(node.GetChild(2)->GetContent(), column)) {
  452. AddError(node, TStringBuilder() << "Bad integer: " << node.GetChild(2)->GetContent());
  453. return nullptr;
  454. }
  455. auto file = TString(node.GetChild(3)->GetContent());
  456. return Expr.MakeType<TErrorExprType>(TIssue(TPosition(column, row, file), TString(node.GetChild(4)->GetContent())));
  457. } else if (content == TStringBuf("Variant")) {
  458. if (node.GetChildrenCount() != 2) {
  459. AddError(node, "Bad variant type annotation");
  460. return nullptr;
  461. }
  462. auto r = CompileTypeAnnotationNode(*node.GetChild(1));
  463. if (!r)
  464. return nullptr;
  465. auto ann = Expr.MakeType<TVariantExprType>(r);
  466. if (!ann->Validate(node.GetPosition(), Expr)) {
  467. return nullptr;
  468. }
  469. return ann;
  470. } else if (content == TStringBuf("Stream")) {
  471. if (node.GetChildrenCount() != 2) {
  472. AddError(node, "Bad stream type annotation");
  473. return nullptr;
  474. }
  475. auto r = CompileTypeAnnotationNode(*node.GetChild(1));
  476. if (!r)
  477. return nullptr;
  478. return Expr.MakeType<TStreamExprType>(r);
  479. } else if (content == TStringBuf("Flow")) {
  480. if (node.GetChildrenCount() != 2) {
  481. AddError(node, "Bad flow type annotation");
  482. return nullptr;
  483. }
  484. auto r = CompileTypeAnnotationNode(*node.GetChild(1));
  485. if (!r)
  486. return nullptr;
  487. return Expr.MakeType<TFlowExprType>(r);
  488. } else if (content == TStringBuf("Block")) {
  489. if (node.GetChildrenCount() != 2) {
  490. AddError(node, "Bad block type annotation");
  491. return nullptr;
  492. }
  493. auto r = CompileTypeAnnotationNode(*node.GetChild(1));
  494. if (!r)
  495. return nullptr;
  496. return Expr.MakeType<TBlockExprType>(r);
  497. } else if (content == TStringBuf("Scalar")) {
  498. if (node.GetChildrenCount() != 2) {
  499. AddError(node, "Bad scalar type annotation");
  500. return nullptr;
  501. }
  502. auto r = CompileTypeAnnotationNode(*node.GetChild(1));
  503. if (!r)
  504. return nullptr;
  505. return Expr.MakeType<TScalarExprType>(r);
  506. } else {
  507. AddError(node, TStringBuilder() << "Unknown type annotation");
  508. return nullptr;
  509. }
  510. }
  511. }
  512. };
  513. TAstNode* ConvertTypeAnnotationToAst(const TTypeAnnotationNode& annotation, TMemoryPool& pool, bool refAtoms) {
  514. switch (annotation.GetKind()) {
  515. case ETypeAnnotationKind::Unit:
  516. {
  517. return TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Unit"), pool);
  518. }
  519. case ETypeAnnotationKind::Tuple:
  520. {
  521. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Tuple"), pool);
  522. TSmallVec<TAstNode*> children;
  523. children.push_back(self);
  524. for (auto& child : annotation.Cast<TTupleExprType>()->GetItems()) {
  525. children.push_back(ConvertTypeAnnotationToAst(*child, pool, refAtoms));
  526. }
  527. return TAstNode::NewList(TPosition(), children.data(), children.size(), pool);
  528. }
  529. case ETypeAnnotationKind::Struct:
  530. {
  531. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Struct"), pool);
  532. TSmallVec<TAstNode*> children;
  533. children.push_back(self);
  534. for (auto& child : annotation.Cast<TStructExprType>()->GetItems()) {
  535. children.push_back(ConvertTypeAnnotationToAst(*child, pool, refAtoms));
  536. }
  537. return TAstNode::NewList(TPosition(), children.data(), children.size(), pool);
  538. }
  539. case ETypeAnnotationKind::List:
  540. {
  541. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("List"), pool);
  542. auto itemType = ConvertTypeAnnotationToAst(*annotation.Cast<TListExprType>()->GetItemType(), pool, refAtoms);
  543. return TAstNode::NewList(TPosition(), pool, self, itemType);
  544. }
  545. case ETypeAnnotationKind::Optional:
  546. {
  547. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Optional"), pool);
  548. auto itemType = ConvertTypeAnnotationToAst(*annotation.Cast<TOptionalExprType>()->GetItemType(), pool, refAtoms);
  549. return TAstNode::NewList(TPosition(), pool, self, itemType);
  550. }
  551. case ETypeAnnotationKind::Item:
  552. {
  553. auto casted = annotation.Cast<TItemExprType>();
  554. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Item"), pool);
  555. auto name = refAtoms ?
  556. TAstNode::NewLiteralAtom(TPosition(), casted->GetName(), pool, TNodeFlags::ArbitraryContent) :
  557. TAstNode::NewAtom(TPosition(), casted->GetName(), pool, TNodeFlags::ArbitraryContent);
  558. auto itemType = ConvertTypeAnnotationToAst(*casted->GetItemType(), pool, refAtoms);
  559. return TAstNode::NewList(TPosition(), pool, self, name, itemType);
  560. }
  561. case ETypeAnnotationKind::Data:
  562. {
  563. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Data"), pool);
  564. auto datatype = refAtoms ?
  565. TAstNode::NewLiteralAtom(TPosition(), annotation.Cast<TDataExprType>()->GetName(), pool) :
  566. TAstNode::NewAtom(TPosition(), annotation.Cast<TDataExprType>()->GetName(), pool);
  567. if (auto params = dynamic_cast<const TDataExprParamsType*>(&annotation)) {
  568. auto param1 = refAtoms ?
  569. TAstNode::NewLiteralAtom(TPosition(), params->GetParamOne(), pool) :
  570. TAstNode::NewAtom(TPosition(), params->GetParamOne(), pool);
  571. auto param2 = refAtoms ?
  572. TAstNode::NewLiteralAtom(TPosition(), params->GetParamTwo(), pool) :
  573. TAstNode::NewAtom(TPosition(), params->GetParamTwo(), pool);
  574. return TAstNode::NewList(TPosition(), pool, self, datatype, param1, param2);
  575. }
  576. return TAstNode::NewList(TPosition(), pool, self, datatype);
  577. }
  578. case ETypeAnnotationKind::Pg:
  579. {
  580. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Pg"), pool);
  581. auto name = TAstNode::NewLiteralAtom(TPosition(), annotation.Cast<TPgExprType>()->GetName(), pool);
  582. return TAstNode::NewList(TPosition(), pool, self, name);
  583. }
  584. case ETypeAnnotationKind::World:
  585. {
  586. return TAstNode::NewLiteralAtom(TPosition(), TStringBuf("World"), pool);
  587. }
  588. case ETypeAnnotationKind::Type:
  589. {
  590. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Type"), pool);
  591. auto type = ConvertTypeAnnotationToAst(*annotation.Cast<TTypeExprType>()->GetType(), pool, refAtoms);
  592. return TAstNode::NewList(TPosition(), pool, self, type);
  593. }
  594. case ETypeAnnotationKind::Dict:
  595. {
  596. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Dict"), pool);
  597. auto dictType = annotation.Cast<TDictExprType>();
  598. auto keyType = ConvertTypeAnnotationToAst(*dictType->GetKeyType(), pool, refAtoms);
  599. auto payloadType = ConvertTypeAnnotationToAst(*dictType->GetPayloadType(), pool, refAtoms);
  600. return TAstNode::NewList(TPosition(), pool, self, keyType, payloadType);
  601. }
  602. case ETypeAnnotationKind::Void:
  603. {
  604. return TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Void"), pool);
  605. }
  606. case ETypeAnnotationKind::Null:
  607. {
  608. return TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Null"), pool);
  609. }
  610. case ETypeAnnotationKind::Callable:
  611. {
  612. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Callable"), pool);
  613. auto callable = annotation.Cast<TCallableExprType>();
  614. TSmallVec<TAstNode*> mainSettings;
  615. if (callable->GetOptionalArgumentsCount() > 0 || !callable->GetPayload().empty()) {
  616. auto optArgs = TAstNode::NewAtom(TPosition(), ToString(callable->GetOptionalArgumentsCount()), pool);
  617. mainSettings.push_back(optArgs);
  618. }
  619. if (!callable->GetPayload().empty()) {
  620. auto payload = TAstNode::NewAtom(TPosition(), callable->GetPayload(), pool, TNodeFlags::ArbitraryContent);
  621. mainSettings.push_back(payload);
  622. }
  623. TSmallVec<TAstNode*> children;
  624. children.push_back(self);
  625. children.push_back(TAstNode::NewList(TPosition(), mainSettings.data(), mainSettings.size(), pool));
  626. TSmallVec<TAstNode*> retSettings;
  627. retSettings.push_back(ConvertTypeAnnotationToAst(*callable->GetReturnType(), pool, refAtoms));
  628. children.push_back(TAstNode::NewList(TPosition(), retSettings.data(), retSettings.size(), pool));
  629. for (auto& arg : callable->GetArguments()) {
  630. TSmallVec<TAstNode*> argSettings;
  631. argSettings.push_back(ConvertTypeAnnotationToAst(*arg.Type, pool, refAtoms));
  632. if (!arg.Name.empty() || arg.Flags != 0) {
  633. auto name = TAstNode::NewAtom(TPosition(), arg.Name, pool, TNodeFlags::ArbitraryContent);
  634. argSettings.push_back(name);
  635. }
  636. if (arg.Flags != 0) {
  637. auto flags = TAstNode::NewAtom(TPosition(), ToString(arg.Flags), pool, TNodeFlags::ArbitraryContent);
  638. argSettings.push_back(flags);
  639. }
  640. children.push_back(TAstNode::NewList(TPosition(), argSettings.data(), argSettings.size(), pool));
  641. }
  642. return TAstNode::NewList(TPosition(), children.data(), children.size(), pool);
  643. }
  644. case ETypeAnnotationKind::Generic:
  645. {
  646. return TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Generic"), pool);
  647. }
  648. case ETypeAnnotationKind::Resource:
  649. {
  650. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Resource"), pool);
  651. auto restype = refAtoms ?
  652. TAstNode::NewLiteralAtom(TPosition(), annotation.Cast<TResourceExprType>()->GetTag(), pool, TNodeFlags::ArbitraryContent) :
  653. TAstNode::NewAtom(TPosition(), annotation.Cast<TResourceExprType>()->GetTag(), pool, TNodeFlags::ArbitraryContent);
  654. return TAstNode::NewList(TPosition(), pool, self, restype);
  655. }
  656. case ETypeAnnotationKind::Tagged:
  657. {
  658. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Tagged"), pool);
  659. auto type = ConvertTypeAnnotationToAst(*annotation.Cast<TTaggedExprType>()->GetBaseType(), pool, refAtoms);
  660. auto restype = refAtoms ?
  661. TAstNode::NewLiteralAtom(TPosition(), annotation.Cast<TTaggedExprType>()->GetTag(), pool, TNodeFlags::ArbitraryContent) :
  662. TAstNode::NewAtom(TPosition(), annotation.Cast<TTaggedExprType>()->GetTag(), pool, TNodeFlags::ArbitraryContent);
  663. return TAstNode::NewList(TPosition(), pool, self, type, restype);
  664. }
  665. case ETypeAnnotationKind::Error:
  666. {
  667. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Error"), pool);
  668. const auto& err = annotation.Cast<TErrorExprType>()->GetError();
  669. auto row = TAstNode::NewAtom(TPosition(), ToString(err.Position.Row), pool);
  670. auto column = TAstNode::NewAtom(TPosition(), ToString(err.Position.Column), pool);
  671. auto file = refAtoms ?
  672. TAstNode::NewLiteralAtom(TPosition(), err.Position.File, pool, TNodeFlags::ArbitraryContent) :
  673. TAstNode::NewAtom(TPosition(), err.Position.File, pool, TNodeFlags::ArbitraryContent);
  674. auto message = refAtoms ?
  675. TAstNode::NewLiteralAtom(TPosition(), err.GetMessage(), pool, TNodeFlags::ArbitraryContent) :
  676. TAstNode::NewAtom(TPosition(), err.GetMessage(), pool, TNodeFlags::ArbitraryContent);
  677. return TAstNode::NewList(TPosition(), pool, self, row, column, file, message);
  678. }
  679. case ETypeAnnotationKind::Variant:
  680. {
  681. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Variant"), pool);
  682. auto underlyingType = ConvertTypeAnnotationToAst(*annotation.Cast<TVariantExprType>()->GetUnderlyingType(), pool, refAtoms);
  683. return TAstNode::NewList(TPosition(), pool, self, underlyingType);
  684. }
  685. case ETypeAnnotationKind::Stream:
  686. {
  687. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Stream"), pool);
  688. auto itemType = ConvertTypeAnnotationToAst(*annotation.Cast<TStreamExprType>()->GetItemType(), pool, refAtoms);
  689. return TAstNode::NewList(TPosition(), pool, self, itemType);
  690. }
  691. case ETypeAnnotationKind::Flow:
  692. {
  693. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Flow"), pool);
  694. auto itemType = ConvertTypeAnnotationToAst(*annotation.Cast<TFlowExprType>()->GetItemType(), pool, refAtoms);
  695. return TAstNode::NewList(TPosition(), pool, self, itemType);
  696. }
  697. case ETypeAnnotationKind::Multi:
  698. {
  699. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Multi"), pool);
  700. TSmallVec<TAstNode*> children;
  701. children.push_back(self);
  702. for (auto& child : annotation.Cast<TMultiExprType>()->GetItems()) {
  703. children.push_back(ConvertTypeAnnotationToAst(*child, pool, refAtoms));
  704. }
  705. return TAstNode::NewList(TPosition(), children.data(), children.size(), pool);
  706. }
  707. case ETypeAnnotationKind::EmptyList:
  708. {
  709. return TAstNode::NewLiteralAtom(TPosition(), TStringBuf("EmptyList"), pool);
  710. }
  711. case ETypeAnnotationKind::EmptyDict:
  712. {
  713. return TAstNode::NewLiteralAtom(TPosition(), TStringBuf("EmptyDict"), pool);
  714. }
  715. case ETypeAnnotationKind::Block:
  716. {
  717. auto type = annotation.Cast<TBlockExprType>();
  718. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Block"), pool);
  719. auto itemType = ConvertTypeAnnotationToAst(*type->GetItemType(), pool, refAtoms);
  720. return TAstNode::NewList(TPosition(), pool, self, itemType);
  721. }
  722. case ETypeAnnotationKind::Scalar:
  723. {
  724. auto type = annotation.Cast<TScalarExprType>();
  725. auto self = TAstNode::NewLiteralAtom(TPosition(), TStringBuf("Scalar"), pool);
  726. auto itemType = ConvertTypeAnnotationToAst(*type->GetItemType(), pool, refAtoms);
  727. return TAstNode::NewList(TPosition(), pool, self, itemType);
  728. }
  729. case ETypeAnnotationKind::LastType:
  730. YQL_ENSURE(false, "Unknown kind: " << annotation.GetKind());
  731. }
  732. }
  733. TAstNode* AnnotateAstNode(TAstNode* node, const TExprNode* exprNode, ui32 flags, TMemoryPool& pool, bool refAtoms) {
  734. if (!flags)
  735. return node;
  736. TSmallVec<TAstNode*> children;
  737. if (flags & TExprAnnotationFlags::Position) {
  738. children.push_back(PositionAsNode(node->GetPosition(), pool));
  739. }
  740. if ((flags & TExprAnnotationFlags::Types)) {
  741. TAstNode* typeAnn = nullptr;
  742. if (exprNode) {
  743. YQL_ENSURE(exprNode->GetTypeAnn());
  744. typeAnn = ConvertTypeAnnotationToAst(*exprNode->GetTypeAnn(), pool, refAtoms);
  745. } else {
  746. typeAnn = TAstNode::NewLiteralAtom(node->GetPosition(), TStringBuf("."), pool);
  747. }
  748. children.push_back(typeAnn);
  749. }
  750. children.push_back(node);
  751. return TAstNode::NewList(node->GetPosition(), children.data(), children.size(), pool);
  752. }
  753. bool AddParameterDependencies(const TString& url, const TAstNode& node, TContext& ctx) {
  754. auto world = ctx.FindBinding("world");
  755. if (!world.empty()) {
  756. TSet<TString> names;
  757. SubstParameters(url, Nothing(), &names);
  758. for (const auto& name : names) {
  759. auto nameRef = ctx.FindBinding(name);
  760. if (nameRef.empty()) {
  761. ctx.AddError(node, TStringBuilder() << "Name not found: " << name);
  762. return false;
  763. }
  764. TExprNode::TListType args = world;
  765. args.insert(args.end(), nameRef.begin(), nameRef.end());
  766. auto newWorld = TExprNode::TListType{ ctx.Expr.NewCallable(node.GetPosition(), "Left!", {
  767. ctx.Expr.NewCallable(node.GetPosition(), "Cons!", std::move(args)) })};
  768. ctx.Frames.back().Bindings["world"] = newWorld;
  769. world = newWorld;
  770. }
  771. }
  772. return true;
  773. }
  774. TExprNode::TListType Compile(const TAstNode& node, TContext& ctx);
  775. TExprNode::TPtr CompileQuote(const TAstNode& node, TContext& ctx) {
  776. if (node.IsAtom()) {
  777. return ctx.ProcessNode(node, ctx.Expr.NewAtom(node.GetPosition(), TString(node.GetContent()), node.GetFlags()));
  778. } else {
  779. TExprNode::TListType children;
  780. children.reserve(node.GetChildrenCount());
  781. for (ui32 index = 0; index < node.GetChildrenCount(); ++index) {
  782. auto r = Compile(*node.GetChild(index), ctx);
  783. if (r.empty())
  784. return {};
  785. std::move(r.begin(), r.end(), std::back_inserter(children));
  786. }
  787. return ctx.ProcessNode(node, ctx.Expr.NewList(node.GetPosition(), std::move(children)));
  788. }
  789. }
  790. TExprNode::TListType CompileLambda(const TAstNode& node, TContext& ctx) {
  791. if (node.GetChildrenCount() < 2) {
  792. ctx.AddError(node, "Expected size of list at least 3.");
  793. return {};
  794. }
  795. const auto args = node.GetChild(1);
  796. if (!args->IsList() || args->GetChildrenCount() != 2 || !args->GetChild(0)->IsAtom() ||
  797. args->GetChild(0)->GetContent() != TStringBuf("quote") || !args->GetChild(1)->IsList()) {
  798. ctx.AddError(node, "Lambda arguments must be a quoted list of atoms");
  799. return {};
  800. }
  801. const auto params = args->GetChild(1);
  802. for (ui32 index = 0; index < params->GetChildrenCount(); ++index) {
  803. if (!params->GetChild(index)->IsAtom()) {
  804. ctx.AddError(node, "Lambda arguments must be a quoted list of atoms");
  805. return {};
  806. }
  807. }
  808. ctx.PushFrame();
  809. TExprNode::TListType argNodes;
  810. for (ui32 index = 0; index < params->GetChildrenCount(); ++index) {
  811. auto arg = params->GetChild(index);
  812. auto lambdaArg = ctx.ProcessNode(*arg, ctx.Expr.NewArgument(arg->GetPosition(), TString(arg->GetContent())));
  813. argNodes.push_back(lambdaArg);
  814. auto& binding = ctx.Frames.back().Bindings[arg->GetContent()];
  815. if (!binding.empty()) {
  816. ctx.PopFrame();
  817. ctx.AddError(*arg, TStringBuilder() << "Duplicated name of lambda parameter: " << arg->GetContent());
  818. return {};
  819. }
  820. binding = {lambdaArg};
  821. }
  822. TExprNode::TListType body;
  823. body.reserve(node.GetChildrenCount() - 2U);
  824. for (auto i = 2U; i < node.GetChildrenCount(); ++i) {
  825. auto r = Compile(*node.GetChild(i), ctx);
  826. if (r.empty())
  827. return {};
  828. std::move(r.begin(), r.end(), std::back_inserter(body));
  829. }
  830. ctx.PopFrame();
  831. auto arguments = ctx.ProcessNode(*args, ctx.Expr.NewArguments(args->GetPosition(), std::move(argNodes)));
  832. auto lambda = ctx.ProcessNode(node, ctx.Expr.NewLambda(node.GetPosition(), std::move(arguments), std::move(body)));
  833. return {lambda};
  834. }
  835. bool CompileSetPackageVersion(const TAstNode& node, TContext& ctx) {
  836. if (node.GetChildrenCount() != 3) {
  837. ctx.AddError(node, "Expected list of size 3");
  838. return false;
  839. }
  840. const auto name = node.GetChild(1);
  841. if (name->IsAtom() || name->GetChildrenCount() != 2 || !name->GetChild(0)->IsAtom() || !name->GetChild(1)->IsAtom() ||
  842. name->GetChild(0)->GetContent() != TStringBuf("quote")) {
  843. ctx.AddError(*name, "Expected quoted atom for package name");
  844. return false;
  845. }
  846. const auto versionNode = node.GetChild(2);
  847. if (versionNode->IsAtom() || versionNode->GetChildrenCount() != 2 || !versionNode->GetChild(0)->IsAtom() || !versionNode->GetChild(1)->IsAtom() ||
  848. versionNode->GetChild(0)->GetContent() != TStringBuf("quote")) {
  849. ctx.AddError(*versionNode, "Expected quoted atom for package version");
  850. return false;
  851. }
  852. ui32 version = 0;
  853. if (!versionNode->GetChild(1)->IsAtom() || !TryFromString(versionNode->GetChild(1)->GetContent(), version)) {
  854. ctx.AddError(*versionNode, TString("Expected package version as number, bad content ") + versionNode->GetChild(1)->GetContent());
  855. return false;
  856. }
  857. if (ctx.ModuleResolver && !ctx.ModuleResolver->SetPackageDefaultVersion(TString(name->GetChild(1)->GetContent()), version)) {
  858. ctx.AddError(*versionNode, TStringBuilder() << "Unable to specify version " << version << " for package " << name->GetChild(1)->GetContent());
  859. return false;
  860. }
  861. return true;
  862. }
  863. TExprNode::TPtr CompileBind(const TAstNode& node, TContext& ctx) {
  864. if (node.GetChildrenCount() != 3) {
  865. ctx.AddError(node, "Expected list of size 3");
  866. return nullptr;
  867. }
  868. const auto name = node.GetChild(1);
  869. if (!name->IsAtom()) {
  870. ctx.AddError(*name, "Expected atom");
  871. return nullptr;
  872. }
  873. const auto alias = node.GetChild(2);
  874. if (alias->IsAtom() || alias->GetChildrenCount() != 2 || !alias->GetChild(0)->IsAtom() || !alias->GetChild(1)->IsAtom() ||
  875. alias->GetChild(0)->GetContent() != TStringBuf("quote")) {
  876. ctx.AddError(*alias, "Expected quoted pair");
  877. return nullptr;
  878. }
  879. const auto& aliasValue = alias->GetChild(1)->GetContent();
  880. const auto& moduleName = name->GetContent();
  881. TStringBuilder baseMsg;
  882. baseMsg << "Module '" << name->GetContent() << "'";
  883. const auto& import = ctx.FindImport(moduleName);
  884. if (import.empty()) {
  885. ctx.AddError(*name, baseMsg << " does not exist");
  886. return nullptr;
  887. }
  888. if (ctx.ModuleResolver) {
  889. auto exportsPtr = ctx.ModuleResolver->GetModule(import);
  890. if (!exportsPtr) {
  891. ctx.AddError(*name, baseMsg << "'" << import << "' does not exist");
  892. return nullptr;
  893. }
  894. const auto& exports = exportsPtr->Symbols();
  895. const auto ex = exports.find(aliasValue);
  896. if (exports.cend() == ex) {
  897. ctx.AddError(*alias, baseMsg << " export '" << aliasValue << "' does not exist");
  898. return nullptr;
  899. }
  900. return ctx.Expr.DeepCopy(*ex->second, exportsPtr->ExprCtx(), ctx.DeepClones, true, false);
  901. } else {
  902. const auto stub = ctx.Expr.NewAtom(node.GetPosition(), "stub");
  903. ctx.Frames.back().Bindings[name->GetContent()] = {stub};
  904. ctx.Cohesion.Imports[stub.Get()] = std::make_pair(import, TString(aliasValue));
  905. return stub;
  906. }
  907. }
  908. bool CompileLet(const TAstNode& node, TContext& ctx) {
  909. if (node.GetChildrenCount() < 3) {
  910. ctx.AddError(node, "Expected size of list at least 3.");
  911. return false;
  912. }
  913. const auto name = node.GetChild(1);
  914. if (!name->IsAtom()) {
  915. ctx.AddError(*name, "Expected atom");
  916. return false;
  917. }
  918. TExprNode::TListType bind;
  919. bind.reserve(node.GetChildrenCount() - 2U);
  920. for (auto i = 2U; i < node.GetChildrenCount(); ++i) {
  921. auto r = Compile(*node.GetChild(i), ctx);
  922. if (r.empty())
  923. return false;
  924. std::move(r.begin(), r.end(), std::back_inserter(bind));
  925. }
  926. ctx.Frames.back().Bindings[name->GetContent()] = std::move(bind);
  927. return true;
  928. }
  929. bool CompileImport(const TAstNode& node, TContext& ctx) {
  930. if (node.GetChildrenCount() != 3) {
  931. ctx.AddError(node, "Expected list of size 3");
  932. return false;
  933. }
  934. const auto name = node.GetChild(1);
  935. if (!name->IsAtom()) {
  936. ctx.AddError(*name, "Expected atom");
  937. return false;
  938. }
  939. const auto alias = node.GetChild(2);
  940. if (!alias->IsListOfSize(2) || !alias->GetChild(0)->IsAtom() || !alias->GetChild(1)->IsAtom() ||
  941. alias->GetChild(0)->GetContent() != TStringBuf("quote")) {
  942. ctx.AddError(node, "Expected quoted pair");
  943. return false;
  944. }
  945. ctx.Frames.back().Imports[name->GetContent()] = alias->GetChild(1)->GetContent();
  946. return true;
  947. }
  948. bool CompileExport(const TAstNode& node, TContext& ctx) {
  949. if (node.GetChildrenCount() != 2) {
  950. ctx.AddError(node, "Expected list of size 2");
  951. return false;
  952. }
  953. const auto name = node.GetChild(1);
  954. if (!name->IsAtom()) {
  955. ctx.AddError(*name, "Expected atom");
  956. return false;
  957. }
  958. auto r = Compile(*node.GetChild(1), ctx);
  959. if (r.size() != 1U)
  960. return false;
  961. ctx.Cohesion.Exports.Symbols(ctx.Expr)[name->GetContent()] = std::move(r.front());
  962. return true;
  963. }
  964. bool CompileDeclare(const TAstNode& node, TContext& ctx, bool checkOnly) {
  965. if (node.GetChildrenCount() != 3) {
  966. ctx.AddError(node, "Expected list of size 3");
  967. return false;
  968. }
  969. const auto name = node.GetChild(1);
  970. if (!name->IsAtom()) {
  971. ctx.AddError(*name, "Expected atom");
  972. return false;
  973. }
  974. TString nameStr = TString(name->GetContent());
  975. if (nameStr.size() < 2) {
  976. ctx.AddError(*name, "Parameter name should be at least 2 characters long.");
  977. return false;
  978. }
  979. if (nameStr[0] == '$' && std::isdigit(nameStr[1])) {
  980. ctx.AddError(*name, "Parameter name cannot start with digit.");
  981. return false;
  982. }
  983. auto typeExpr = Compile(*node.GetChild(2), ctx);
  984. if (typeExpr.size() != 1U)
  985. return false;
  986. auto typePos = node.GetChild(2)->GetPosition();
  987. auto parameterExpr = ctx.ProcessNode(node,
  988. ctx.Expr.NewCallable(typePos, "Parameter", {
  989. ctx.Expr.NewAtom(node.GetPosition(), nameStr),
  990. std::move(typeExpr.front())
  991. }));
  992. bool error = false;
  993. if (checkOnly) {
  994. auto it = ctx.Frames.back().Bindings.find(nameStr);
  995. if (it == ctx.Frames.back().Bindings.end()) {
  996. ctx.AddError(*name, TStringBuilder() << "Missing parameter: " << nameStr);
  997. return false;
  998. }
  999. if (it->second.size() != 1 || !it->second.front()->IsCallable("Parameter")) {
  1000. error = true;
  1001. }
  1002. } else {
  1003. if (!ctx.Frames.back().Bindings.emplace(nameStr, TExprNode::TListType{ std::move(parameterExpr) }).second) {
  1004. error = true;
  1005. }
  1006. }
  1007. if (error) {
  1008. ctx.AddError(node, TStringBuilder() << "Declare statement hides previously defined name: " << nameStr);
  1009. return false;
  1010. }
  1011. return true;
  1012. }
  1013. bool CompileLibraryDef(const TAstNode& node, TContext& ctx) {
  1014. if (node.GetChildrenCount() < 2 || node.GetChildrenCount() > 4) {
  1015. ctx.AddError(node, "Expected list of size from 2 to 4");
  1016. return false;
  1017. }
  1018. const auto name = node.GetChild(1);
  1019. if (!name->IsAtom()) {
  1020. ctx.AddError(*name, "Expected atom");
  1021. return false;
  1022. }
  1023. TString url;
  1024. TString token;
  1025. if (node.GetChildrenCount() > 2) {
  1026. const auto file = node.GetChild(2);
  1027. if (!file->IsAtom()) {
  1028. ctx.AddError(*file, "Expected atom");
  1029. return false;
  1030. }
  1031. url = file->GetContent();
  1032. if (node.GetChildrenCount() > 3) {
  1033. const auto tokenNode = node.GetChild(3);
  1034. if (!tokenNode->IsAtom()) {
  1035. ctx.AddError(*tokenNode, "Expected atom");
  1036. return false;
  1037. }
  1038. token = tokenNode->GetContent();
  1039. }
  1040. }
  1041. if (url && !AddParameterDependencies(url, node, ctx)) {
  1042. return false;
  1043. }
  1044. if (!ctx.ModuleResolver) {
  1045. return true;
  1046. }
  1047. if (url) {
  1048. if (!ctx.ModuleResolver->AddFromUrl(name->GetContent(), url, token, ctx.Expr, ctx.SyntaxVersion, 0, name->GetPosition())) {
  1049. return false;
  1050. }
  1051. } else {
  1052. if (!ctx.ModuleResolver->AddFromFile(name->GetContent(), ctx.Expr, ctx.SyntaxVersion, 0, name->GetPosition())) {
  1053. return false;
  1054. }
  1055. }
  1056. return true;
  1057. }
  1058. bool CompilePackageDef(const TAstNode& node, TContext& ctx) {
  1059. if (node.GetChildrenCount() < 2 || node.GetChildrenCount() > 4) {
  1060. ctx.AddError(node, "Expected list of size from 2 to 4");
  1061. return false;
  1062. }
  1063. auto nameNode = node.GetChild(1);
  1064. if (!nameNode->IsAtom()) {
  1065. ctx.AddError(*nameNode, "Expected atom");
  1066. return false;
  1067. }
  1068. auto name = TString(nameNode->GetContent());
  1069. TString url;
  1070. if (node.GetChildrenCount() > 2) {
  1071. const auto file = node.GetChild(2);
  1072. if (!file->IsAtom()) {
  1073. ctx.AddError(*file, "Expected atom");
  1074. return false;
  1075. }
  1076. url = file->GetContent();
  1077. }
  1078. TString token;
  1079. if (node.GetChildrenCount() > 3) {
  1080. const auto tokenNode = node.GetChild(3);
  1081. if (!tokenNode->IsAtom()) {
  1082. ctx.AddError(*tokenNode, "Expected atom");
  1083. return false;
  1084. }
  1085. token = tokenNode->GetContent();
  1086. }
  1087. if (url && !AddParameterDependencies(url, node, ctx)) {
  1088. return false;
  1089. }
  1090. if (!ctx.ModuleResolver) {
  1091. return true;
  1092. }
  1093. if (!ctx.UrlListerManager) {
  1094. return true;
  1095. }
  1096. ctx.ModuleResolver->RegisterPackage(name);
  1097. auto packageModuleName = TStringBuilder() << PkgPrefix;
  1098. TStringBuf nameBuf(name);
  1099. while (auto part = nameBuf.NextTok(Dot)) {
  1100. packageModuleName << Sep << part;
  1101. }
  1102. auto queue = TVector<std::pair<TString, TString>> {
  1103. {packageModuleName, url}
  1104. };
  1105. while (queue) {
  1106. auto [prefix, url] = queue.back();
  1107. queue.pop_back();
  1108. TVector<TUrlListEntry> urlListEntries;
  1109. try {
  1110. urlListEntries = ctx.UrlListerManager->ListUrl(url, token);
  1111. } catch (const std::exception& e) {
  1112. ctx.AddError(*nameNode,
  1113. TStringBuilder()
  1114. << "UrlListerManager: failed to list URL \"" << url
  1115. << "\", details: " << e.what()
  1116. );
  1117. return false;
  1118. }
  1119. for (auto& urlListEntry: urlListEntries) {
  1120. switch (urlListEntry.Type) {
  1121. case EUrlListEntryType::FILE: {
  1122. auto moduleName = TStringBuilder()
  1123. << prefix << Sep << urlListEntry.Name;
  1124. if (ctx.OverrideLibraries.contains(moduleName)) {
  1125. continue;
  1126. }
  1127. if (!ctx.ModuleResolver->AddFromUrl(
  1128. moduleName, urlListEntry.Url, token, ctx.Expr,
  1129. ctx.SyntaxVersion, 0, nameNode->GetPosition()
  1130. )) {
  1131. return false;
  1132. }
  1133. break;
  1134. }
  1135. case EUrlListEntryType::DIRECTORY: {
  1136. queue.push_back({
  1137. TStringBuilder() << prefix << Sep << urlListEntry.Name,
  1138. urlListEntry.Url
  1139. });
  1140. break;
  1141. }
  1142. }
  1143. }
  1144. }
  1145. return true;
  1146. }
  1147. bool CompileOverrideLibraryDef(const TAstNode& node, TContext& ctx) {
  1148. if (node.GetChildrenCount() != 2) {
  1149. ctx.AddError(node, "Expected list of size 2");
  1150. return false;
  1151. }
  1152. auto nameNode = node.GetChild(1);
  1153. if (!nameNode->IsAtom()) {
  1154. ctx.AddError(*nameNode, "Expected atom");
  1155. return false;
  1156. }
  1157. if (!ctx.ModuleResolver) {
  1158. return true;
  1159. }
  1160. auto overrideLibraryName = TStringBuilder()
  1161. << PkgPrefix << Sep << nameNode->GetContent();
  1162. if (!ctx.ModuleResolver->AddFromFile(
  1163. overrideLibraryName, ctx.Expr, ctx.SyntaxVersion, 0, nameNode->GetPosition()
  1164. )) {
  1165. return false;
  1166. }
  1167. ctx.OverrideLibraries.insert(std::move(overrideLibraryName));
  1168. return true;
  1169. }
  1170. bool CompileReturn(const TAstNode& node, TContext& ctx) {
  1171. if (node.GetChildrenCount() < 2U) {
  1172. ctx.AddError(node, "Expected non empty list.");
  1173. return false;
  1174. }
  1175. TExprNode::TListType returns;
  1176. returns.reserve(node.GetChildrenCount() - 1U);
  1177. for (auto i = 1U; i < node.GetChildrenCount(); ++i) {
  1178. auto r = Compile(*node.GetChild(i), ctx);
  1179. if (r.empty())
  1180. return false;
  1181. std::move(r.begin(), r.end(), std::back_inserter(returns));
  1182. }
  1183. ctx.Frames.back().Return = std::move(returns);
  1184. return true;
  1185. }
  1186. TExprNode::TListType CompileFunction(const TAstNode& root, TContext& ctx, bool topLevel = false) {
  1187. if (!root.IsList()) {
  1188. ctx.AddError(root, "Expected list");
  1189. return {};
  1190. }
  1191. if (ctx.Frames.size() > 1000U) {
  1192. ctx.AddError(root, "Too deep graph!");
  1193. return {};
  1194. }
  1195. ctx.PushFrame();
  1196. if (topLevel) {
  1197. for (ui32 index = 0; index < root.GetChildrenCount(); ++index) {
  1198. const auto node = root.GetChild(index);
  1199. if (!node->IsList()) {
  1200. ctx.AddError(*node, "Expected list");
  1201. return {};
  1202. }
  1203. if (node->GetChildrenCount() == 0) {
  1204. ctx.AddError(*node, "Expected not empty list");
  1205. return {};
  1206. }
  1207. const auto firstChild = node->GetChild(0);
  1208. if (!firstChild->IsAtom()) {
  1209. ctx.AddError(*firstChild, "Expected atom");
  1210. return {};
  1211. }
  1212. if (firstChild->GetContent() == TStringBuf("library")) {
  1213. if (!CompileLibraryDef(*node, ctx))
  1214. return {};
  1215. } else if (firstChild->GetContent() == TStringBuf("set_package_version")) {
  1216. if (!CompileSetPackageVersion(*node, ctx))
  1217. return {};
  1218. } else if (firstChild->GetContent() == TStringBuf("declare")) {
  1219. if (!CompileDeclare(*node, ctx, false))
  1220. return {};
  1221. } else if (firstChild->GetContent() == TStringBuf("package")) {
  1222. if (!CompilePackageDef(*node, ctx)) {
  1223. return {};
  1224. }
  1225. } else if (firstChild->GetContent() == TStringBuf("override_library")) {
  1226. if (!CompileOverrideLibraryDef(*node, ctx)) {
  1227. return {};
  1228. }
  1229. }
  1230. }
  1231. if (ctx.ModuleResolver) {
  1232. if (!ctx.ModuleResolver->Link(ctx.Expr)) {
  1233. return {};
  1234. }
  1235. ctx.ModuleResolver->UpdateNextUniqueId(ctx.Expr);
  1236. }
  1237. }
  1238. for (ui32 index = 0; index < root.GetChildrenCount(); ++index) {
  1239. const auto node = root.GetChild(index);
  1240. if (!ctx.Frames.back().Return.empty()) {
  1241. ctx.Frames.back().Return.clear();
  1242. ctx.AddError(*node, "Return is already exist");
  1243. return {};
  1244. }
  1245. if (!node->IsList()) {
  1246. ctx.AddError(*node, "Expected list");
  1247. return {};
  1248. }
  1249. if (node->GetChildrenCount() == 0) {
  1250. ctx.AddError(*node, "Expected not empty list");
  1251. return {};
  1252. }
  1253. auto firstChild = node->GetChild(0);
  1254. if (!firstChild->IsAtom()) {
  1255. ctx.AddError(*firstChild, "Expected atom");
  1256. return {};
  1257. }
  1258. if (firstChild->GetContent() == TStringBuf("let")) {
  1259. if (!CompileLet(*node, ctx))
  1260. return {};
  1261. } else if (firstChild->GetContent() == TStringBuf("return")) {
  1262. if (!CompileReturn(*node, ctx))
  1263. return {};
  1264. } else if (firstChild->GetContent() == TStringBuf("import")) {
  1265. if (!CompileImport(*node, ctx))
  1266. return {};
  1267. } else if (firstChild->GetContent() == TStringBuf("declare")) {
  1268. if (!topLevel) {
  1269. ctx.AddError(*firstChild, "Declare statements are only allowed on top level block");
  1270. return {};
  1271. }
  1272. if (!CompileDeclare(*node, ctx, true))
  1273. return {};
  1274. continue;
  1275. } else if (firstChild->GetContent() == TStringBuf("library")) {
  1276. if (!topLevel) {
  1277. ctx.AddError(*firstChild, "Library statements are only allowed on top level block");
  1278. return {};
  1279. }
  1280. continue;
  1281. } else if (firstChild->GetContent() == TStringBuf("set_package_version")) {
  1282. if (!topLevel) {
  1283. ctx.AddError(*firstChild, "set_package_version statements are only allowed on top level block");
  1284. return {};
  1285. }
  1286. continue;
  1287. } else if (firstChild->GetContent() == TStringBuf("package")) {
  1288. if (!topLevel) {
  1289. ctx.AddError(*firstChild, "Package statements are only allowed on top level block");
  1290. return {};
  1291. }
  1292. } else if (firstChild->GetContent() == TStringBuf("override_library")) {
  1293. if (!topLevel) {
  1294. ctx.AddError(*firstChild, "override_library statements are only allowed on top level block");
  1295. return {};
  1296. }
  1297. } else {
  1298. ctx.AddError(*firstChild, ToString("expected either let, return or import, but have ") + firstChild->GetContent());
  1299. return {};
  1300. }
  1301. }
  1302. auto ret = std::move(ctx.Frames.back().Return);
  1303. ctx.PopFrame();
  1304. if (ret.empty()) {
  1305. ctx.AddError(root, "No return found");
  1306. }
  1307. return ret;
  1308. }
  1309. bool CompileLibrary(const TAstNode& root, TContext& ctx) {
  1310. if (!root.IsList()) {
  1311. ctx.AddError(root, "Expected list");
  1312. return false;
  1313. }
  1314. ctx.PushFrame();
  1315. for (ui32 index = 0; index < root.GetChildrenCount(); ++index) {
  1316. const auto node = root.GetChild(index);
  1317. if (!node->IsList()) {
  1318. ctx.AddError(*node, "Expected list");
  1319. return false;
  1320. }
  1321. if (node->GetChildrenCount() == 0) {
  1322. ctx.AddError(*node, "Expected not empty list");
  1323. return false;
  1324. }
  1325. auto firstChild = node->GetChild(0);
  1326. if (!firstChild->IsAtom()) {
  1327. ctx.AddError(*firstChild, "Expected atom");
  1328. return false;
  1329. }
  1330. if (firstChild->GetContent() == TStringBuf("let")) {
  1331. if (!CompileLet(*node, ctx))
  1332. return false;
  1333. } else if (firstChild->GetContent() == TStringBuf("import")) {
  1334. if (!CompileImport(*node, ctx))
  1335. return false;
  1336. } else if (firstChild->GetContent() == TStringBuf("export")) {
  1337. if (!CompileExport(*node, ctx))
  1338. return false;
  1339. } else {
  1340. ctx.AddError(*firstChild, "expected either let, export or import");
  1341. return false;
  1342. }
  1343. }
  1344. ctx.PopFrame();
  1345. return true;
  1346. }
  1347. TExprNode::TListType Compile(const TAstNode& node, TContext& ctx) {
  1348. if (node.IsAtom()) {
  1349. const auto foundNode = ctx.FindBinding(node.GetContent());
  1350. if (foundNode.empty()) {
  1351. ctx.AddError(node, TStringBuilder() << "Name not found: " << node.GetContent());
  1352. return {};
  1353. }
  1354. return foundNode;
  1355. }
  1356. if (node.GetChildrenCount() == 0) {
  1357. ctx.AddError(node, "Empty list, did you forget quote?");
  1358. return {};
  1359. }
  1360. if (!node.GetChild(0)->IsAtom()) {
  1361. ctx.AddError(node, "First item in list is not an atom, did you forget quote?");
  1362. return {};
  1363. }
  1364. auto function = node.GetChild(0)->GetContent();
  1365. if (function == TStringBuf("quote")) {
  1366. if (node.GetChildrenCount() != 2) {
  1367. ctx.AddError(node, "Quote should have one argument");
  1368. return {};
  1369. }
  1370. if (auto quote = CompileQuote(*node.GetChild(1), ctx))
  1371. return {std::move(quote)};
  1372. return {};
  1373. }
  1374. if (function == TStringBuf("let") || function == TStringBuf("return")) {
  1375. ctx.AddError(node, "Let and return should be used only at first level or inside def");
  1376. return {};
  1377. }
  1378. if (function == TStringBuf("lambda")) {
  1379. return CompileLambda(node, ctx);
  1380. }
  1381. if (function == TStringBuf("bind")) {
  1382. if (auto bind = CompileBind(node, ctx))
  1383. return {std::move(bind)};
  1384. return {};
  1385. }
  1386. if (function == TStringBuf("block")) {
  1387. if (node.GetChildrenCount() != 2) {
  1388. ctx.AddError(node, "Block should have one argument");
  1389. return {};
  1390. }
  1391. const auto quotedList = node.GetChild(1);
  1392. if (quotedList->GetChildrenCount() != 2 || !quotedList->GetChild(0)->IsAtom() ||
  1393. quotedList->GetChild(0)->GetContent() != TStringBuf("quote")) {
  1394. ctx.AddError(node, "Expected quoted list");
  1395. return {};
  1396. }
  1397. return CompileFunction(*quotedList->GetChild(1), ctx);
  1398. }
  1399. TExprNode::TListType children;
  1400. children.reserve(node.GetChildrenCount() - 1U);
  1401. for (auto index = 1U; index < node.GetChildrenCount(); ++index) {
  1402. auto r = Compile(*node.GetChild(index), ctx);
  1403. if (r.empty())
  1404. return {};
  1405. std::move(r.begin(), r.end(), std::back_inserter(children));
  1406. }
  1407. return {ctx.ProcessNode(node, ctx.Expr.NewCallable(node.GetPosition(), TString(function), std::move(children)))};
  1408. }
  1409. struct TFrameContext {
  1410. size_t Index = 0;
  1411. size_t Parent = 0;
  1412. std::map<size_t, const TExprNode*> Nodes;
  1413. std::vector<const TExprNode*> TopoSortedNodes;
  1414. TNodeMap<TString> Bindings;
  1415. };
  1416. struct TVisitNodeContext {
  1417. explicit TVisitNodeContext(TExprContext& expr)
  1418. : Expr(expr)
  1419. {}
  1420. TExprContext& Expr;
  1421. size_t Order = 0ULL;
  1422. bool RefAtoms = false;
  1423. bool AllowFreeArgs = false;
  1424. bool NormalizeAtomFlags = false;
  1425. TNodeMap<size_t> FreeArgs;
  1426. std::unique_ptr<TMemoryPool> Pool;
  1427. std::vector<TFrameContext> Frames;
  1428. TFrameContext* CurrentFrame = nullptr;
  1429. TNodeMap<size_t> LambdaFrames;
  1430. std::map<TStringBuf, std::pair<const TExprNode*, TAstNode*>> Parameters;
  1431. struct TCounters {
  1432. size_t References = 0ULL, Neighbors = 0ULL, Order = 0ULL, Frame = 0ULL;
  1433. };
  1434. TNodeMap<TCounters> References;
  1435. const TString& FindBinding(const TExprNode* node) const {
  1436. for (const auto* frame = CurrentFrame; frame; frame = frame->Index > 0 ? &Frames[frame->Parent] : nullptr) {
  1437. const auto it = frame->Bindings.find(node);
  1438. if (frame->Bindings.cend() != it)
  1439. return it->second;
  1440. }
  1441. static const TString stub;
  1442. return stub;
  1443. }
  1444. size_t FindCommonAncestor(size_t one, size_t two) const {
  1445. while (one && two) {
  1446. if (one == two)
  1447. return one;
  1448. if (one > two)
  1449. one = Frames[one].Parent;
  1450. else
  1451. two = Frames[two].Parent;
  1452. }
  1453. return 0ULL;
  1454. }
  1455. };
  1456. void VisitArguments(const TExprNode& node, TVisitNodeContext& ctx) {
  1457. YQL_ENSURE(node.Type() == TExprNode::Arguments);
  1458. for (const auto& arg : node.Children()) {
  1459. auto& counts = ctx.References[arg.Get()];
  1460. ++counts.References;
  1461. YQL_ENSURE(ctx.CurrentFrame->Nodes.emplace(counts.Order = ++ctx.Order, arg.Get()).second);
  1462. }
  1463. }
  1464. void RevisitNode(const TExprNode& node, TVisitNodeContext& ctx);
  1465. void RevisitNode(TVisitNodeContext::TCounters& counts, const TExprNode& node, TVisitNodeContext& ctx) {
  1466. const auto nf = ctx.FindCommonAncestor(ctx.CurrentFrame->Index, counts.Frame);
  1467. if (counts.Frame != nf) {
  1468. auto& frame = ctx.Frames[counts.Frame = nf];
  1469. frame.Nodes.emplace(counts.Order, &node);
  1470. if (TExprNode::Lambda == node.Type()) {
  1471. ctx.Frames[ctx.LambdaFrames[&node]].Parent = counts.Frame;
  1472. } else {
  1473. node.ForEachChild([&ctx](const TExprNode& child) {
  1474. RevisitNode(child, ctx);
  1475. });
  1476. }
  1477. }
  1478. }
  1479. void RevisitNode(const TExprNode& node, TVisitNodeContext& ctx) {
  1480. if (TExprNode::Argument != node.Type()) {
  1481. RevisitNode(ctx.References[&node], node, ctx);
  1482. }
  1483. }
  1484. void VisitNode(const TExprNode& node, size_t neighbors, TVisitNodeContext& ctx) {
  1485. if (TExprNode::Argument == node.Type())
  1486. return;
  1487. auto& counts = ctx.References[&node];
  1488. counts.Neighbors += neighbors;
  1489. if (counts.References++) {
  1490. RevisitNode(counts, node, ctx);
  1491. } else {
  1492. counts.Frame = ctx.CurrentFrame->Index;
  1493. if (node.Type() == TExprNode::Lambda) {
  1494. YQL_ENSURE(node.ChildrenSize() > 0U);
  1495. const auto index = ctx.Frames.size();
  1496. if (ctx.LambdaFrames.emplace(&node, index).second) {
  1497. const auto prevFrameIndex = ctx.CurrentFrame - &ctx.Frames.front();
  1498. const auto parentIndex = ctx.CurrentFrame->Index;
  1499. ctx.Frames.emplace_back();
  1500. ctx.CurrentFrame = &ctx.Frames.back();
  1501. ctx.CurrentFrame->Index = index;
  1502. ctx.CurrentFrame->Parent = parentIndex;
  1503. VisitArguments(node.Head(), ctx);
  1504. for(ui32 i = 1U; i < node.ChildrenSize(); ++i) {
  1505. VisitNode(*node.Child(i), node.ChildrenSize() - 1U, ctx);
  1506. }
  1507. ctx.CurrentFrame = &ctx.Frames.front() + prevFrameIndex;
  1508. }
  1509. } else {
  1510. node.ForEachChild([&](const TExprNode& child) {
  1511. VisitNode(child, node.ChildrenSize(), ctx);
  1512. });
  1513. }
  1514. if (!counts.Order)
  1515. counts.Order = ++ctx.Order;
  1516. ctx.CurrentFrame->Nodes.emplace(counts.Order, &node);
  1517. }
  1518. }
  1519. using TRoots = TSmallVec<const TExprNode*>;
  1520. TAstNode* ConvertFunction(TPositionHandle position, const TRoots& roots, TVisitNodeContext& ctx, ui32 annotationFlags, TMemoryPool& pool);
  1521. TAstNode* BuildValueNode(const TExprNode& node, TVisitNodeContext& ctx, const TString& topLevelName, ui32 annotationFlags, TMemoryPool& pool, bool useBindings) {
  1522. TAstNode* res = nullptr;
  1523. const auto& name = ctx.FindBinding(&node);
  1524. if (!name.empty() && name != topLevelName && useBindings) {
  1525. res = TAstNode::NewAtom(ctx.Expr.GetPosition(node.Pos()), name, pool);
  1526. } else {
  1527. switch (node.Type()) {
  1528. case TExprNode::Atom:
  1529. {
  1530. auto quote = AnnotateAstNode(&TAstNode::QuoteAtom, nullptr, annotationFlags, pool, ctx.RefAtoms);
  1531. auto flags = ctx.NormalizeAtomFlags ? TNodeFlags::ArbitraryContent : node.Flags();
  1532. auto content = AnnotateAstNode(
  1533. ctx.RefAtoms ?
  1534. TAstNode::NewLiteralAtom(ctx.Expr.GetPosition(node.Pos()), node.Content(), pool, flags) :
  1535. TAstNode::NewAtom(ctx.Expr.GetPosition(node.Pos()), node.Content(), pool, flags),
  1536. &node, annotationFlags, pool, ctx.RefAtoms);
  1537. res = TAstNode::NewList(ctx.Expr.GetPosition(node.Pos()), pool, quote, content);
  1538. break;
  1539. }
  1540. case TExprNode::List:
  1541. {
  1542. TSmallVec<TAstNode*> values;
  1543. for (const auto& child : node.Children()) {
  1544. values.push_back(BuildValueNode(*child, ctx, topLevelName, annotationFlags, pool, useBindings));
  1545. }
  1546. auto quote = AnnotateAstNode(&TAstNode::QuoteAtom, nullptr, annotationFlags, pool, ctx.RefAtoms);
  1547. auto list = AnnotateAstNode(TAstNode::NewList(
  1548. ctx.Expr.GetPosition(node.Pos()), values.data(), values.size(), pool), &node, annotationFlags, pool, ctx.RefAtoms);
  1549. res = TAstNode::NewList(ctx.Expr.GetPosition(node.Pos()), pool, quote, list);
  1550. break;
  1551. }
  1552. case TExprNode::Callable:
  1553. {
  1554. if (node.Content() == "Parameter") {
  1555. const auto& nameNode = *node.Child(0);
  1556. const auto& typeNode = *node.Child(1);
  1557. Y_UNUSED(typeNode);
  1558. res = TAstNode::NewAtom(ctx.Expr.GetPosition(node.Pos()), nameNode.Content(), pool);
  1559. auto it = ctx.Parameters.find(nameNode.Content());
  1560. if (it != ctx.Parameters.end()) {
  1561. break;
  1562. }
  1563. auto declareAtom = TAstNode::NewLiteralAtom(ctx.Expr.GetPosition(node.Pos()), TStringBuf("declare"), pool);
  1564. auto nameAtom = ctx.RefAtoms
  1565. ? TAstNode::NewLiteralAtom(ctx.Expr.GetPosition(nameNode.Pos()), nameNode.Content(), pool)
  1566. : TAstNode::NewAtom(ctx.Expr.GetPosition(nameNode.Pos()), nameNode.Content(), pool);
  1567. TSmallVec<TAstNode*> children;
  1568. children.push_back(AnnotateAstNode(declareAtom, nullptr, annotationFlags, pool, ctx.RefAtoms));
  1569. children.push_back(AnnotateAstNode(nameAtom, nullptr, annotationFlags, pool, ctx.RefAtoms));
  1570. children.push_back(BuildValueNode(typeNode, ctx, topLevelName, annotationFlags, pool, false));
  1571. auto declareNode = TAstNode::NewList(ctx.Expr.GetPosition(node.Pos()), children.data(), children.size(), pool);
  1572. declareNode = AnnotateAstNode(declareNode, &node, annotationFlags, pool, ctx.RefAtoms);
  1573. ctx.Parameters.insert(std::make_pair(nameNode.Content(),
  1574. std::make_pair(&typeNode, declareNode)));
  1575. break;
  1576. }
  1577. TSmallVec<TAstNode*> children;
  1578. children.push_back(AnnotateAstNode(
  1579. ctx.RefAtoms ?
  1580. TAstNode::NewLiteralAtom(ctx.Expr.GetPosition(node.Pos()), node.Content(), pool) :
  1581. TAstNode::NewAtom(ctx.Expr.GetPosition(node.Pos()), node.Content(), pool),
  1582. nullptr, annotationFlags, pool, ctx.RefAtoms));
  1583. for (const auto& child : node.Children()) {
  1584. children.push_back(BuildValueNode(*child, ctx, topLevelName, annotationFlags, pool, useBindings));
  1585. }
  1586. res = TAstNode::NewList(ctx.Expr.GetPosition(node.Pos()), children.data(), children.size(), pool);
  1587. break;
  1588. }
  1589. case TExprNode::Lambda:
  1590. {
  1591. const auto prevFrame = ctx.CurrentFrame;
  1592. const auto it = ctx.LambdaFrames.find(&node);
  1593. YQL_ENSURE(it != ctx.LambdaFrames.end());
  1594. ctx.CurrentFrame = &ctx.Frames[it->second];
  1595. YQL_ENSURE(node.ChildrenSize() > 0U);
  1596. const auto& args = node.Head();
  1597. TSmallVec<TAstNode*> argsChildren;
  1598. for (const auto& arg : args.Children()) {
  1599. const auto& name = ctx.FindBinding(arg.Get());
  1600. const auto atom = TAstNode::NewAtom(ctx.Expr.GetPosition(node.Pos()), name, pool);
  1601. argsChildren.emplace_back(AnnotateAstNode(atom, arg.Get(), annotationFlags, pool, ctx.RefAtoms));
  1602. }
  1603. auto argsNode = TAstNode::NewList(ctx.Expr.GetPosition(args.Pos()), argsChildren.data(), argsChildren.size(), pool);
  1604. auto argsContainer = TAstNode::NewList(ctx.Expr.GetPosition(args.Pos()), pool,
  1605. AnnotateAstNode(&TAstNode::QuoteAtom, nullptr, annotationFlags, pool, ctx.RefAtoms),
  1606. AnnotateAstNode(argsNode, nullptr, annotationFlags, pool, ctx.RefAtoms));
  1607. const bool block = ctx.CurrentFrame->Bindings.cend() != std::find_if(ctx.CurrentFrame->Bindings.cbegin(), ctx.CurrentFrame->Bindings.cend(),
  1608. [](const auto& bind) { return bind.first->Type() != TExprNode::Argument; }
  1609. );
  1610. if (block) {
  1611. TSmallVec<const TExprNode*> body(node.ChildrenSize() - 1U);
  1612. for (ui32 i = 0U; i < body.size(); ++i)
  1613. body[i] = node.Child(i + 1U);
  1614. const auto blockNode = TAstNode::NewLiteralAtom(ctx.Expr.GetPosition(node.Pos()), TStringBuf("block"), pool);
  1615. const auto quotedListNode = TAstNode::NewList(ctx.Expr.GetPosition(node.Pos()), pool,
  1616. AnnotateAstNode(&TAstNode::QuoteAtom, nullptr, annotationFlags, pool, ctx.RefAtoms),
  1617. ConvertFunction(node.Pos(), body, ctx, annotationFlags, pool));
  1618. const auto blockBody = TAstNode::NewList(ctx.Expr.GetPosition(node.Pos()), pool,
  1619. AnnotateAstNode(blockNode, nullptr, annotationFlags, pool, ctx.RefAtoms),
  1620. AnnotateAstNode(quotedListNode, nullptr, annotationFlags, pool, ctx.RefAtoms));
  1621. res = AnnotateAstNode(blockBody, nullptr, annotationFlags, pool, ctx.RefAtoms);
  1622. ctx.CurrentFrame = prevFrame;
  1623. res = TAstNode::NewList(ctx.Expr.GetPosition(node.Pos()), pool,
  1624. AnnotateAstNode(TAstNode::NewLiteralAtom(
  1625. ctx.Expr.GetPosition(node.Pos()), TStringBuf("lambda"), pool), nullptr, annotationFlags, pool, ctx.RefAtoms),
  1626. AnnotateAstNode(argsContainer, &args, annotationFlags, pool, ctx.RefAtoms),
  1627. res);
  1628. } else {
  1629. TSmallVec<TAstNode*> children(node.ChildrenSize() + 1U);
  1630. for (ui32 i = 1U; i < node.ChildrenSize(); ++i) {
  1631. children[i + 1U] = BuildValueNode(*node.Child(i), ctx, topLevelName, annotationFlags, pool, useBindings);
  1632. }
  1633. ctx.CurrentFrame = prevFrame;
  1634. children[0] = AnnotateAstNode(TAstNode::NewLiteralAtom(
  1635. ctx.Expr.GetPosition(node.Pos()), TStringBuf("lambda"), pool), nullptr, annotationFlags, pool, ctx.RefAtoms);
  1636. children[1] = AnnotateAstNode(argsContainer, &args, annotationFlags, pool, ctx.RefAtoms);
  1637. res = TAstNode::NewList(ctx.Expr.GetPosition(node.Pos()), children.data(), children.size(), pool);
  1638. }
  1639. break;
  1640. }
  1641. case TExprNode::World:
  1642. res = TAstNode::NewLiteralAtom(ctx.Expr.GetPosition(node.Pos()), TStringBuf("world"), pool);
  1643. break;
  1644. case TExprNode::Argument: {
  1645. YQL_ENSURE(ctx.AllowFreeArgs, "Free arguments are not allowed");
  1646. auto iter = ctx.FreeArgs.emplace(&node, ctx.FreeArgs.size());
  1647. res = TAstNode::NewLiteralAtom(ctx.Expr.GetPosition(node.Pos()), ctx.Expr.AppendString("_FreeArg" + ToString(iter.first->second)), pool);
  1648. break;
  1649. }
  1650. default:
  1651. YQL_ENSURE(false, "Unknown type: " << static_cast<ui32>(node.Type()));
  1652. }
  1653. }
  1654. return AnnotateAstNode(res, &node, annotationFlags, pool, ctx.RefAtoms);
  1655. }
  1656. TAstNode* ConvertFunction(TPositionHandle position, const TRoots& roots, TVisitNodeContext& ctx, ui32 annotationFlags, TMemoryPool& pool) {
  1657. YQL_ENSURE(!roots.empty(), "Missed roots.");
  1658. TSmallVec<TAstNode*> children;
  1659. for (const auto& node : ctx.CurrentFrame->TopoSortedNodes) {
  1660. const auto& name = ctx.FindBinding(node);
  1661. if (name.empty() || node->Type() == TExprNode::Arguments || node->Type() == TExprNode::Argument) {
  1662. continue;
  1663. }
  1664. const auto letAtom = TAstNode::NewLiteralAtom(ctx.Expr.GetPosition(node->Pos()), TStringBuf("let"), pool);
  1665. const auto nameAtom = TAstNode::NewAtom(ctx.Expr.GetPosition(node->Pos()), name, pool);
  1666. const auto valueNode = BuildValueNode(*node, ctx, name, annotationFlags, pool, true);
  1667. const auto letNode = TAstNode::NewList(ctx.Expr.GetPosition(node->Pos()), pool,
  1668. AnnotateAstNode(letAtom, nullptr, annotationFlags, pool, ctx.RefAtoms),
  1669. AnnotateAstNode(nameAtom, nullptr, annotationFlags, pool, ctx.RefAtoms),
  1670. valueNode);
  1671. children.push_back(AnnotateAstNode(letNode, nullptr, annotationFlags, pool, ctx.RefAtoms));
  1672. }
  1673. const auto returnAtom = TAstNode::NewLiteralAtom(ctx.Expr.GetPosition(position), TStringBuf("return"), pool);
  1674. TSmallVec<TAstNode*> returnChildren;
  1675. returnChildren.reserve(roots.size() + 1U);
  1676. returnChildren.emplace_back(AnnotateAstNode(returnAtom, nullptr, annotationFlags, pool, ctx.RefAtoms));
  1677. for (const auto root : roots) {
  1678. returnChildren.emplace_back(BuildValueNode(*root, ctx, TString(), annotationFlags, pool, true));
  1679. }
  1680. const auto returnList = TAstNode::NewList(ctx.Expr.GetPosition(position), returnChildren.data(), returnChildren.size(), pool);
  1681. children.emplace_back(AnnotateAstNode(returnList, 1U == roots.size() ? roots.front() : nullptr, annotationFlags, pool, ctx.RefAtoms));
  1682. if (!ctx.CurrentFrame->Index && !ctx.Parameters.empty()) {
  1683. TSmallVec<TAstNode*> parameterNodes;
  1684. parameterNodes.reserve(ctx.Parameters.size());
  1685. for (auto& pair : ctx.Parameters) {
  1686. parameterNodes.push_back(pair.second.second);
  1687. }
  1688. children.insert(children.begin(), parameterNodes.begin(), parameterNodes.end());
  1689. }
  1690. const auto res = TAstNode::NewList(ctx.Expr.GetPosition(position), children.data(), children.size(), pool);
  1691. return AnnotateAstNode(res, nullptr, annotationFlags, pool, ctx.RefAtoms);
  1692. }
  1693. bool InlineNode(const TExprNode& node, size_t references, size_t neighbors, const TConvertToAstSettings& settings) {
  1694. if (settings.NoInlineFunc) {
  1695. if (settings.NoInlineFunc(node)) {
  1696. return false;
  1697. }
  1698. }
  1699. switch (node.Type()) {
  1700. case TExprNode::Argument:
  1701. return false;
  1702. case TExprNode::Atom:
  1703. if (const auto flags = node.Flags()) {
  1704. if ((TNodeFlags::BinaryContent | TNodeFlags::MultilineContent) & flags)
  1705. return false;
  1706. else {
  1707. if (TNodeFlags::ArbitraryContent & flags)
  1708. return node.Content().length() <= (references == 1U ? 0x40U : 0x10U);
  1709. else
  1710. return true;
  1711. }
  1712. } else
  1713. return true;
  1714. default:
  1715. if (neighbors < 2U)
  1716. return true;
  1717. if (const auto children = node.ChildrenSize())
  1718. return references == 1U && children < 3U;
  1719. else
  1720. return true;
  1721. }
  1722. }
  1723. typedef std::pair<const TExprNode*, const TExprNode*> TPairOfNodePotinters;
  1724. typedef std::unordered_set<TPairOfNodePotinters, THash<TPairOfNodePotinters>> TNodesPairSet;
  1725. typedef TNodeMap<std::pair<ui32, ui32>> TArgumentsMap;
  1726. bool CompareExpressions(const TExprNode*& one, const TExprNode*& two, TArgumentsMap& argumentsMap, ui32 level, TNodesPairSet& visited) {
  1727. const auto ins = visited.emplace(one, two);
  1728. if (!ins.second) {
  1729. return true;
  1730. }
  1731. if (one->Type() != two->Type())
  1732. return false;
  1733. if (one->ChildrenSize() != two->ChildrenSize())
  1734. return false;
  1735. switch (two->Type()) {
  1736. case TExprNode::Arguments: {
  1737. ui32 i1 = 0U, i2 = 0U;
  1738. one->ForEachChild([&](const TExprNode& arg){ argumentsMap.emplace(&arg, std::make_pair(level, ++i1)); });
  1739. two->ForEachChild([&](const TExprNode& arg){ argumentsMap.emplace(&arg, std::make_pair(level, ++i2)); });
  1740. return true;
  1741. }
  1742. case TExprNode::Argument:
  1743. if (const auto oneArg = argumentsMap.find(one), twoArg = argumentsMap.find(two); oneArg == twoArg)
  1744. return argumentsMap.cend() != oneArg || one == two;
  1745. else if (argumentsMap.cend() != oneArg && argumentsMap.cend() != twoArg) {
  1746. return oneArg->second == twoArg->second;
  1747. }
  1748. return false;
  1749. case TExprNode::Atom:
  1750. if (one->GetFlagsToCompare() != two->GetFlagsToCompare())
  1751. return false;
  1752. [[fallthrough]]; // AUTOGENERATED_FALLTHROUGH_FIXME
  1753. case TExprNode::Callable:
  1754. if (one->Content() != two->Content())
  1755. return false;
  1756. [[fallthrough]]; // AUTOGENERATED_FALLTHROUGH_FIXME
  1757. default:
  1758. break;
  1759. case TExprNode::Lambda:
  1760. ++level;
  1761. }
  1762. if (const auto childs = one->ChildrenSize()) {
  1763. const auto& l = one->Children();
  1764. const auto& r = two->Children();
  1765. for (ui32 i = 0U; i < childs; ++i) {
  1766. if (!CompareExpressions(one = l[i].Get(), two = r[i].Get(), argumentsMap, level, visited)) {
  1767. return false;
  1768. }
  1769. }
  1770. }
  1771. return true;
  1772. }
  1773. using TNodeSetPtr = std::shared_ptr<TNodeSet>;
  1774. TNodeSetPtr ExcludeFromUnresolved(const TExprNode& args, const TNodeSetPtr& unresolved) {
  1775. if (!unresolved || unresolved->empty() || args.ChildrenSize() == 0) {
  1776. return unresolved;
  1777. }
  1778. size_t excluded = 0;
  1779. auto newUnresolved = std::make_shared<TNodeSet>(*unresolved);
  1780. for (auto& toExclude : args.Children()) {
  1781. excluded += newUnresolved->erase(toExclude.Get());
  1782. }
  1783. return excluded ? newUnresolved : unresolved;
  1784. }
  1785. TNodeSetPtr MergeUnresolvedArgs(const TNodeSetPtr& one, const TNodeSetPtr& two) {
  1786. if (!one || one->empty()) {
  1787. return two;
  1788. }
  1789. if (!two || two->empty()) {
  1790. return one;
  1791. }
  1792. const TNodeSetPtr& bigger = (one->size() > two->size()) ? one : two;
  1793. const TNodeSetPtr& smaller = (one->size() > two->size()) ? two : one;
  1794. TNodeSetPtr result = std::make_shared<TNodeSet>(*bigger);
  1795. bool inserted = false;
  1796. for (auto& item : *smaller) {
  1797. if (result->insert(item).second) {
  1798. inserted = true;
  1799. }
  1800. }
  1801. return inserted ? result : bigger;
  1802. }
  1803. TNodeSetPtr CollectUnresolvedArgs(const TExprNode& root, TNodeMap<TNodeSetPtr>& unresolvedArgs, TNodeSet& allArgs) {
  1804. auto it = unresolvedArgs.find(&root);
  1805. if (it != unresolvedArgs.end()) {
  1806. return it->second;
  1807. }
  1808. TNodeSetPtr result;
  1809. switch (root.Type()) {
  1810. case TExprNode::Argument:
  1811. result = std::make_shared<TNodeSet>(TNodeSet{&root});
  1812. break;
  1813. case TExprNode::Lambda:
  1814. {
  1815. if (!root.ChildrenSize()) {
  1816. ythrow yexception() << "lambda #" << root.UniqueId() << " has " << root.ChildrenSize() << " children";
  1817. }
  1818. const auto& arguments = root.Head();
  1819. if (arguments.Type() != TExprNode::Arguments) {
  1820. ythrow yexception() << "unexpected type of arguments node in lambda #" << root.UniqueId();
  1821. }
  1822. arguments.ForEachChild([&](const TExprNode& arg) {
  1823. if (arg.Type() != TExprNode::Argument) {
  1824. ythrow yexception() << "expecting argument, #[" << arg.UniqueId() << "]";
  1825. }
  1826. if (!allArgs.insert(&arg).second) {
  1827. ythrow yexception() << "argument is duplicated, #[" << arg.UniqueId() << "]";
  1828. }
  1829. });
  1830. for (ui32 i = 1U; i < root.ChildrenSize(); ++i) {
  1831. const auto bodyUnresolvedArgs = CollectUnresolvedArgs(*root.Child(i), unresolvedArgs, allArgs);
  1832. result = ExcludeFromUnresolved(arguments, bodyUnresolvedArgs);
  1833. }
  1834. break;
  1835. }
  1836. case TExprNode::Callable:
  1837. case TExprNode::List:
  1838. {
  1839. root.ForEachChild([&](const TExprNode& child) {
  1840. result = MergeUnresolvedArgs(result, CollectUnresolvedArgs(child, unresolvedArgs, allArgs));
  1841. });
  1842. break;
  1843. }
  1844. case TExprNode::Atom:
  1845. case TExprNode::World:
  1846. break;
  1847. case TExprNode::Arguments:
  1848. ythrow yexception() << "unexpected free arguments node #[" << root.UniqueId() << "]";
  1849. break;
  1850. }
  1851. unresolvedArgs[&root] = result;
  1852. return result;
  1853. }
  1854. typedef TNodeMap<long> TRefCountsMap;
  1855. void CalculateReferences(const TExprNode& node, TRefCountsMap& refCounts) {
  1856. if (!refCounts[&node]++)
  1857. for (const auto& child : node.Children())
  1858. CalculateReferences(*child, refCounts);
  1859. }
  1860. void CheckReferences(const TExprNode& node, TRefCountsMap& refCounts, TNodeSet& visited) {
  1861. if (visited.emplace(&node).second) {
  1862. for (const auto& child : node.Children()) {
  1863. YQL_ENSURE(child->UseCount() == refCounts[child.Get()]);
  1864. CheckReferences(*child, refCounts, visited);
  1865. }
  1866. }
  1867. }
  1868. bool GatherParentsImpl(const TExprNode& node, TParentsMap& parentsMap, TNodeSet& visited) {
  1869. if (node.Type() == TExprNode::Arguments || node.Type() == TExprNode::Atom || node.Type() == TExprNode::World) {
  1870. return false;
  1871. }
  1872. if (!visited.emplace(&node).second) {
  1873. return true;
  1874. }
  1875. node.ForEachChild([&](const TExprNode& child) {
  1876. if (GatherParentsImpl(child, parentsMap, visited)) {
  1877. parentsMap[&child].emplace(&node);
  1878. }
  1879. });
  1880. return true;
  1881. }
  1882. } // namespace
  1883. bool CompileExpr(TAstNode& astRoot, TExprNode::TPtr& exprRoot, TExprContext& ctx,
  1884. IModuleResolver* resolver, IUrlListerManager* urlListerManager,
  1885. bool hasAnnotations, ui32 typeAnnotationIndex, ui16 syntaxVersion) {
  1886. exprRoot.Reset();
  1887. TAstNode* cleanRoot = nullptr;
  1888. TAnnotationNodeMap annotations;
  1889. const TAnnotationNodeMap* currentAnnotations = nullptr;
  1890. TAstParseResult cleanupRes;
  1891. if (!hasAnnotations) {
  1892. typeAnnotationIndex = Max<ui32>();
  1893. cleanRoot = &astRoot;
  1894. currentAnnotations = nullptr;
  1895. } else if (typeAnnotationIndex != Max<ui32>()) {
  1896. cleanupRes.Pool = std::make_unique<TMemoryPool>(4096);
  1897. cleanRoot = ExtractAnnotations(astRoot, annotations, *cleanupRes.Pool);
  1898. cleanupRes.Root = cleanRoot;
  1899. currentAnnotations = &annotations;
  1900. } else {
  1901. cleanupRes.Pool = std::make_unique<TMemoryPool>(4096);
  1902. cleanRoot = RemoveAnnotations(astRoot, *cleanupRes.Pool);
  1903. cleanupRes.Root = cleanRoot;
  1904. currentAnnotations = nullptr;
  1905. }
  1906. if (!cleanRoot) {
  1907. return false;
  1908. }
  1909. TContext compileCtx(ctx);
  1910. compileCtx.SyntaxVersion = syntaxVersion;
  1911. compileCtx.Annotations = currentAnnotations;
  1912. compileCtx.TypeAnnotationIndex = typeAnnotationIndex;
  1913. compileCtx.ModuleResolver = resolver;
  1914. compileCtx.UrlListerManager = urlListerManager;
  1915. compileCtx.PushFrame();
  1916. auto world = compileCtx.Expr.NewWorld(astRoot.GetPosition());
  1917. if (typeAnnotationIndex != Max<ui32>()) {
  1918. world->SetTypeAnn(compileCtx.Expr.MakeType<TWorldExprType>());
  1919. }
  1920. compileCtx.Frames.back().Bindings[TStringBuf("world")] = {std::move(world)};
  1921. auto ret = CompileFunction(*cleanRoot, compileCtx, true);
  1922. if (1U != ret.size())
  1923. return false;
  1924. exprRoot = std::move(ret.front());
  1925. compileCtx.PopFrame();
  1926. return bool(exprRoot);
  1927. }
  1928. bool CompileExpr(TAstNode& astRoot, TExprNode::TPtr& exprRoot, TExprContext& ctx,
  1929. IModuleResolver* resolver, IUrlListerManager* urlListerManager,
  1930. ui32 annotationFlags, ui16 syntaxVersion)
  1931. {
  1932. bool hasAnnotations = annotationFlags != TExprAnnotationFlags::None;
  1933. ui32 typeAnnotationIndex = Max<ui32>();
  1934. if (annotationFlags & TExprAnnotationFlags::Types) {
  1935. bool hasPostions = annotationFlags & TExprAnnotationFlags::Position;
  1936. typeAnnotationIndex = hasPostions ? 1 : 0;
  1937. }
  1938. return CompileExpr(astRoot, exprRoot, ctx, resolver, urlListerManager, hasAnnotations, typeAnnotationIndex, syntaxVersion);
  1939. }
  1940. bool CompileExpr(TAstNode& astRoot, TLibraryCohesion& library, TExprContext& ctx, ui16 syntaxVersion) {
  1941. const TAstNode* cleanRoot = &astRoot;
  1942. TContext compileCtx(ctx);
  1943. compileCtx.Annotations = nullptr;
  1944. compileCtx.TypeAnnotationIndex = Max<ui32>();
  1945. compileCtx.SyntaxVersion = syntaxVersion;
  1946. const bool ok = CompileLibrary(*cleanRoot, compileCtx);
  1947. library = compileCtx.Cohesion;
  1948. return ok;
  1949. }
  1950. const TTypeAnnotationNode* CompileTypeAnnotation(const TAstNode& node, TExprContext& ctx) {
  1951. TContext compileCtx(ctx);
  1952. return compileCtx.CompileTypeAnnotationNode(node);
  1953. }
  1954. template<class Set>
  1955. bool IsDependedImpl(const TExprNode& node, const Set& dependences, TNodeSet& visited) {
  1956. if (!visited.emplace(&node).second)
  1957. return false;
  1958. if (dependences.cend() != dependences.find(&node))
  1959. return true;
  1960. for (const auto& child : node.Children()) {
  1961. if (IsDependedImpl(*child, dependences, visited))
  1962. return true;
  1963. }
  1964. return false;
  1965. }
  1966. namespace {
  1967. enum EChangeState : ui8 {
  1968. Unknown = 0,
  1969. Changed = 1,
  1970. Unchanged = 2
  1971. };
  1972. ui64 CalcBloom(const ui64 id) {
  1973. return 1ULL |
  1974. (2ULL << (std::hash<ui64>()(id) % 63ULL)) |
  1975. (2ULL << (IntHash<ui64>(id) % 63ULL)) |
  1976. (2ULL << (FnvHash<ui64>(&id, sizeof(id)) % 63ULL)) |
  1977. (2ULL << (MurmurHash<ui64>(&id, sizeof(id)) % 63ULL)) |
  1978. (2ULL << (CityHash64(reinterpret_cast<const char*>(&id), sizeof(id)) % 63ULL));
  1979. }
  1980. inline bool InBloom(const ui64 set, const ui64 bloom) {
  1981. return (bloom >> 1) == ((bloom & set) >> 1);
  1982. }
  1983. EChangeState GetChanges(TExprNode* start, const TNodeOnNodeOwnedMap& replaces, const TNodeMap<TNodeOnNodeOwnedMap>& localReplaces,
  1984. TNodeMap<EChangeState>& changes, TNodeMap<bool>& updatedLambdas);
  1985. EChangeState DoGetChanges(TExprNode* start, const TNodeOnNodeOwnedMap& replaces, const TNodeMap<TNodeOnNodeOwnedMap>& localReplaces,
  1986. TNodeMap<EChangeState>& changes, TNodeMap<bool>& updatedLambdas) {
  1987. if (start->GetBloom() & 1ULL) {
  1988. bool maybe = false;
  1989. for (const auto& repl : replaces) {
  1990. if (repl.second && !repl.first->Dead()) {
  1991. if (TExprNode::Argument != repl.first->Type()) {
  1992. maybe = true;
  1993. break;
  1994. }
  1995. if (!repl.first->GetBloom())
  1996. const_cast<TExprNode*>(repl.first)->SetBloom(CalcBloom(repl.first->UniqueId()));
  1997. if (InBloom(start->GetBloom(), repl.first->GetBloom())) {
  1998. maybe = true;
  1999. break;
  2000. }
  2001. }
  2002. }
  2003. if (!maybe) {
  2004. return EChangeState::Unchanged;
  2005. }
  2006. }
  2007. start->SetBloom(1ULL);
  2008. ui32 combinedState = EChangeState::Unchanged;
  2009. bool incompleteBloom = false;
  2010. start->ForEachChild([&](TExprNode& child) {
  2011. combinedState |= GetChanges(&child, replaces, localReplaces, changes, updatedLambdas);
  2012. start->SetBloom(start->GetBloom() | child.GetBloom());
  2013. incompleteBloom = incompleteBloom || (child.Type() != TExprNode::Arguments && !child.GetBloom());
  2014. });
  2015. if (incompleteBloom) {
  2016. start->SetBloom(0ULL);
  2017. }
  2018. return (EChangeState)combinedState;
  2019. }
  2020. EChangeState GetChanges(TExprNode* start, const TNodeOnNodeOwnedMap& replaces, const TNodeMap<TNodeOnNodeOwnedMap>& localReplaces,
  2021. TNodeMap<EChangeState>& changes, TNodeMap<bool>& updatedLambdas) {
  2022. if (start->Type() == TExprNode::Arguments) {
  2023. return EChangeState::Unchanged;
  2024. }
  2025. if (!start->GetBloom() && TExprNode::Argument == start->Type()) {
  2026. start->SetBloom(CalcBloom(start->UniqueId()));
  2027. }
  2028. auto& state = changes[start];
  2029. if (state != EChangeState::Unknown) {
  2030. return state;
  2031. }
  2032. if (const auto it = replaces.find(start); it != replaces.cend()) {
  2033. return state = it->second ? EChangeState::Changed : EChangeState::Unchanged;
  2034. }
  2035. if (start->ChildrenSize() == 0) {
  2036. return state = EChangeState::Unchanged;
  2037. }
  2038. if (start->Type() == TExprNode::Lambda) {
  2039. TNodeOnNodeOwnedMap newReplaces = replaces;
  2040. start->Head().ForEachChild([&](const TExprNode& arg){ newReplaces[&arg] = {}; });
  2041. const auto locIt = localReplaces.find(start);
  2042. if (locIt != localReplaces.end()) {
  2043. for (auto& r: locIt->second) {
  2044. newReplaces[r.first] = r.second;
  2045. }
  2046. }
  2047. state = DoGetChanges(start, newReplaces, localReplaces, changes, updatedLambdas);
  2048. if ((state & EChangeState::Changed) != 0) {
  2049. updatedLambdas.emplace(start, false);
  2050. }
  2051. return state;
  2052. }
  2053. return state = DoGetChanges(start, replaces, localReplaces, changes, updatedLambdas);
  2054. }
  2055. template<bool KeepTypeAnns>
  2056. TExprNode::TPtr DoReplace(const TExprNode::TPtr& start, const TNodeOnNodeOwnedMap& replaces,
  2057. const TNodeOnNodeOwnedMap& argReplaces, const TNodeMap<TNodeOnNodeOwnedMap>& localReplaces,
  2058. TNodeMap<EChangeState>& changes, TNodeOnNodeOwnedMap& processed, TExprContext& ctx)
  2059. {
  2060. auto& target = processed[start.Get()];
  2061. if (target) {
  2062. return target;
  2063. }
  2064. TMaybe<TExprNode::TPtr> replace;
  2065. const auto it = replaces.find(start.Get());
  2066. if (it != replaces.end()) {
  2067. replace = it->second;
  2068. }
  2069. const auto argIt = argReplaces.find(start.Get());
  2070. if (argIt != argReplaces.end()) {
  2071. YQL_ENSURE(!replace.Defined());
  2072. replace = argIt->second;
  2073. }
  2074. if (replace.Defined()) {
  2075. if (*replace) {
  2076. return target = ctx.ReplaceNodes(std::move(*replace), argReplaces);
  2077. }
  2078. return target = start;
  2079. }
  2080. if (start->ChildrenSize() != 0) {
  2081. auto changeIt = changes.find(start.Get());
  2082. YQL_ENSURE(changeIt != changes.end(), "Missing change");
  2083. const bool isChanged = (changeIt->second & EChangeState::Changed) != 0;
  2084. if (isChanged) {
  2085. if (start->Type() == TExprNode::Lambda) {
  2086. TNodeOnNodeOwnedMap newArgReplaces = argReplaces;
  2087. const auto locIt = localReplaces.find(start.Get());
  2088. YQL_ENSURE(locIt != localReplaces.end(), "Missing local changes");
  2089. for (auto& r: locIt->second) {
  2090. newArgReplaces[r.first] = r.second;
  2091. }
  2092. const auto& args = start->Head();
  2093. TExprNode::TListType newArgsList;
  2094. newArgsList.reserve(args.ChildrenSize());
  2095. args.ForEachChild([&](const TExprNode& arg) {
  2096. const auto argIt = newArgReplaces.find(&arg);
  2097. YQL_ENSURE(argIt != newArgReplaces.end(), "Missing argument");
  2098. processed.emplace(&arg, argIt->second);
  2099. newArgsList.emplace_back(argIt->second);
  2100. });
  2101. auto newBody = GetLambdaBody(*start);
  2102. std::for_each(newBody.begin(), newBody.end(), [&](TExprNode::TPtr& node) {
  2103. node = DoReplace<KeepTypeAnns>(node, replaces, newArgReplaces, localReplaces,
  2104. changes, processed, ctx);
  2105. });
  2106. auto newArgs = ctx.NewArguments(start->Pos(), std::move(newArgsList));
  2107. if constexpr (KeepTypeAnns)
  2108. newArgs->SetTypeAnn(ctx.MakeType<TUnitExprType>());
  2109. target = ctx.NewLambda(start->Pos(), std::move(newArgs), std::move(newBody));
  2110. if constexpr (KeepTypeAnns)
  2111. target->SetTypeAnn(start->GetTypeAnn());
  2112. return target;
  2113. } else {
  2114. bool replaced = false;
  2115. TExprNode::TListType newChildren;
  2116. newChildren.reserve(start->ChildrenSize());
  2117. for (const auto& child : start->Children()) {
  2118. auto newChild = DoReplace<KeepTypeAnns>(child, replaces, argReplaces, localReplaces,
  2119. changes, processed, ctx);
  2120. if (newChild != child)
  2121. replaced = true;
  2122. newChildren.emplace_back(std::move(newChild));
  2123. }
  2124. if (replaced) {
  2125. target = ctx.ChangeChildren(*start, std::move(newChildren));
  2126. if constexpr (KeepTypeAnns)
  2127. target->SetTypeAnn(start->GetTypeAnn());
  2128. return target;
  2129. }
  2130. }
  2131. }
  2132. }
  2133. return target = start;
  2134. }
  2135. void EnsureNoBadReplaces(const TExprNode& start, const TNodeOnNodeOwnedMap& replaces, TNodeSet&& visited = TNodeSet()) {
  2136. if (!visited.insert(&start).second) {
  2137. return;
  2138. }
  2139. const auto it = replaces.find(&start);
  2140. if (it != replaces.end() && it->second) {
  2141. ythrow yexception() << "Bad replace for node: " << start.UniqueId() << "\n";
  2142. }
  2143. if (start.Type() == TExprNode::Lambda) {
  2144. TNodeOnNodeOwnedMap newReplaces = replaces;
  2145. start.Head().ForEachChild([&](const TExprNode& arg){ newReplaces[&arg] = {}; });
  2146. start.ForEachChild([&](const TExprNode& child){ EnsureNoBadReplaces(child, newReplaces, std::move(visited)); });
  2147. } else {
  2148. start.ForEachChild([&](const TExprNode& child){ EnsureNoBadReplaces(child, replaces, std::move(visited)); });
  2149. }
  2150. }
  2151. const bool InternalDebug = false;
  2152. template<bool KeepTypeAnns>
  2153. TExprNode::TPtr ReplaceNodesImpl(TExprNode::TPtr&& start, const TNodeOnNodeOwnedMap& replaces, TNodeOnNodeOwnedMap& processed, TExprContext& ctx) {
  2154. if (InternalDebug) {
  2155. Cerr << "Before\n" << start->Dump() << "\n";
  2156. Cerr << "Replaces\n";
  2157. ui32 rep = 0;
  2158. for (auto& x : replaces) {
  2159. if (x.second) {
  2160. Cerr << "#" << ++rep << " " << x.first->Dump() << "\n into " << x.second->Dump() << "\n";
  2161. }
  2162. }
  2163. }
  2164. TNodeMap<EChangeState> changes;
  2165. TNodeMap<bool> updatedLambdas;
  2166. TNodeMap<TNodeOnNodeOwnedMap> localReplaces;
  2167. if ((GetChanges(start.Get(), replaces, localReplaces, changes, updatedLambdas) & EChangeState::Changed) == 0) {
  2168. return std::move(start);
  2169. }
  2170. if (!updatedLambdas.empty()) {
  2171. for (;;) {
  2172. changes.clear();
  2173. for (auto& x : updatedLambdas) {
  2174. if (!x.second) {
  2175. TNodeOnNodeOwnedMap& lambdaReplaces = localReplaces[x.first];
  2176. const auto& args = x.first->Head();
  2177. args.ForEachChild([&](const TExprNode& arg) {
  2178. const auto newArg = lambdaReplaces.emplace(&arg, ctx.ShallowCopy(arg)).first->second;
  2179. if constexpr (KeepTypeAnns)
  2180. newArg->SetTypeAnn(arg.GetTypeAnn());
  2181. });
  2182. x.second = true;
  2183. }
  2184. }
  2185. auto prevSize = updatedLambdas.size();
  2186. GetChanges(start.Get(), replaces, localReplaces, changes, updatedLambdas);
  2187. if (updatedLambdas.size() == prevSize) {
  2188. break;
  2189. }
  2190. }
  2191. }
  2192. auto ret = DoReplace<KeepTypeAnns>(start, replaces, {}, localReplaces, changes, processed, ctx);
  2193. if (InternalDebug) {
  2194. Cerr << "After\n" << ret->Dump() << "\n";
  2195. EnsureNoBadReplaces(*ret, replaces);
  2196. }
  2197. return ret;
  2198. }
  2199. }
  2200. TExprNode::TPtr TExprContext::ReplaceNode(TExprNode::TPtr&& start, const TExprNode& src, TExprNode::TPtr dst) {
  2201. if (start->Type() == TExprNode::Lambda) {
  2202. const auto& args = start->Head();
  2203. auto body = GetLambdaBody(*start);
  2204. std::optional<ui32> argIndex;
  2205. for (ui32 index = 0U; index < args.ChildrenSize(); ++index) {
  2206. const auto arg = args.Child(index);
  2207. if (arg == &src) {
  2208. if (argIndex) {
  2209. ythrow yexception() << "argument is duplicated, #[" << arg->UniqueId() << "]";
  2210. }
  2211. argIndex = index;
  2212. }
  2213. }
  2214. if (argIndex) {
  2215. TExprNode::TListType newArgNodes;
  2216. newArgNodes.reserve(args.ChildrenSize());
  2217. TNodeOnNodeOwnedMap replaces(args.ChildrenSize());
  2218. for (ui32 i = 0U; i < args.ChildrenSize(); ++i) {
  2219. const auto arg = args.Child(i);
  2220. auto newArg = (i == *argIndex) ? dst : ShallowCopy(*arg);
  2221. YQL_ENSURE(replaces.emplace(arg, newArg).second);
  2222. newArgNodes.emplace_back(std::move(newArg));
  2223. }
  2224. return NewLambda(start->Pos(), NewArguments(args.Pos(), std::move(newArgNodes)), ReplaceNodes<false>(std::move(body), replaces));
  2225. }
  2226. } else if (&src == start) {
  2227. return dst;
  2228. }
  2229. return ReplaceNodes(std::move(start), {{&src, std::move(dst)}});
  2230. }
  2231. TExprNode::TPtr TExprContext::ReplaceNodes(TExprNode::TPtr&& start, const TNodeOnNodeOwnedMap& replaces) {
  2232. TNodeOnNodeOwnedMap processed;
  2233. return replaces.empty() ? std::move(start) : ReplaceNodesImpl<false>(std::move(start), replaces, processed, *this);
  2234. }
  2235. template<bool KeepTypeAnns>
  2236. TExprNode::TListType TExprContext::ReplaceNodes(TExprNode::TListType&& starts, const TNodeOnNodeOwnedMap& replaces) {
  2237. if (!replaces.empty()) {
  2238. TNodeOnNodeOwnedMap processed;
  2239. for (auto& node : starts) {
  2240. node = ReplaceNodesImpl<KeepTypeAnns>(std::move(node), replaces, processed, *this);
  2241. }
  2242. }
  2243. return std::move(starts);
  2244. }
  2245. template TExprNode::TListType TExprContext::ReplaceNodes<true>(TExprNode::TListType&& starts, const TNodeOnNodeOwnedMap& replaces);
  2246. template TExprNode::TListType TExprContext::ReplaceNodes<false>(TExprNode::TListType&& starts, const TNodeOnNodeOwnedMap& replaces);
  2247. bool IsDepended(const TExprNode& node, const TNodeSet& dependences) {
  2248. TNodeSet visited;
  2249. return !dependences.empty() && IsDependedImpl(node, dependences, visited);
  2250. }
  2251. void CheckArguments(const TExprNode& root) {
  2252. try {
  2253. TNodeMap<TNodeSetPtr> unresolvedArgsMap;
  2254. TNodeSet allArgs;
  2255. auto rootUnresolved = CollectUnresolvedArgs(root, unresolvedArgsMap, allArgs);
  2256. if (rootUnresolved && !rootUnresolved->empty()) {
  2257. TVector<ui64> ids;
  2258. for (auto& i : *rootUnresolved) {
  2259. ids.push_back(i->UniqueId());
  2260. }
  2261. ythrow yexception() << "detected unresolved arguments at top level: #[" << JoinSeq(", ", ids) << "]";
  2262. }
  2263. } catch (yexception& e) {
  2264. e << "\n" << root.Dump();
  2265. throw;
  2266. }
  2267. }
  2268. TAstParseResult ConvertToAst(const TExprNode& root, TExprContext& exprContext, const TConvertToAstSettings& settings) {
  2269. #ifdef _DEBUG
  2270. CheckArguments(root);
  2271. #endif
  2272. TVisitNodeContext ctx(exprContext);
  2273. ctx.RefAtoms = settings.RefAtoms;
  2274. ctx.AllowFreeArgs = settings.AllowFreeArgs;
  2275. ctx.NormalizeAtomFlags = settings.NormalizeAtomFlags;
  2276. ctx.Pool = std::make_unique<TMemoryPool>(4096, TMemoryPool::TExpGrow::Instance(), settings.Allocator);
  2277. ctx.Frames.push_back(TFrameContext());
  2278. ctx.CurrentFrame = &ctx.Frames.front();
  2279. VisitNode(root, 0ULL, ctx);
  2280. ui32 uniqueNum = 0;
  2281. for (auto& frame : ctx.Frames) {
  2282. ctx.CurrentFrame = &frame;
  2283. frame.TopoSortedNodes.reserve(frame.Nodes.size());
  2284. for (const auto& node : frame.Nodes) {
  2285. const auto name = ctx.FindBinding(node.second);
  2286. if (name.empty()) {
  2287. const auto& ref = ctx.References[node.second];
  2288. if (!InlineNode(*node.second, ref.References, ref.Neighbors, settings)) {
  2289. if (settings.PrintArguments && node.second->IsArgument()) {
  2290. auto buffer = TStringBuilder() << "$" << ++uniqueNum
  2291. << "{" << node.second->Content() << ":"
  2292. << node.second->UniqueId() << "}";
  2293. YQL_ENSURE(frame.Bindings.emplace(node.second, buffer).second);
  2294. } else {
  2295. char buffer[1 + 10 + 1];
  2296. snprintf(buffer, sizeof(buffer), "$%" PRIu32, ++uniqueNum);
  2297. YQL_ENSURE(frame.Bindings.emplace(node.second, buffer).second);
  2298. }
  2299. frame.TopoSortedNodes.emplace_back(node.second);
  2300. }
  2301. }
  2302. }
  2303. }
  2304. ctx.CurrentFrame = &ctx.Frames.front();
  2305. TAstParseResult result;
  2306. result.Root = ConvertFunction(exprContext.AppendPosition(TPosition(1, 1)), {&root}, ctx, settings.AnnotationFlags, *ctx.Pool);
  2307. result.Pool = std::move(ctx.Pool);
  2308. return result;
  2309. }
  2310. TAstParseResult ConvertToAst(const TExprNode& root, TExprContext& exprContext, ui32 annotationFlags, bool refAtoms) {
  2311. TConvertToAstSettings settings;
  2312. settings.AnnotationFlags = annotationFlags;
  2313. settings.RefAtoms = refAtoms;
  2314. return ConvertToAst(root, exprContext, settings);
  2315. }
  2316. TString TExprNode::Dump() const {
  2317. TNodeSet visited;
  2318. TStringStream out;
  2319. DumpNode(*this, out, 0, visited);
  2320. return out.Str();
  2321. }
  2322. TPosition TExprNode::Pos(const TExprContext& ctx) const {
  2323. return ctx.GetPosition(Pos());
  2324. }
  2325. TExprNode::TPtr TExprContext::RenameNode(const TExprNode& node, const TStringBuf& name) {
  2326. const auto newNode = node.ChangeContent(AllocateNextUniqueId(), AppendString(name));
  2327. ExprNodes.emplace_back(newNode.Get());
  2328. return newNode;
  2329. }
  2330. TExprNode::TPtr TExprContext::ShallowCopy(const TExprNode& node) {
  2331. YQL_ENSURE(node.Type() != TExprNode::Lambda);
  2332. const auto newNode = node.Clone(AllocateNextUniqueId());
  2333. ExprNodes.emplace_back(newNode.Get());
  2334. return newNode;
  2335. }
  2336. TExprNode::TPtr TExprContext::ShallowCopyWithPosition(const TExprNode& node, TPositionHandle pos) {
  2337. YQL_ENSURE(node.Type() != TExprNode::Lambda);
  2338. const auto newNode = node.CloneWithPosition(AllocateNextUniqueId(), pos);
  2339. ExprNodes.emplace_back(newNode.Get());
  2340. return newNode;
  2341. }
  2342. TExprNode::TPtr TExprContext::ChangeChildren(const TExprNode& node, TExprNode::TListType&& children) {
  2343. const auto newNode = node.ChangeChildren(AllocateNextUniqueId(), std::move(children));
  2344. ExprNodes.emplace_back(newNode.Get());
  2345. return newNode;
  2346. }
  2347. TExprNode::TPtr TExprContext::ChangeChild(const TExprNode& node, ui32 index, TExprNode::TPtr&& child) {
  2348. const auto newNode = node.ChangeChild(AllocateNextUniqueId(), index, std::move(child));
  2349. ExprNodes.emplace_back(newNode.Get());
  2350. return newNode;
  2351. }
  2352. TExprNode::TPtr TExprContext::ExactChangeChildren(const TExprNode& node, TExprNode::TListType&& children) {
  2353. const auto newNode = node.ChangeChildren(AllocateNextUniqueId(), std::move(children));
  2354. newNode->SetTypeAnn(node.GetTypeAnn());
  2355. newNode->CopyConstraints(node);
  2356. newNode->SetState(node.GetState());
  2357. newNode->Result = node.Result;
  2358. ExprNodes.emplace_back(newNode.Get());
  2359. return newNode;
  2360. }
  2361. TExprNode::TPtr TExprContext::ExactShallowCopy(const TExprNode& node) {
  2362. YQL_ENSURE(node.Type() != TExprNode::Lambda);
  2363. const auto newNode = node.Clone(AllocateNextUniqueId());
  2364. newNode->SetTypeAnn(node.GetTypeAnn());
  2365. newNode->CopyConstraints(node);
  2366. newNode->SetState(node.GetState());
  2367. newNode->Result = node.Result;
  2368. ExprNodes.emplace_back(newNode.Get());
  2369. return newNode;
  2370. }
  2371. TExprNode::TListType GetLambdaBody(const TExprNode& node) {
  2372. switch (node.ChildrenSize()) {
  2373. case 1U: return {};
  2374. case 2U: return {node.TailPtr()};
  2375. default: break;
  2376. }
  2377. auto body = node.ChildrenList();
  2378. body.erase(body.cbegin());
  2379. return body;
  2380. }
  2381. TExprNode::TPtr TExprContext::DeepCopyLambda(const TExprNode& node, TExprNode::TListType&& body) {
  2382. YQL_ENSURE(node.IsLambda());
  2383. const auto& prevArgs = node.Head();
  2384. TNodeOnNodeOwnedMap replaces(prevArgs.ChildrenSize());
  2385. TExprNode::TListType newArgNodes;
  2386. newArgNodes.reserve(prevArgs.ChildrenSize());
  2387. prevArgs.ForEachChild([&](const TExprNode& arg) {
  2388. auto newArg = ShallowCopy(arg);
  2389. YQL_ENSURE(replaces.emplace(&arg, newArg).second);
  2390. newArgNodes.emplace_back(std::move(newArg));
  2391. });
  2392. auto newBody = ReplaceNodes(std::move(body), replaces);
  2393. return NewLambda(node.Pos(), NewArguments(prevArgs.Pos(), std::move(newArgNodes)), std::move(newBody));
  2394. }
  2395. TExprNode::TPtr TExprContext::DeepCopyLambda(const TExprNode& node, TExprNode::TPtr&& body) {
  2396. YQL_ENSURE(node.IsLambda());
  2397. const auto& prevArgs = node.Head();
  2398. TNodeOnNodeOwnedMap replaces(prevArgs.ChildrenSize());
  2399. TExprNode::TListType newArgNodes;
  2400. newArgNodes.reserve(prevArgs.ChildrenSize());
  2401. prevArgs.ForEachChild([&](const TExprNode& arg) {
  2402. auto newArg = ShallowCopy(arg);
  2403. YQL_ENSURE(replaces.emplace(&arg, newArg).second);
  2404. newArgNodes.emplace_back(std::move(newArg));
  2405. });
  2406. auto newBody = ReplaceNodes(body ? TExprNode::TListType{std::move(body)} : GetLambdaBody(node), replaces);
  2407. return NewLambda(node.Pos(), NewArguments(prevArgs.Pos(), std::move(newArgNodes)), std::move(newBody));
  2408. }
  2409. TExprNode::TPtr TExprContext::FuseLambdas(const TExprNode& outer, const TExprNode& inner) {
  2410. YQL_ENSURE(outer.IsLambda() && inner.IsLambda());
  2411. const auto& outerArgs = outer.Head();
  2412. const auto& innerArgs = inner.Head();
  2413. TNodeOnNodeOwnedMap innerReplaces(innerArgs.ChildrenSize());
  2414. TExprNode::TListType newArgNodes;
  2415. newArgNodes.reserve(innerArgs.ChildrenSize());
  2416. innerArgs.ForEachChild([&](const TExprNode& arg) {
  2417. auto newArg = ShallowCopy(arg);
  2418. YQL_ENSURE(innerReplaces.emplace(&arg, newArg).second);
  2419. newArgNodes.emplace_back(std::move(newArg));
  2420. });
  2421. auto body = ReplaceNodes(GetLambdaBody(inner), innerReplaces);
  2422. TExprNode::TListType newBody;
  2423. auto outerBody = GetLambdaBody(outer);
  2424. if (outerArgs.ChildrenSize() + 1U == inner.ChildrenSize()) {
  2425. auto i = 0U;
  2426. TNodeOnNodeOwnedMap outerReplaces(outerArgs.ChildrenSize());
  2427. outerArgs.ForEachChild([&](const TExprNode& arg) {
  2428. YQL_ENSURE(outerReplaces.emplace(&arg, std::move(body[i++])).second);
  2429. });
  2430. newBody = ReplaceNodes(std::move(outerBody), outerReplaces);
  2431. } else if (1U == outerArgs.ChildrenSize()) {
  2432. newBody.reserve(newBody.size() * body.size());
  2433. for (auto item : body) {
  2434. for (auto root : outerBody) {
  2435. newBody.emplace_back(ReplaceNode(TExprNode::TPtr(root), outerArgs.Head(), TExprNode::TPtr(item)));
  2436. }
  2437. }
  2438. } else {
  2439. YQL_ENSURE(outerBody.empty(), "Incompatible lambdas for fuse.");
  2440. }
  2441. return NewLambda(outer.Pos(), NewArguments(inner.Head().Pos(), std::move(newArgNodes)), std::move(newBody));
  2442. }
  2443. TExprNode::TPtr TExprContext::DeepCopy(const TExprNode& node, TExprContext& nodeCtx, TNodeOnNodeOwnedMap& deepClones,
  2444. bool internStrings, bool copyTypes, bool copyResult, TCustomDeepCopier customCopier)
  2445. {
  2446. const auto ins = deepClones.emplace(&node, nullptr);
  2447. if (ins.second) {
  2448. TExprNode::TListType children;
  2449. children.reserve(node.ChildrenSize());
  2450. if (customCopier && customCopier(node, children)) {
  2451. } else {
  2452. node.ForEachChild([&](const TExprNode& child) {
  2453. children.emplace_back(DeepCopy(child, nodeCtx, deepClones, internStrings, copyTypes, copyResult, customCopier));
  2454. });
  2455. }
  2456. ++NodeAllocationCounter;
  2457. auto newNode = TExprNode::NewNode(AppendPosition(nodeCtx.GetPosition(node.Pos())), node.Type(),
  2458. std::move(children), internStrings ? AppendString(node.Content()) : node.Content(), node.Flags(),
  2459. AllocateNextUniqueId());
  2460. if (copyTypes && node.GetTypeAnn()) {
  2461. newNode->SetTypeAnn(node.GetTypeAnn());
  2462. }
  2463. if (copyResult && node.IsCallable() && node.HasResult()) {
  2464. newNode->SetResult(nodeCtx.ShallowCopy(node.GetResult()));
  2465. }
  2466. ins.first->second = newNode;
  2467. ExprNodes.emplace_back(ins.first->second.Get());
  2468. }
  2469. return ins.first->second;
  2470. }
  2471. TExprNode::TPtr TExprContext::WrapByCallableIf(bool condition, const TStringBuf& callable, TExprNode::TPtr&& node) {
  2472. if (!condition) {
  2473. return node;
  2474. }
  2475. const auto pos = node->Pos();
  2476. return NewCallable(pos, callable, {std::move(node)});
  2477. }
  2478. TExprNode::TPtr TExprContext::SwapWithHead(const TExprNode& node) {
  2479. return ChangeChild(node.Head(), 0U, ChangeChild(node, 0U, node.Head().HeadPtr()));
  2480. }
  2481. TConstraintSet TExprContext::MakeConstraintSet(const NYT::TNode& serializedConstraints) {
  2482. const static std::unordered_map<std::string_view, std::function<const TConstraintNode*(TExprContext&, const NYT::TNode&)>> FACTORIES = {
  2483. {TSortedConstraintNode::Name(), std::mem_fn(&TExprContext::MakeConstraint<TSortedConstraintNode, const NYT::TNode&>)},
  2484. {TChoppedConstraintNode::Name(), std::mem_fn(&TExprContext::MakeConstraint<TChoppedConstraintNode, const NYT::TNode&>)},
  2485. {TUniqueConstraintNode::Name(), std::mem_fn(&TExprContext::MakeConstraint<TUniqueConstraintNode, const NYT::TNode&>)},
  2486. {TDistinctConstraintNode::Name(), std::mem_fn(&TExprContext::MakeConstraint<TDistinctConstraintNode, const NYT::TNode&>)},
  2487. {TEmptyConstraintNode::Name(), std::mem_fn(&TExprContext::MakeConstraint<TEmptyConstraintNode, const NYT::TNode&>)},
  2488. {TVarIndexConstraintNode::Name(), std::mem_fn(&TExprContext::MakeConstraint<TVarIndexConstraintNode, const NYT::TNode&>)},
  2489. {TMultiConstraintNode::Name(), std::mem_fn(&TExprContext::MakeConstraint<TMultiConstraintNode, const NYT::TNode&>)},
  2490. };
  2491. TConstraintSet res;
  2492. YQL_ENSURE(serializedConstraints.IsMap(), "Unexpected node type with serialize constraints: " << serializedConstraints.GetType());
  2493. for (const auto& [key, node]: serializedConstraints.AsMap()) {
  2494. auto it = FACTORIES.find(key);
  2495. YQL_ENSURE(it != FACTORIES.cend(), "Unsupported constraint construction: " << key);
  2496. try {
  2497. res.AddConstraint((it->second)(*this, node));
  2498. } catch (...) {
  2499. YQL_ENSURE(false, "Error while constructing constraint: " << CurrentExceptionMessage());
  2500. }
  2501. }
  2502. return res;
  2503. }
  2504. TNodeException::TNodeException()
  2505. : Pos_()
  2506. {
  2507. }
  2508. TNodeException::TNodeException(const TExprNode& node)
  2509. : Pos_(node.Pos())
  2510. {
  2511. }
  2512. TNodeException::TNodeException(const TExprNode* node)
  2513. : Pos_(node ? node->Pos() : TPositionHandle())
  2514. {
  2515. }
  2516. TNodeException::TNodeException(const TPositionHandle& pos)
  2517. : Pos_(pos)
  2518. {
  2519. }
  2520. bool ValidateName(TPosition position, TStringBuf name, TStringBuf descr, TExprContext& ctx) {
  2521. if (name.empty()) {
  2522. ctx.AddError(TIssue(position,
  2523. TStringBuilder() << "Empty " << descr << " name is not allowed"));
  2524. return false;
  2525. }
  2526. if (!IsUtf8(name)) {
  2527. ctx.AddError(TIssue(position, TStringBuilder() <<
  2528. TString(descr).to_title() << " name must be a valid utf-8 byte sequence: " << TString{name}.Quote()));
  2529. return false;
  2530. }
  2531. if (name.size() > 16_KB) {
  2532. ctx.AddError(TIssue(position, TStringBuilder() <<
  2533. TString(descr).to_title() << " name length must be less than " << 16_KB));
  2534. return false;
  2535. }
  2536. return true;
  2537. }
  2538. bool ValidateName(TPositionHandle position, TStringBuf name, TStringBuf descr, TExprContext& ctx) {
  2539. return ValidateName(ctx.GetPosition(position), name, descr, ctx);
  2540. }
  2541. bool TDataExprParamsType::Validate(TPosition position, TExprContext& ctx) const {
  2542. if (GetSlot() != EDataSlot::Decimal) {
  2543. ctx.AddError(TIssue(position, TStringBuilder() << "Only Decimal may contain parameters, but got: " << GetName()));
  2544. return false;
  2545. }
  2546. ui8 precision;
  2547. if (!TryFromString<ui8>(GetParamOne(), precision)){
  2548. ctx.AddError(TIssue(position, TStringBuilder() << "Invalid decimal precision: " << GetParamOne()));
  2549. return false;
  2550. }
  2551. if (!precision || precision > 35) {
  2552. ctx.AddError(TIssue(position, TStringBuilder() << "Invalid decimal precision: " << GetParamOne()));
  2553. return false;
  2554. }
  2555. ui8 scale;
  2556. if (!TryFromString<ui8>(GetParamTwo(), scale)){
  2557. ctx.AddError(TIssue(position, TStringBuilder() << "Invalid decimal scale: " << GetParamTwo()));
  2558. return false;
  2559. }
  2560. if (scale > precision) {
  2561. ctx.AddError(TIssue(position, TStringBuilder() << "Invalid decimal parameters: (" << GetParamOne() << "," << GetParamTwo() << ")."));
  2562. return false;
  2563. }
  2564. return true;
  2565. }
  2566. bool TDataExprParamsType::Validate(TPositionHandle position, TExprContext& ctx) const {
  2567. return Validate(ctx.GetPosition(position), ctx);
  2568. }
  2569. bool TItemExprType::Validate(TPosition position, TExprContext& ctx) const {
  2570. return ValidateName(position, Name, "member", ctx);
  2571. }
  2572. bool TItemExprType::Validate(TPositionHandle position, TExprContext& ctx) const {
  2573. return Validate(ctx.GetPosition(position), ctx);
  2574. }
  2575. TStringBuf TItemExprType::GetCleanName(bool isVirtual) const {
  2576. if (!isVirtual) {
  2577. return Name;
  2578. }
  2579. YQL_ENSURE(Name.StartsWith(YqlVirtualPrefix));
  2580. return Name.SubStr(YqlVirtualPrefix.size());
  2581. }
  2582. const TItemExprType* TItemExprType::GetCleanItem(bool isVirtual, TExprContext& ctx) const {
  2583. if (!isVirtual) {
  2584. return this;
  2585. }
  2586. YQL_ENSURE(Name.StartsWith(YqlVirtualPrefix));
  2587. return ctx.MakeType<TItemExprType>(Name.SubStr(YqlVirtualPrefix.size()), ItemType);
  2588. }
  2589. bool TMultiExprType::Validate(TPosition position, TExprContext& ctx) const {
  2590. if (Items.size() > Max<ui16>()) {
  2591. ctx.AddError(TIssue(position, TStringBuilder() << "Too many elements: " << Items.size()));
  2592. return false;
  2593. }
  2594. return true;
  2595. }
  2596. bool TMultiExprType::Validate(TPositionHandle position, TExprContext& ctx) const {
  2597. return Validate(ctx.GetPosition(position), ctx);
  2598. }
  2599. bool TTupleExprType::Validate(TPosition position, TExprContext& ctx) const {
  2600. if (Items.size() > Max<ui16>()) {
  2601. ctx.AddError(TIssue(position, TStringBuilder() << "Too many tuple elements: " << Items.size()));
  2602. return false;
  2603. }
  2604. return true;
  2605. }
  2606. bool TTupleExprType::Validate(TPositionHandle position, TExprContext& ctx) const {
  2607. return Validate(ctx.GetPosition(position), ctx);
  2608. }
  2609. bool TStructExprType::Validate(TPosition position, TExprContext& ctx) const {
  2610. if (Items.size() > Max<ui16>()) {
  2611. ctx.AddError(TIssue(position, TStringBuilder() << "Too many struct members: " << Items.size()));
  2612. return false;
  2613. }
  2614. TString lastName;
  2615. for (auto& item : Items) {
  2616. if (!item->Validate(position, ctx)) {
  2617. return false;
  2618. }
  2619. if (item->GetName() == lastName) {
  2620. ctx.AddError(TIssue(position, TStringBuilder() << "Duplicated member: " << lastName));
  2621. return false;
  2622. }
  2623. lastName = item->GetName();
  2624. }
  2625. return true;
  2626. }
  2627. bool TStructExprType::Validate(TPositionHandle position, TExprContext& ctx) const {
  2628. return Validate(ctx.GetPosition(position), ctx);
  2629. }
  2630. bool TVariantExprType::Validate(TPosition position, TExprContext& ctx) const {
  2631. if (UnderlyingType->GetKind() == ETypeAnnotationKind::Tuple) {
  2632. if (!UnderlyingType->Cast<TTupleExprType>()->GetSize()) {
  2633. ctx.AddError(TIssue(position, TStringBuilder() << "Empty tuple is not allowed as underlying type"));
  2634. return false;
  2635. }
  2636. }
  2637. else if (UnderlyingType->GetKind() == ETypeAnnotationKind::Struct) {
  2638. if (!UnderlyingType->Cast<TStructExprType>()->GetSize()) {
  2639. ctx.AddError(TIssue(position, TStringBuilder() << "Empty struct is not allowed as underlying type"));
  2640. return false;
  2641. }
  2642. }
  2643. else {
  2644. ctx.AddError(TIssue(position, TStringBuilder() << "Expected tuple or struct, but got:" << *UnderlyingType));
  2645. return false;
  2646. }
  2647. return true;
  2648. }
  2649. bool TVariantExprType::Validate(TPositionHandle position, TExprContext& ctx) const {
  2650. return Validate(ctx.GetPosition(position), ctx);
  2651. }
  2652. ui32 TVariantExprType::MakeFlags(const TTypeAnnotationNode* underlyingType) {
  2653. switch (underlyingType->GetKind()) {
  2654. case ETypeAnnotationKind::Tuple: {
  2655. const auto tupleType = underlyingType->Cast<TTupleExprType>();
  2656. auto ret = CombineFlags(tupleType->GetItems());
  2657. if (tupleType->GetSize() > 1) {
  2658. ret |= TypeHasManyValues;
  2659. }
  2660. return ret;
  2661. }
  2662. case ETypeAnnotationKind::Struct: {
  2663. const auto structType = underlyingType->Cast<TStructExprType>();
  2664. auto ret = CombineFlags(structType->GetItems());
  2665. if (structType->GetSize() > 1) {
  2666. ret |= TypeHasManyValues;
  2667. }
  2668. return ret;
  2669. }
  2670. default: break;
  2671. }
  2672. ythrow yexception() << "unexpected underlying type" << *underlyingType;
  2673. }
  2674. bool TDictExprType::Validate(TPosition position, TExprContext& ctx) const {
  2675. if (KeyType->IsHashable() && KeyType->IsEquatable()) {
  2676. return true;
  2677. }
  2678. if (KeyType->IsComparableInternal()) {
  2679. return true;
  2680. }
  2681. ctx.AddError(TIssue(position, TStringBuilder() << "Expected hashable and equatable or internally comparable dict key type, but got: " << *KeyType));
  2682. return false;
  2683. }
  2684. bool TDictExprType::Validate(TPositionHandle position, TExprContext& ctx) const {
  2685. return Validate(ctx.GetPosition(position), ctx);
  2686. }
  2687. bool TCallableExprType::Validate(TPosition position, TExprContext& ctx) const {
  2688. if (OptionalArgumentsCount > Arguments.size()) {
  2689. ctx.AddError(TIssue(position, TStringBuilder() << "Too many optional arguments: " << OptionalArgumentsCount
  2690. << ", function has only " << Arguments.size() << " arguments"));
  2691. return false;
  2692. }
  2693. for (ui32 index = Arguments.size() - OptionalArgumentsCount; index < Arguments.size(); ++index) {
  2694. auto type = Arguments[index].Type;
  2695. if (type->GetKind() != ETypeAnnotationKind::Optional) {
  2696. ctx.AddError(TIssue(position, TStringBuilder() << "Expected optional type for argument: " << (index + 1)
  2697. << " because it's an optional argument, but got: " << *type));
  2698. return false;
  2699. }
  2700. }
  2701. bool startedNames = false;
  2702. std::unordered_set<std::string_view> usedNames(Arguments.size());
  2703. for (ui32 index = 0; index < Arguments.size(); ++index) {
  2704. bool hasName = !Arguments[index].Name.empty();
  2705. if (startedNames) {
  2706. if (!hasName) {
  2707. ctx.AddError(TIssue(position, TStringBuilder() << "Unexpected positional argument at position "
  2708. << (index + 1) << " just after named arguments"));
  2709. return false;
  2710. }
  2711. } else {
  2712. startedNames = hasName;
  2713. }
  2714. if (hasName) {
  2715. if (!usedNames.insert(Arguments[index].Name).second) {
  2716. ctx.AddError(TIssue(position, TStringBuilder() << "Duplication of named argument: " << Arguments[index].Name));
  2717. return false;
  2718. }
  2719. }
  2720. }
  2721. return true;
  2722. }
  2723. bool TCallableExprType::Validate(TPositionHandle position, TExprContext& ctx) const {
  2724. return Validate(ctx.GetPosition(position), ctx);
  2725. }
  2726. bool TTaggedExprType::Validate(TPosition position, TExprContext& ctx) const {
  2727. return ValidateName(position, Tag, "tag", ctx);
  2728. }
  2729. bool TTaggedExprType::Validate(TPositionHandle position, TExprContext& ctx) const {
  2730. return Validate(ctx.GetPosition(position), ctx);
  2731. }
  2732. const TString& TPgExprType::GetName() const {
  2733. return NPg::LookupType(TypeId).Name;
  2734. }
  2735. ui32 TPgExprType::GetFlags(ui32 typeId) {
  2736. auto descPtr = &NPg::LookupType(typeId);
  2737. if (descPtr->ArrayTypeId == descPtr->TypeId) {
  2738. auto elemType = descPtr->ElementTypeId;
  2739. descPtr = &NPg::LookupType(elemType);
  2740. }
  2741. const auto& desc = *descPtr;
  2742. ui32 ret = TypeHasManyValues | TypeHasOptional;
  2743. if ((!desc.SendFuncId || !desc.ReceiveFuncId) && (!desc.OutFuncId || !desc.InFuncId)) {
  2744. ret |= TypeNonPersistable;
  2745. }
  2746. if (!desc.LessProcId || !desc.CompareProcId) {
  2747. ret |= TypeNonComparable;
  2748. }
  2749. if (!desc.EqualProcId || !desc.CompareProcId) {
  2750. if (desc.TypeId != NPg::UnknownOid) {
  2751. ret |= TypeNonEquatable;
  2752. }
  2753. }
  2754. if (!desc.HashProcId) {
  2755. ret |= TypeNonHashable;
  2756. }
  2757. static const std::unordered_set<std::string_view> PgSupportedPresort = {
  2758. "bool"sv,
  2759. "int2"sv,
  2760. "int4"sv,
  2761. "int8"sv,
  2762. "float4"sv,
  2763. "float8"sv,
  2764. "bytea"sv,
  2765. "varchar"sv,
  2766. "text"sv,
  2767. "cstring"sv
  2768. };
  2769. if (!PgSupportedPresort.contains(descPtr->Name)) {
  2770. ret |= TypeNonPresortable;
  2771. }
  2772. return ret;
  2773. }
  2774. ui64 TPgExprType::GetPgExtensionsMask(ui32 typeId) {
  2775. auto descPtr = &NPg::LookupType(typeId);
  2776. return MakePgExtensionMask(descPtr->ExtensionIndex);
  2777. }
  2778. ui64 MakePgExtensionMask(ui32 extensionIndex) {
  2779. if (!extensionIndex) {
  2780. return 0;
  2781. }
  2782. YQL_ENSURE(extensionIndex <= 64);
  2783. return 1ull << (extensionIndex - 1);
  2784. }
  2785. TExprContext::TExprContext(ui64 nextUniqueId)
  2786. : StringPool(4096)
  2787. , NextUniqueId(nextUniqueId)
  2788. , Frozen(false)
  2789. , PositionSet(
  2790. 16,
  2791. [this](TPositionHandle p) { return GetHash(p); },
  2792. [this](TPositionHandle a, TPositionHandle b) { return IsEqual(a, b); }
  2793. )
  2794. {
  2795. auto handle = AppendPosition(TPosition());
  2796. YQL_ENSURE(handle.Handle == 0);
  2797. IssueManager.SetWarningToErrorTreatMessage(
  2798. "Treat warning as error mode enabled. "
  2799. "To disable it use \"pragma warning(\"default\", <code>);\"");
  2800. IssueManager.SetIssueCountLimit(100);
  2801. }
  2802. TPositionHandle TExprContext::AppendPosition(const TPosition& pos) {
  2803. YQL_ENSURE(Positions.size() <= Max<ui32>(), "Too many positions");
  2804. TPositionHandle handle;
  2805. handle.Handle = (ui32)Positions.size();
  2806. Positions.push_back(pos);
  2807. auto inserted = PositionSet.insert(handle);
  2808. if (inserted.second) {
  2809. return handle;
  2810. }
  2811. Positions.pop_back();
  2812. return *inserted.first;
  2813. }
  2814. TPosition TExprContext::GetPosition(TPositionHandle handle) const {
  2815. YQL_ENSURE(handle.Handle < Positions.size(), "Unknown PositionHandle");
  2816. return Positions[handle.Handle];
  2817. }
  2818. TExprContext::~TExprContext() {
  2819. UnFreeze();
  2820. }
  2821. void TExprContext::Freeze() {
  2822. for (auto& node : ExprNodes) {
  2823. node->MarkFrozen();
  2824. }
  2825. Frozen = true;
  2826. }
  2827. void TExprContext::UnFreeze() {
  2828. if (Frozen) {
  2829. for (auto& node : ExprNodes) {
  2830. node->MarkFrozen(false);
  2831. }
  2832. Frozen = false;
  2833. }
  2834. }
  2835. void TExprContext::Reset() {
  2836. YQL_ENSURE(!Frozen);
  2837. IssueManager.Reset();
  2838. Step.Reset();
  2839. RepeatTransformCounter = 0;
  2840. }
  2841. bool TExprContext::IsEqual(TPositionHandle a, TPositionHandle b) const {
  2842. YQL_ENSURE(a.Handle < Positions.size());
  2843. YQL_ENSURE(b.Handle < Positions.size());
  2844. return Positions[a.Handle] == Positions[b.Handle];
  2845. }
  2846. size_t TExprContext::GetHash(TPositionHandle p) const {
  2847. YQL_ENSURE(p.Handle < Positions.size());
  2848. const TPosition& pos = Positions[p.Handle];
  2849. size_t h = ComputeHash(pos.File);
  2850. h = CombineHashes(h, NumericHash(pos.Row));
  2851. return CombineHashes(h, NumericHash(pos.Column));
  2852. }
  2853. std::string_view TExprContext::GetIndexAsString(ui32 index) {
  2854. const auto it = Indexes.find(index);
  2855. if (it != Indexes.cend()) {
  2856. return it->second;
  2857. }
  2858. const auto& newBuf = AppendString(ToString(index));
  2859. Indexes.emplace_hint(it, index, newBuf);
  2860. return newBuf;
  2861. }
  2862. template<class T, typename... Args>
  2863. const T* MakeSinglethonType(TExprContext& ctx, Args&&... args) {
  2864. auto& singleton = std::get<const T*>(ctx.SingletonTypeCache);
  2865. if (!singleton)
  2866. singleton = AddType<T>(ctx, T::MakeHash(args...), std::forward<Args>(args)...);
  2867. return singleton;
  2868. }
  2869. const TVoidExprType* TMakeTypeImpl<TVoidExprType>::Make(TExprContext& ctx) {
  2870. return MakeSinglethonType<TVoidExprType>(ctx);
  2871. }
  2872. const TNullExprType* TMakeTypeImpl<TNullExprType>::Make(TExprContext& ctx) {
  2873. return MakeSinglethonType<TNullExprType>(ctx);
  2874. }
  2875. const TEmptyListExprType* TMakeTypeImpl<TEmptyListExprType>::Make(TExprContext& ctx) {
  2876. return MakeSinglethonType<TEmptyListExprType>(ctx);
  2877. }
  2878. const TEmptyDictExprType* TMakeTypeImpl<TEmptyDictExprType>::Make(TExprContext& ctx) {
  2879. return MakeSinglethonType<TEmptyDictExprType>(ctx);
  2880. }
  2881. const TUnitExprType* TMakeTypeImpl<TUnitExprType>::Make(TExprContext& ctx) {
  2882. return MakeSinglethonType<TUnitExprType>(ctx);
  2883. }
  2884. const TWorldExprType* TMakeTypeImpl<TWorldExprType>::Make(TExprContext& ctx) {
  2885. return MakeSinglethonType<TWorldExprType>(ctx);
  2886. }
  2887. const TGenericExprType* TMakeTypeImpl<TGenericExprType>::Make(TExprContext& ctx) {
  2888. return MakeSinglethonType<TGenericExprType>(ctx);
  2889. }
  2890. const TItemExprType* TMakeTypeImpl<TItemExprType>::Make(TExprContext& ctx, const TStringBuf& name, const TTypeAnnotationNode* itemType) {
  2891. const auto hash = TItemExprType::MakeHash(name, itemType);
  2892. TItemExprType sample(hash, name, itemType);
  2893. if (const auto found = FindType(sample, ctx))
  2894. return found;
  2895. auto nameStr = ctx.AppendString(name);
  2896. return AddType<TItemExprType>(ctx, hash, nameStr, itemType);
  2897. }
  2898. const TListExprType* TMakeTypeImpl<TListExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode* itemType) {
  2899. const auto hash = TListExprType::MakeHash(itemType);
  2900. TListExprType sample(hash, itemType);
  2901. if (const auto found = FindType(sample, ctx))
  2902. return found;
  2903. return AddType<TListExprType>(ctx, hash, itemType);
  2904. }
  2905. const TOptionalExprType* TMakeTypeImpl<TOptionalExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode* itemType) {
  2906. const auto hash = TOptionalExprType::MakeHash(itemType);
  2907. TOptionalExprType sample(hash, itemType);
  2908. if (const auto found = FindType(sample, ctx))
  2909. return found;
  2910. return AddType<TOptionalExprType>(ctx, hash, itemType);
  2911. }
  2912. const TVariantExprType* TMakeTypeImpl<TVariantExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode* underlyingType) {
  2913. const auto hash = TVariantExprType::MakeHash(underlyingType);
  2914. TVariantExprType sample(hash, underlyingType);
  2915. if (const auto found = FindType(sample, ctx))
  2916. return found;
  2917. return AddType<TVariantExprType>(ctx, hash, underlyingType);
  2918. }
  2919. const TErrorExprType* TMakeTypeImpl<TErrorExprType>::Make(TExprContext& ctx, const TIssue& error) {
  2920. const auto hash = TErrorExprType::MakeHash(error);
  2921. TErrorExprType sample(hash, error);
  2922. if (const auto found = FindType(sample, ctx))
  2923. return found;
  2924. return AddType<TErrorExprType>(ctx, hash, error);
  2925. }
  2926. const TDictExprType* TMakeTypeImpl<TDictExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode* keyType,
  2927. const TTypeAnnotationNode* payloadType) {
  2928. const auto hash = TDictExprType::MakeHash(keyType, payloadType);
  2929. TDictExprType sample(hash, keyType, payloadType);
  2930. if (const auto found = FindType(sample, ctx))
  2931. return found;
  2932. return AddType<TDictExprType>(ctx, hash, keyType, payloadType);
  2933. }
  2934. const TTypeExprType* TMakeTypeImpl<TTypeExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode* baseType) {
  2935. const auto hash = TTypeExprType::MakeHash(baseType);
  2936. TTypeExprType sample(hash, baseType);
  2937. if (const auto found = FindType(sample, ctx))
  2938. return found;
  2939. return AddType<TTypeExprType>(ctx, hash, baseType);
  2940. }
  2941. const TDataExprType* TMakeTypeImpl<TDataExprType>::Make(TExprContext& ctx, EDataSlot slot) {
  2942. const auto hash = TDataExprType::MakeHash(slot);
  2943. TDataExprType sample(hash, slot);
  2944. if (const auto found = FindType(sample, ctx))
  2945. return found;
  2946. return AddType<TDataExprType>(ctx, hash, slot);
  2947. }
  2948. const TPgExprType* TMakeTypeImpl<TPgExprType>::Make(TExprContext& ctx, ui32 typeId) {
  2949. const auto hash = TPgExprType::MakeHash(typeId);
  2950. TPgExprType sample(hash, typeId);
  2951. if (const auto found = FindType(sample, ctx))
  2952. return found;
  2953. return AddType<TPgExprType>(ctx, hash, typeId);
  2954. }
  2955. const TDataExprParamsType* TMakeTypeImpl<TDataExprParamsType>::Make(TExprContext& ctx, EDataSlot slot, const TStringBuf& one, const TStringBuf& two) {
  2956. const auto hash = TDataExprParamsType::MakeHash(slot, one, two);
  2957. TDataExprParamsType sample(hash, slot, one, two);
  2958. if (const auto found = FindType(sample, ctx))
  2959. return found;
  2960. return AddType<TDataExprParamsType>(ctx, hash, slot, ctx.AppendString(one), ctx.AppendString(two));
  2961. }
  2962. const TCallableExprType* TMakeTypeImpl<TCallableExprType>::Make(
  2963. TExprContext& ctx, const TTypeAnnotationNode* returnType, const TVector<TCallableExprType::TArgumentInfo>& arguments,
  2964. size_t optionalArgumentsCount, const TStringBuf& payload) {
  2965. const auto hash = TCallableExprType::MakeHash(returnType, arguments, optionalArgumentsCount, payload);
  2966. TCallableExprType sample(hash, returnType, arguments, optionalArgumentsCount, payload);
  2967. if (const auto found = FindType(sample, ctx))
  2968. return found;
  2969. TVector<TCallableExprType::TArgumentInfo> newArgs;
  2970. newArgs.reserve(arguments.size());
  2971. for (const auto& x : arguments) {
  2972. TCallableExprType::TArgumentInfo arg;
  2973. arg.Type = x.Type;
  2974. arg.Name = ctx.AppendString(x.Name);
  2975. arg.Flags = x.Flags;
  2976. newArgs.emplace_back(arg);
  2977. }
  2978. return AddType<TCallableExprType>(ctx, hash, returnType, newArgs, optionalArgumentsCount, ctx.AppendString(payload));
  2979. }
  2980. const TResourceExprType* TMakeTypeImpl<TResourceExprType>::Make(TExprContext& ctx, const TStringBuf& tag) {
  2981. const auto hash = TResourceExprType::MakeHash(tag);
  2982. TResourceExprType sample(hash, tag);
  2983. if (const auto found = FindType(sample, ctx))
  2984. return found;
  2985. return AddType<TResourceExprType>(ctx, hash, ctx.AppendString(tag));
  2986. }
  2987. const TTaggedExprType* TMakeTypeImpl<TTaggedExprType>::Make(
  2988. TExprContext& ctx, const TTypeAnnotationNode* baseType, const TStringBuf& tag) {
  2989. const auto hash = TTaggedExprType::MakeHash(baseType, tag);
  2990. TTaggedExprType sample(hash, baseType, tag);
  2991. if (const auto found = FindType(sample, ctx))
  2992. return found;
  2993. return AddType<TTaggedExprType>(ctx, hash, baseType, ctx.AppendString(tag));
  2994. }
  2995. const TStructExprType* TMakeTypeImpl<TStructExprType>::Make(
  2996. TExprContext& ctx, const TVector<const TItemExprType*>& items) {
  2997. if (items.empty())
  2998. return MakeSinglethonType<TStructExprType>(ctx, items);
  2999. auto sortedItems = items;
  3000. Sort(sortedItems, TStructExprType::TItemLess());
  3001. const auto hash = TStructExprType::MakeHash(sortedItems);
  3002. TStructExprType sample(hash, sortedItems);
  3003. if (const auto found = FindType(sample, ctx))
  3004. return found;
  3005. return AddType<TStructExprType>(ctx, hash, sortedItems);
  3006. }
  3007. const TMultiExprType* TMakeTypeImpl<TMultiExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode::TListType& items) {
  3008. if (items.empty())
  3009. return MakeSinglethonType<TMultiExprType>(ctx, items);
  3010. const auto hash = TMultiExprType::MakeHash(items);
  3011. TMultiExprType sample(hash, items);
  3012. if (const auto found = FindType(sample, ctx))
  3013. return found;
  3014. return AddType<TMultiExprType>(ctx, hash, items);
  3015. }
  3016. const TTupleExprType* TMakeTypeImpl<TTupleExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode::TListType& items) {
  3017. if (items.empty())
  3018. return MakeSinglethonType<TTupleExprType>(ctx, items);
  3019. const auto hash = TTupleExprType::MakeHash(items);
  3020. TTupleExprType sample(hash, items);
  3021. if (const auto found = FindType(sample, ctx))
  3022. return found;
  3023. return AddType<TTupleExprType>(ctx, hash, items);
  3024. }
  3025. const TStreamExprType* TMakeTypeImpl<TStreamExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode* itemType) {
  3026. const auto hash = TStreamExprType::MakeHash(itemType);
  3027. TStreamExprType sample(hash, itemType);
  3028. if (const auto found = FindType(sample, ctx))
  3029. return found;
  3030. return AddType<TStreamExprType>(ctx, hash, itemType);
  3031. }
  3032. const TFlowExprType* TMakeTypeImpl<TFlowExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode* itemType) {
  3033. const auto hash = TFlowExprType::MakeHash(itemType);
  3034. TFlowExprType sample(hash, itemType);
  3035. if (const auto found = FindType(sample, ctx))
  3036. return found;
  3037. return AddType<TFlowExprType>(ctx, hash, itemType);
  3038. }
  3039. const TBlockExprType* TMakeTypeImpl<TBlockExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode* itemType) {
  3040. const auto hash = TBlockExprType::MakeHash(itemType);
  3041. TBlockExprType sample(hash, itemType);
  3042. if (const auto found = FindType(sample, ctx))
  3043. return found;
  3044. return AddType<TBlockExprType>(ctx, hash, itemType);
  3045. }
  3046. const TScalarExprType* TMakeTypeImpl<TScalarExprType>::Make(TExprContext& ctx, const TTypeAnnotationNode* itemType) {
  3047. const auto hash = TScalarExprType::MakeHash(itemType);
  3048. TScalarExprType sample(hash, itemType);
  3049. if (const auto found = FindType(sample, ctx))
  3050. return found;
  3051. return AddType<TScalarExprType>(ctx, hash, itemType);
  3052. }
  3053. bool CompareExprTrees(const TExprNode*& one, const TExprNode*& two) {
  3054. TArgumentsMap map;
  3055. ui32 level = 0;
  3056. TNodesPairSet visited;
  3057. return CompareExpressions(one, two, map, level, visited);
  3058. }
  3059. bool CompareExprTreeParts(const TExprNode& one, const TExprNode& two, const TNodeMap<ui32>& argsMap) {
  3060. TArgumentsMap map;
  3061. ui32 level = 0;
  3062. TNodesPairSet visited;
  3063. map.reserve(argsMap.size());
  3064. std::for_each(argsMap.cbegin(), argsMap.cend(), [&](const TNodeMap<ui32>::value_type& v){ map.emplace(v.first, std::make_pair(0U, v.second)); });
  3065. auto l = &one, r = &two;
  3066. return CompareExpressions(l, r, map, level, visited);
  3067. }
  3068. class TCacheKeyBuilder {
  3069. public:
  3070. TString Process(const TExprNode& root) {
  3071. SHA256_Init(&Sha);
  3072. unsigned char hash[SHA256_DIGEST_LENGTH];
  3073. Visit(root);
  3074. SHA256_Final(hash, &Sha);
  3075. return TString((const char*)hash, sizeof(hash));
  3076. }
  3077. private:
  3078. void Visit(const TExprNode& node) {
  3079. auto [it, inserted] = Visited.emplace(&node, Visited.size());
  3080. SHA256_Update(&Sha, &it->second, sizeof(it->second));
  3081. if (!inserted) {
  3082. return;
  3083. }
  3084. ui32 type = node.Type();
  3085. SHA256_Update(&Sha, &type, sizeof(type));
  3086. if (node.Type() == TExprNode::EType::Atom || node.Type() == TExprNode::EType::Callable) {
  3087. ui32 textLen = node.Content().size();
  3088. SHA256_Update(&Sha, &textLen, sizeof(textLen));
  3089. SHA256_Update(&Sha, node.Content().data(), textLen);
  3090. }
  3091. if (node.Type() == TExprNode::EType::Atom || node.Type() == TExprNode::EType::Argument || node.Type() == TExprNode::EType::World) {
  3092. return;
  3093. }
  3094. ui32 len = node.ChildrenSize();
  3095. SHA256_Update(&Sha, &len, sizeof(len));
  3096. for (const auto& child : node.Children()) {
  3097. Visit(*child);
  3098. }
  3099. }
  3100. private:
  3101. SHA256_CTX Sha;
  3102. TNodeMap<ui64> Visited;
  3103. };
  3104. TString MakeCacheKey(const TExprNode& root) {
  3105. TCacheKeyBuilder builder;
  3106. return builder.Process(root);
  3107. }
  3108. void GatherParents(const TExprNode& node, TParentsMap& parentsMap) {
  3109. parentsMap.clear();
  3110. TNodeSet visisted;
  3111. GatherParentsImpl(node, parentsMap, visisted);
  3112. }
  3113. void CheckCounts(const TExprNode& root) {
  3114. TRefCountsMap refCounts;
  3115. CalculateReferences(root, refCounts);
  3116. TNodeSet visited;
  3117. CheckReferences(root, refCounts, visited);
  3118. }
  3119. TString SubstParameters(const TString& str, const TMaybe<NYT::TNode>& params, TSet<TString>* usedNames) {
  3120. size_t pos = 0;
  3121. try {
  3122. TStringBuilder res;
  3123. bool insideBrackets = false;
  3124. TStringBuilder paramBuilder;
  3125. for (char c : str) {
  3126. if (c == '{') {
  3127. if (insideBrackets) {
  3128. throw yexception() << "Unpexpected {";
  3129. }
  3130. insideBrackets = true;
  3131. continue;
  3132. }
  3133. if (c == '}') {
  3134. if (!insideBrackets) {
  3135. throw yexception() << "Unexpected }";
  3136. }
  3137. insideBrackets = false;
  3138. TString param = paramBuilder;
  3139. paramBuilder.clear();
  3140. if (usedNames) {
  3141. usedNames->insert(param);
  3142. }
  3143. if (params) {
  3144. const auto& map = params->AsMap();
  3145. auto it = map.find(param);
  3146. if (it == map.end()) {
  3147. throw yexception() << "No such parameter: '" << param << "'";
  3148. }
  3149. const auto& value = it->second["Data"];
  3150. if (!value.IsString()) {
  3151. throw yexception() << "Parameter value must be a string";
  3152. }
  3153. res << value.AsString();
  3154. }
  3155. continue;
  3156. }
  3157. if (insideBrackets) {
  3158. paramBuilder << c;
  3159. }
  3160. else {
  3161. res << c;
  3162. }
  3163. ++pos;
  3164. }
  3165. if (insideBrackets) {
  3166. throw yexception() << "Missing }";
  3167. }
  3168. return res;
  3169. }
  3170. catch (yexception& e) {
  3171. throw yexception() << "Failed to substitute parameters into url: " << str << ", reason:" << e.what() << ", position: " << pos;
  3172. }
  3173. }
  3174. const TTypeAnnotationNode* GetSeqItemType(const TTypeAnnotationNode* type) {
  3175. if (!type)
  3176. return nullptr;
  3177. switch (type->GetKind()) {
  3178. case ETypeAnnotationKind::List: return type->Cast<TListExprType>()->GetItemType();
  3179. case ETypeAnnotationKind::Flow: return type->Cast<TFlowExprType>()->GetItemType();
  3180. case ETypeAnnotationKind::Stream: return type->Cast<TStreamExprType>()->GetItemType();
  3181. case ETypeAnnotationKind::Optional: return type->Cast<TOptionalExprType>()->GetItemType();
  3182. default: break;
  3183. }
  3184. return nullptr;
  3185. }
  3186. const TTypeAnnotationNode& GetSeqItemType(const TTypeAnnotationNode& type) {
  3187. if (const auto itemType = GetSeqItemType(&type))
  3188. return *itemType;
  3189. throw yexception() << "Impossible to get item type from " << type;
  3190. }
  3191. const TTypeAnnotationNode& RemoveOptionality(const TTypeAnnotationNode& type) {
  3192. return ETypeAnnotationKind::Optional == type.GetKind() ? *type.Cast<TOptionalExprType>()->GetItemType() : type;
  3193. }
  3194. TMaybe<TIssue> NormalizeName(TPosition position, TString& name) {
  3195. const ui32 inputLength = name.length();
  3196. ui32 startCharPos = 0;
  3197. ui32 totalSkipped = 0;
  3198. bool atStart = true;
  3199. bool justSkippedUnderscore = false;
  3200. for (ui32 i = 0; i < inputLength; ++i) {
  3201. const char c = name.at(i);
  3202. if (c == '_') {
  3203. if (!atStart) {
  3204. if (justSkippedUnderscore) {
  3205. return TIssue(position, TStringBuilder() << "\"" << name << "\" looks weird, has multiple consecutive underscores");
  3206. }
  3207. justSkippedUnderscore = true;
  3208. ++totalSkipped;
  3209. continue;
  3210. } else {
  3211. ++startCharPos;
  3212. }
  3213. }
  3214. else {
  3215. atStart = false;
  3216. justSkippedUnderscore = false;
  3217. }
  3218. }
  3219. if (totalSkipped >= 5) {
  3220. return TIssue(position, TStringBuilder() << "\"" << name << "\" looks weird, has multiple consecutive underscores");
  3221. }
  3222. ui32 outPos = startCharPos;
  3223. for (ui32 i = startCharPos; i < inputLength; i++) {
  3224. const char c = name.at(i);
  3225. if (c == '_') {
  3226. continue;
  3227. } else {
  3228. name[outPos] = AsciiToLower(c);
  3229. ++outPos;
  3230. }
  3231. }
  3232. name.resize(outPos);
  3233. Y_ABORT_UNLESS(inputLength - outPos == totalSkipped);
  3234. return Nothing();
  3235. }
  3236. TString NormalizeName(const TStringBuf& name) {
  3237. TString result(name);
  3238. TMaybe<TIssue> error = NormalizeName(TPosition(), result);
  3239. YQL_ENSURE(error.Empty(), "" << error->GetMessage());
  3240. return result;
  3241. }
  3242. } // namespace NYql
  3243. template<>
  3244. void Out<NYql::TExprNode::EType>(class IOutputStream &o, NYql::TExprNode::EType x) {
  3245. #define YQL_EXPR_NODE_TYPE_MAP_TO_STRING_IMPL(name, ...) \
  3246. case NYql::TExprNode::name: \
  3247. o << #name; \
  3248. return;
  3249. switch (x) {
  3250. YQL_EXPR_NODE_TYPE_MAP(YQL_EXPR_NODE_TYPE_MAP_TO_STRING_IMPL)
  3251. default:
  3252. o << static_cast<int>(x);
  3253. return;
  3254. }
  3255. }
  3256. template<>
  3257. void Out<NYql::TExprNode::EState>(class IOutputStream &o, NYql::TExprNode::EState x) {
  3258. #define YQL_EXPR_NODE_STATE_MAP_TO_STRING_IMPL(name, ...) \
  3259. case NYql::TExprNode::EState::name: \
  3260. o << #name; \
  3261. return;
  3262. switch (x) {
  3263. YQL_EXPR_NODE_STATE_MAP(YQL_EXPR_NODE_STATE_MAP_TO_STRING_IMPL)
  3264. default:
  3265. o << static_cast<int>(x);
  3266. return;
  3267. }
  3268. }