sql_format.cpp 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314
  1. #include "sql_format.h"
  2. #include <yql/essentials/parser/lexer_common/lexer.h>
  3. #include <yql/essentials/core/sql_types/simple_types.h>
  4. #include <yql/essentials/parser/proto_ast/gen/v1_proto_split/SQLv1Parser.pb.main.h>
  5. #include <library/cpp/protobuf/util/simple_reflection.h>
  6. #include <library/cpp/resource/resource.h>
  7. #include <util/string/builder.h>
  8. #include <util/string/split.h>
  9. #include <util/string/strip.h>
  10. #include <util/string/subst.h>
  11. #include <util/generic/hash_set.h>
  12. namespace NSQLFormat {
  13. namespace {
  14. using namespace NSQLv1Generated;
  15. using NSQLTranslation::TParsedToken;
  16. using NSQLTranslation::TParsedTokenList;
  17. using NSQLTranslationV1::IsProbablyKeyword;
  18. using TTokenIterator = TParsedTokenList::const_iterator;
  19. TTokenIterator SkipWS(TTokenIterator curr, TTokenIterator end) {
  20. while (curr != end && curr->Name == "WS") {
  21. ++curr;
  22. }
  23. return curr;
  24. }
  25. TTokenIterator SkipWSOrComment(TTokenIterator curr, TTokenIterator end) {
  26. while (curr != end && (curr->Name == "WS" || curr->Name == "COMMENT")) {
  27. ++curr;
  28. }
  29. return curr;
  30. }
  31. TTokenIterator SkipWSOrCommentBackward(TTokenIterator curr, TTokenIterator begin) {
  32. while (curr != begin && (curr->Name == "WS" || curr->Name == "COMMENT")) {
  33. --curr;
  34. }
  35. return curr;
  36. }
  37. void SkipForValidate(
  38. TTokenIterator& in,
  39. TTokenIterator& out,
  40. const TParsedTokenList& query,
  41. const TParsedTokenList& formattedQuery,
  42. i32& parenthesesBalance
  43. ) {
  44. in = SkipWS(in, query.end());
  45. out = SkipWS(out, formattedQuery.end());
  46. auto inSkippedComments = SkipWSOrComment(in, query.end());
  47. auto skipAddedToken = [&](const TString& addedToken, const TVector<TString>& beforeTokens, const TVector<TString>& afterTokens) {
  48. if (
  49. out != formattedQuery.end() && out->Name == addedToken &&
  50. (in == query.end() || in->Name != addedToken) &&
  51. (beforeTokens.empty() || (inSkippedComments != query.end() && IsIn(beforeTokens, inSkippedComments->Name))) &&
  52. (afterTokens.empty() || (in != query.begin() && IsIn(afterTokens, SkipWSOrCommentBackward(in - 1, query.begin())->Name)))
  53. ) {
  54. out = SkipWS(++out, formattedQuery.end());
  55. if (addedToken == "LPAREN") {
  56. ++parenthesesBalance;
  57. } else if (addedToken == "RPAREN") {
  58. --parenthesesBalance;
  59. }
  60. }
  61. };
  62. skipAddedToken("LPAREN", {}, {"EQUALS"});
  63. skipAddedToken("RPAREN", {"END", "EOF", "SEMICOLON"}, {});
  64. skipAddedToken("SEMICOLON", {"END", "RBRACE_CURLY"}, {});
  65. auto skipDeletedToken = [&](const TString& deletedToken, const TVector<TString>& afterTokens) {
  66. if (
  67. in != query.end() && in->Name == deletedToken &&
  68. (out == formattedQuery.end() || out->Name != deletedToken) &&
  69. in != query.begin() && IsIn(afterTokens, SkipWSOrCommentBackward(in - 1, query.begin())->Name)
  70. ) {
  71. in = SkipWS(++in, query.end());
  72. return true;
  73. }
  74. return false;
  75. };
  76. while (skipDeletedToken("SEMICOLON", {"AS", "BEGIN", "LBRACE_CURLY", "SEMICOLON"})) {}
  77. }
  78. TParsedToken TransformTokenForValidate(TParsedToken token) {
  79. if (token.Name == "EQUALS2") {
  80. token.Name = "EQUALS";
  81. token.Content = "=";
  82. } else if (token.Name == "NOT_EQUALS2") {
  83. token.Name = "NOT_EQUALS";
  84. token.Content = "!=";
  85. }
  86. return token;
  87. }
  88. TStringBuf SkipQuotes(const TString& content) {
  89. TStringBuf str = content;
  90. str.SkipPrefix("\"");
  91. str.ChopSuffix("\"");
  92. str.SkipPrefix("'");
  93. str.ChopSuffix("'");
  94. return str;
  95. }
  96. TStringBuf SkipNewline(const TString& content) {
  97. TStringBuf str = content;
  98. str.ChopSuffix("\n");
  99. return str;
  100. }
  101. bool Validate(const TParsedTokenList& query, const TParsedTokenList& formattedQuery) {
  102. auto in = query.begin();
  103. auto out = formattedQuery.begin();
  104. auto inEnd = query.end();
  105. auto outEnd = formattedQuery.end();
  106. i32 parenthesesBalance = 0;
  107. while (in != inEnd && out != outEnd) {
  108. SkipForValidate(in, out, query, formattedQuery, parenthesesBalance);
  109. if (in != inEnd && out != outEnd) {
  110. auto inToken = TransformTokenForValidate(*in);
  111. auto outToken = TransformTokenForValidate(*out);
  112. if (inToken.Name != outToken.Name) {
  113. return false;
  114. }
  115. if (IsProbablyKeyword(inToken)) {
  116. if (!AsciiEqualsIgnoreCase(inToken.Content, outToken.Content)) {
  117. return false;
  118. }
  119. } else if (inToken.Name == "STRING_VALUE") {
  120. if (SkipQuotes(inToken.Content) != SkipQuotes(outToken.Content)) {
  121. return false;
  122. }
  123. } else if (inToken.Name == "COMMENT") {
  124. if (SkipNewline(inToken.Content) != SkipNewline(outToken.Content)) {
  125. return false;
  126. }
  127. } else {
  128. if (inToken.Content != outToken.Content) {
  129. return false;
  130. }
  131. }
  132. ++in;
  133. ++out;
  134. }
  135. }
  136. SkipForValidate(in, out, query, formattedQuery, parenthesesBalance);
  137. return in == inEnd && out == outEnd && parenthesesBalance == 0;
  138. }
  139. enum class EScope {
  140. Default,
  141. TypeName,
  142. Identifier,
  143. DoubleQuestion
  144. };
  145. class TPrettyVisitor;
  146. using TPrettyFunctor = std::function<void(TPrettyVisitor&, const NProtoBuf::Message& msg)>;
  147. class TObfuscatingVisitor;
  148. using TObfuscatingFunctor = std::function<void(TObfuscatingVisitor&, const NProtoBuf::Message& msg)>;
  149. struct TStaticData {
  150. TStaticData();
  151. static const TStaticData& GetInstance() {
  152. return *Singleton<TStaticData>();
  153. }
  154. THashSet<TString> Keywords;
  155. THashMap<const NProtoBuf::Descriptor*, EScope> ScopeDispatch;
  156. THashMap<const NProtoBuf::Descriptor*, TPrettyFunctor> PrettyVisitDispatch;
  157. THashMap<const NProtoBuf::Descriptor*, TObfuscatingFunctor> ObfuscatingVisitDispatch;
  158. };
  159. template <typename T, void (T::*Func)(const NProtoBuf::Message&)>
  160. void VisitAllFieldsImpl(T* obj, const NProtoBuf::Descriptor* descr, const NProtoBuf::Message& msg) {
  161. for (int i = 0; i < descr->field_count(); ++i) {
  162. const NProtoBuf::FieldDescriptor* fd = descr->field(i);
  163. NProtoBuf::TConstField field(msg, fd);
  164. if (field.IsMessage()) {
  165. for (size_t j = 0; j < field.Size(); ++j) {
  166. (obj->*Func)(*field.template Get<NProtoBuf::Message>(j));
  167. }
  168. }
  169. }
  170. }
  171. class TObfuscatingVisitor {
  172. friend struct TStaticData;
  173. public:
  174. TObfuscatingVisitor()
  175. : StaticData(TStaticData::GetInstance())
  176. {}
  177. TString Process(const NProtoBuf::Message& msg) {
  178. Scopes.push_back(EScope::Default);
  179. Visit(msg);
  180. return SB;
  181. }
  182. private:
  183. void VisitToken(const TToken& token) {
  184. auto str = token.GetValue();
  185. if (str == "<EOF>") {
  186. return;
  187. }
  188. if (!First) {
  189. SB << ' ';
  190. } else {
  191. First = false;
  192. }
  193. if (str == "$" && FuncCall) {
  194. FuncCall = false;
  195. }
  196. if (Scopes.back() == EScope::Identifier && !FuncCall) {
  197. if (str != "$" && !NYql::LookupSimpleTypeBySqlAlias(str, true)) {
  198. SB << "id";
  199. } else {
  200. SB << str;
  201. }
  202. } else if (NextToken) {
  203. SB << *NextToken;
  204. NextToken = Nothing();
  205. } else {
  206. SB << str;
  207. }
  208. }
  209. void VisitPragmaValue(const TRule_pragma_value& msg) {
  210. switch (msg.Alt_case()) {
  211. case TRule_pragma_value::kAltPragmaValue1: {
  212. NextToken = "0";
  213. break;
  214. }
  215. case TRule_pragma_value::kAltPragmaValue3: {
  216. NextToken = "'str'";
  217. break;
  218. }
  219. case TRule_pragma_value::kAltPragmaValue4: {
  220. NextToken = "false";
  221. break;
  222. }
  223. default:;
  224. }
  225. VisitAllFields(TRule_pragma_value::GetDescriptor(), msg);
  226. }
  227. void VisitLiteralValue(const TRule_literal_value& msg) {
  228. switch (msg.Alt_case()) {
  229. case TRule_literal_value::kAltLiteralValue1: {
  230. NextToken = "0";
  231. break;
  232. }
  233. case TRule_literal_value::kAltLiteralValue2: {
  234. NextToken = "0.0";
  235. break;
  236. }
  237. case TRule_literal_value::kAltLiteralValue3: {
  238. NextToken = "'str'";
  239. break;
  240. }
  241. case TRule_literal_value::kAltLiteralValue9: {
  242. NextToken = "false";
  243. break;
  244. }
  245. default:;
  246. }
  247. VisitAllFields(TRule_literal_value::GetDescriptor(), msg);
  248. }
  249. void VisitAtomExpr(const TRule_atom_expr& msg) {
  250. switch (msg.Alt_case()) {
  251. case TRule_atom_expr::kAltAtomExpr7: {
  252. FuncCall = true;
  253. break;
  254. }
  255. default:;
  256. }
  257. VisitAllFields(TRule_atom_expr::GetDescriptor(), msg);
  258. FuncCall = false;
  259. }
  260. void VisitInAtomExpr(const TRule_in_atom_expr& msg) {
  261. switch (msg.Alt_case()) {
  262. case TRule_in_atom_expr::kAltInAtomExpr6: {
  263. FuncCall = true;
  264. break;
  265. }
  266. default:;
  267. }
  268. VisitAllFields(TRule_in_atom_expr::GetDescriptor(), msg);
  269. FuncCall = false;
  270. }
  271. void VisitUnaryCasualSubexpr(const TRule_unary_casual_subexpr& msg) {
  272. bool invoke = false;
  273. for (auto& b : msg.GetRule_unary_subexpr_suffix2().GetBlock1()) {
  274. switch (b.GetBlock1().Alt_case()) {
  275. case TRule_unary_subexpr_suffix::TBlock1::TBlock1::kAlt2: {
  276. invoke = true;
  277. break;
  278. }
  279. default:;
  280. }
  281. break;
  282. }
  283. if (invoke) {
  284. FuncCall = true;
  285. }
  286. Visit(msg.GetBlock1());
  287. if (invoke) {
  288. FuncCall = false;
  289. }
  290. Visit(msg.GetRule_unary_subexpr_suffix2());
  291. }
  292. void VisitInUnaryCasualSubexpr(const TRule_in_unary_casual_subexpr& msg) {
  293. bool invoke = false;
  294. for (auto& b : msg.GetRule_unary_subexpr_suffix2().GetBlock1()) {
  295. switch (b.GetBlock1().Alt_case()) {
  296. case TRule_unary_subexpr_suffix::TBlock1::TBlock1::kAlt2: {
  297. invoke = true;
  298. break;
  299. }
  300. default:;
  301. }
  302. break;
  303. }
  304. if (invoke) {
  305. FuncCall = true;
  306. }
  307. Visit(msg.GetBlock1());
  308. if (invoke) {
  309. FuncCall = false;
  310. }
  311. Visit(msg.GetRule_unary_subexpr_suffix2());
  312. }
  313. void Visit(const NProtoBuf::Message& msg) {
  314. const NProtoBuf::Descriptor* descr = msg.GetDescriptor();
  315. auto scopePtr = StaticData.ScopeDispatch.FindPtr(descr);
  316. if (scopePtr) {
  317. Scopes.push_back(*scopePtr);
  318. }
  319. auto funcPtr = StaticData.ObfuscatingVisitDispatch.FindPtr(descr);
  320. if (funcPtr) {
  321. (*funcPtr)(*this, msg);
  322. } else {
  323. VisitAllFields(descr, msg);
  324. }
  325. if (scopePtr) {
  326. Scopes.pop_back();
  327. }
  328. }
  329. void VisitAllFields(const NProtoBuf::Descriptor* descr, const NProtoBuf::Message& msg) {
  330. VisitAllFieldsImpl<TObfuscatingVisitor, &TObfuscatingVisitor::Visit>(this, descr, msg);
  331. }
  332. const TStaticData& StaticData;
  333. TStringBuilder SB;
  334. bool First = true;
  335. TMaybe<TString> NextToken;
  336. TVector<EScope> Scopes;
  337. bool FuncCall = false;
  338. };
  339. class TPrettyVisitor {
  340. friend struct TStaticData;
  341. public:
  342. TPrettyVisitor(const TParsedTokenList& parsedTokens, const TParsedTokenList& comments, bool ansiLexer)
  343. : StaticData(TStaticData::GetInstance())
  344. , ParsedTokens(parsedTokens)
  345. , Comments(comments)
  346. , AnsiLexer(ansiLexer)
  347. {
  348. }
  349. TString Process(const NProtoBuf::Message& msg, bool& addLineBefore, bool& addLineAfter, TMaybe<ui32>& stmtCoreAltCase) {
  350. Scopes.push_back(EScope::Default);
  351. MarkedTokens.reserve(ParsedTokens.size());
  352. MarkTokens(msg);
  353. Y_ENSURE(MarkTokenStack.empty());
  354. Y_ENSURE(TokenIndex == ParsedTokens.size());
  355. TokenIndex = 0;
  356. Visit(msg);
  357. Y_ENSURE(TokenIndex == ParsedTokens.size());
  358. Y_ENSURE(MarkTokenStack.empty());
  359. for (; LastComment < Comments.size(); ++LastComment) {
  360. const auto text = Comments[LastComment].Content;
  361. AddComment(text);
  362. }
  363. ui32 lines = OutLine - (OutColumn == 0 ? 1 : 0);
  364. addLineBefore = AddLine.GetOrElse(true) || lines > 1;
  365. addLineAfter = AddLine.GetOrElse(true) || lines - CommentLines > 1;
  366. stmtCoreAltCase = StmtCoreAltCase;
  367. return SB;
  368. }
  369. private:
  370. struct TTokenInfo {
  371. bool OpeningBracket = false;
  372. bool ClosingBracket = false;
  373. bool BracketForcedExpansion = false;
  374. ui32 ClosingBracketIndex = 0;
  375. };
  376. using TMarkTokenStack = TVector<ui32>;
  377. void Out(TStringBuf s) {
  378. for (ui32 i = 0; i < s.size(); ++i) {
  379. Out(s[i], i == 0);
  380. }
  381. }
  382. void Out(char c, bool useIndent = true) {
  383. if (c == '\n' || c == '\r') {
  384. SB << c;
  385. if (!(c == '\n' && !SB.empty() && SB.back() == '\r')) {
  386. // do not increase OutLine if \n is preceded by \r
  387. // this way we handle \r, \n, or \r\n as single new line
  388. ++OutLine;
  389. }
  390. OutColumn = 0;
  391. } else {
  392. if (!OutColumn && useIndent) {
  393. ui32 indent = (CurrentIndent >= 0) ? CurrentIndent : 0;
  394. for (ui32 i = 0; i < indent; ++i) {
  395. SB << ' ';
  396. }
  397. }
  398. SB << c;
  399. ++OutColumn;
  400. }
  401. }
  402. void NewLine() {
  403. if (TokenIndex >= ParsedTokens.size() || ParsedTokens[TokenIndex].Line > LastLine) {
  404. WriteComments(true);
  405. }
  406. if (OutColumn) {
  407. Out('\n');
  408. }
  409. }
  410. void AddComment(TStringBuf text) {
  411. if (!AfterComment && OutLine > BlockFirstLine && OutColumn == 0) {
  412. Out('\n');
  413. }
  414. AfterComment = true;
  415. if (!SB.empty() && SB.back() != ' ' && SB.back() != '\n') {
  416. Out(' ');
  417. }
  418. if (OutColumn == 0) {
  419. ++CommentLines;
  420. }
  421. if (!text.StartsWith("--")) {
  422. CommentLines += CountIf(text, [](auto c) { return c == '\n'; });
  423. }
  424. Out(text);
  425. if (text.StartsWith("--") && !text.EndsWith("\n")) {
  426. Out('\n');
  427. }
  428. if (!text.StartsWith("--") &&
  429. TokenIndex < ParsedTokens.size() &&
  430. Comments[LastComment].Line < ParsedTokens[TokenIndex].Line &&
  431. (LastComment + 1 >= Comments.size() || Comments[LastComment].Line < Comments[LastComment + 1].Line)
  432. ) {
  433. Out('\n');
  434. }
  435. }
  436. void MarkTokens(const NProtoBuf::Message& msg) {
  437. const NProtoBuf::Descriptor* descr = msg.GetDescriptor();
  438. auto scopePtr = StaticData.ScopeDispatch.FindPtr(descr);
  439. if (scopePtr) {
  440. if (*scopePtr == EScope::TypeName) {
  441. ++InsideType;
  442. }
  443. Scopes.push_back(*scopePtr);
  444. }
  445. bool suppressExpr = false;
  446. if (descr == TToken::GetDescriptor()) {
  447. const auto& token = dynamic_cast<const TToken&>(msg);
  448. MarkToken(token);
  449. } else if (descr == TRule_sql_stmt_core::GetDescriptor()) {
  450. if (AddLine.Empty()) {
  451. const auto& rule = dynamic_cast<const TRule_sql_stmt_core&>(msg);
  452. AddLine = !IsSimpleStatement(rule).GetOrElse(false);
  453. StmtCoreAltCase = rule.Alt_case();
  454. }
  455. } else if (descr == TRule_lambda_body::GetDescriptor()) {
  456. Y_ENSURE(TokenIndex >= 1);
  457. auto prevIndex = TokenIndex - 1;
  458. Y_ENSURE(prevIndex < ParsedTokens.size());
  459. Y_ENSURE(ParsedTokens[prevIndex].Content == "{");
  460. MarkedTokens[prevIndex].OpeningBracket = false;
  461. ForceExpandedColumn = ParsedTokens[prevIndex].LinePos;
  462. ForceExpandedLine = ParsedTokens[prevIndex].Line;
  463. } else if (descr == TRule_in_atom_expr::GetDescriptor()) {
  464. const auto& value = dynamic_cast<const TRule_in_atom_expr&>(msg);
  465. if (value.Alt_case() == TRule_in_atom_expr::kAltInAtomExpr7) {
  466. suppressExpr = true;
  467. }
  468. } else if (descr == TRule_select_kind_parenthesis::GetDescriptor()) {
  469. const auto& value = dynamic_cast<const TRule_select_kind_parenthesis&>(msg);
  470. if (value.Alt_case() == TRule_select_kind_parenthesis::kAltSelectKindParenthesis2) {
  471. suppressExpr = true;
  472. }
  473. } else if (descr == TRule_window_specification::GetDescriptor()) {
  474. const auto& value = dynamic_cast<const TRule_window_specification&>(msg);
  475. const auto& details = value.GetRule_window_specification_details2();
  476. const bool needsNewline = details.HasBlock1() || details.HasBlock2() ||
  477. details.HasBlock3() || details.HasBlock4();
  478. if (needsNewline) {
  479. auto& paren = value.GetToken1();
  480. ForceExpandedColumn = paren.GetColumn();
  481. ForceExpandedLine = paren.GetLine();
  482. }
  483. suppressExpr = true;
  484. } else if (descr == TRule_exists_expr::GetDescriptor()) {
  485. const auto& value = dynamic_cast<const TRule_exists_expr&>(msg);
  486. auto& paren = value.GetToken2();
  487. ForceExpandedColumn = paren.GetColumn();
  488. ForceExpandedLine = paren.GetLine();
  489. suppressExpr = true;
  490. } else if (descr == TRule_case_expr::GetDescriptor()) {
  491. const auto& value = dynamic_cast<const TRule_case_expr&>(msg);
  492. auto& token = value.GetToken1();
  493. ForceExpandedColumn = token.GetColumn();
  494. ForceExpandedLine = token.GetLine();
  495. }
  496. const bool expr = (descr == TRule_expr::GetDescriptor() || descr == TRule_in_expr::GetDescriptor() || descr == TRule_type_name_composite::GetDescriptor());
  497. if (expr) {
  498. ++InsideExpr;
  499. }
  500. ui64 prevInsideExpr = InsideExpr;
  501. if (suppressExpr) {
  502. InsideExpr = 0;
  503. }
  504. VisitAllFieldsImpl<TPrettyVisitor, &TPrettyVisitor::MarkTokens>(this, descr, msg);
  505. if (suppressExpr) {
  506. InsideExpr = prevInsideExpr;
  507. }
  508. if (scopePtr) {
  509. if (*scopePtr == EScope::TypeName) {
  510. --InsideType;
  511. }
  512. Scopes.pop_back();
  513. }
  514. if (expr) {
  515. --InsideExpr;
  516. }
  517. }
  518. void MarkToken(const TToken& token) {
  519. auto str = token.GetValue();
  520. if (str == "<EOF>") {
  521. return;
  522. }
  523. MarkedTokens.emplace_back();
  524. if (str == "(" || str == "[" || str == "{" || str == "<|" || (InsideType && str == "<")) {
  525. MarkTokenStack.push_back(TokenIndex);
  526. auto& info = MarkedTokens[TokenIndex];
  527. info.OpeningBracket = (InsideExpr > 0);
  528. } else if (str == ")") {
  529. PopBracket("(");
  530. } else if (str == "]") {
  531. PopBracket("[");
  532. } else if (str == "}") {
  533. PopBracket("{");
  534. } else if (str == "|>") {
  535. PopBracket("<|");
  536. } else if (InsideType && str == ">") {
  537. PopBracket("<");
  538. }
  539. TokenIndex++;
  540. }
  541. void PopBracket(const TString& expected) {
  542. Y_ENSURE(!MarkTokenStack.empty());
  543. Y_ENSURE(MarkTokenStack.back() < ParsedTokens.size());
  544. auto& openToken = ParsedTokens[MarkTokenStack.back()];
  545. Y_ENSURE(openToken.Content == expected);
  546. auto& openInfo = MarkedTokens[MarkTokenStack.back()];
  547. auto& closeInfo = MarkedTokens[TokenIndex];
  548. const bool forcedExpansion = openToken.Line == ForceExpandedLine && openToken.LinePos <= ForceExpandedColumn;
  549. if (openInfo.OpeningBracket) {
  550. openInfo.ClosingBracketIndex = TokenIndex;
  551. openInfo.BracketForcedExpansion = forcedExpansion;
  552. closeInfo.BracketForcedExpansion = forcedExpansion;
  553. closeInfo.ClosingBracket = true;
  554. }
  555. MarkTokenStack.pop_back();
  556. }
  557. void Visit(const NProtoBuf::Message& msg) {
  558. const NProtoBuf::Descriptor* descr = msg.GetDescriptor();
  559. //Cerr << descr->name() << "\n";
  560. auto scopePtr = StaticData.ScopeDispatch.FindPtr(descr);
  561. if (descr == TRule_invoke_expr::GetDescriptor()) {
  562. AfterInvokeExpr = true;
  563. }
  564. if (descr == TRule_unary_op::GetDescriptor()) {
  565. AfterUnaryOp = true;
  566. }
  567. if (scopePtr) {
  568. if (*scopePtr == EScope::TypeName) {
  569. ++InsideType;
  570. }
  571. Scopes.push_back(*scopePtr);
  572. }
  573. auto funcPtr = StaticData.PrettyVisitDispatch.FindPtr(descr);
  574. if (funcPtr) {
  575. (*funcPtr)(*this, msg);
  576. } else {
  577. VisitAllFields(descr, msg);
  578. }
  579. if (scopePtr) {
  580. if (*scopePtr == EScope::TypeName) {
  581. --InsideType;
  582. }
  583. Scopes.pop_back();
  584. }
  585. }
  586. TMaybe<bool> IsSimpleStatement(const TRule_sql_stmt_core& msg) {
  587. switch (msg.Alt_case()) {
  588. case TRule_sql_stmt_core::kAltSqlStmtCore1: // pragma
  589. case TRule_sql_stmt_core::kAltSqlStmtCore5: // drop table
  590. case TRule_sql_stmt_core::kAltSqlStmtCore6: // use
  591. case TRule_sql_stmt_core::kAltSqlStmtCore8: // commit
  592. case TRule_sql_stmt_core::kAltSqlStmtCore11: // rollback
  593. case TRule_sql_stmt_core::kAltSqlStmtCore12: // declare
  594. case TRule_sql_stmt_core::kAltSqlStmtCore13: // import
  595. case TRule_sql_stmt_core::kAltSqlStmtCore14: // export
  596. case TRule_sql_stmt_core::kAltSqlStmtCore32: // drop external data source
  597. case TRule_sql_stmt_core::kAltSqlStmtCore34: // drop replication
  598. case TRule_sql_stmt_core::kAltSqlStmtCore60: // drop transfer
  599. return true;
  600. case TRule_sql_stmt_core::kAltSqlStmtCore3: { // named nodes
  601. const auto& stmt = msg.GetAlt_sql_stmt_core3().GetRule_named_nodes_stmt1();
  602. if (stmt.GetBlock3().HasAlt1()) {
  603. return true;
  604. }
  605. break;
  606. }
  607. case TRule_sql_stmt_core::kAltSqlStmtCore17: { // do
  608. const auto& stmt = msg.GetAlt_sql_stmt_core17().GetRule_do_stmt1();
  609. if (stmt.GetBlock2().HasAlt1()) {
  610. return true;
  611. }
  612. break;
  613. }
  614. case TRule_sql_stmt_core::kAltSqlStmtCore19: // if
  615. case TRule_sql_stmt_core::kAltSqlStmtCore20: // for
  616. return false;
  617. default:
  618. break;
  619. }
  620. return {};
  621. }
  622. template <typename T>
  623. void VisitRepeated(const ::google::protobuf::RepeatedPtrField<T>& field) {
  624. for (const auto& m : field) {
  625. Visit(m);
  626. }
  627. }
  628. template <typename T>
  629. void SkipSemicolons(const ::google::protobuf::RepeatedPtrField<T>& field, bool printOne = false) {
  630. for (const auto& m : field) {
  631. if (printOne) {
  632. Visit(m);
  633. printOne = false;
  634. } else {
  635. ++TokenIndex;
  636. }
  637. }
  638. if (printOne) {
  639. Out(';');
  640. }
  641. }
  642. void VisitValueConstructor(const TRule_value_constructor& msg) {
  643. switch (msg.Alt_case()) {
  644. case TRule_value_constructor::kAltValueConstructor1: {
  645. auto& ctor = msg.GetAlt_value_constructor1();
  646. Scopes.push_back(EScope::TypeName);
  647. Visit(ctor.GetToken1());
  648. Scopes.pop_back();
  649. AfterInvokeExpr = true;
  650. Visit(ctor.GetToken2());
  651. Visit(ctor.GetRule_expr3());
  652. Visit(ctor.GetToken4());
  653. Visit(ctor.GetRule_expr5());
  654. Visit(ctor.GetToken6());
  655. Visit(ctor.GetRule_expr7());
  656. Visit(ctor.GetToken8());
  657. break;
  658. }
  659. case TRule_value_constructor::kAltValueConstructor2: {
  660. auto& ctor = msg.GetAlt_value_constructor2();
  661. Scopes.push_back(EScope::TypeName);
  662. Visit(ctor.GetToken1());
  663. Scopes.pop_back();
  664. AfterInvokeExpr = true;
  665. Visit(ctor.GetToken2());
  666. Visit(ctor.GetRule_expr3());
  667. Visit(ctor.GetToken4());
  668. Visit(ctor.GetRule_expr5());
  669. Visit(ctor.GetToken6());
  670. break;
  671. }
  672. case TRule_value_constructor::kAltValueConstructor3: {
  673. auto& ctor = msg.GetAlt_value_constructor3();
  674. Scopes.push_back(EScope::TypeName);
  675. Visit(ctor.GetToken1());
  676. Scopes.pop_back();
  677. AfterInvokeExpr = true;
  678. Visit(ctor.GetToken2());
  679. Visit(ctor.GetRule_expr3());
  680. Visit(ctor.GetToken4());
  681. Visit(ctor.GetRule_expr5());
  682. Visit(ctor.GetToken6());
  683. break;
  684. }
  685. case TRule_value_constructor::ALT_NOT_SET:
  686. Y_ABORT("You should change implementation according to grammar changes");
  687. }
  688. }
  689. void VisitDefineActionOrSubqueryBody(const TRule_define_action_or_subquery_body& msg) {
  690. SkipSemicolons(msg.GetBlock1());
  691. if (msg.HasBlock2()) {
  692. const auto& b = msg.GetBlock2();
  693. Visit(b.GetRule_sql_stmt_core1());
  694. for (auto block : b.GetBlock2()) {
  695. SkipSemicolons(block.GetBlock1(), /* printOne = */ true);
  696. if (!IsSimpleStatement(block.GetRule_sql_stmt_core2()).GetOrElse(false)) {
  697. Out('\n');
  698. }
  699. Visit(block.GetRule_sql_stmt_core2());
  700. }
  701. SkipSemicolons(b.GetBlock3(), /* printOne = */ true);
  702. }
  703. }
  704. void VisitPragma(const TRule_pragma_stmt& msg) {
  705. NewLine();
  706. VisitKeyword(msg.GetToken1());
  707. auto prefix = msg.GetRule_opt_id_prefix_or_type2();
  708. if (prefix.HasBlock1()) {
  709. Visit(prefix.GetBlock1().GetRule_an_id_or_type1());
  710. VisitKeyword(prefix.GetBlock1().GetToken2());
  711. AfterDot = true;
  712. }
  713. Visit(msg.GetRule_an_id3());
  714. if (msg.GetBlock4().HasAlt2()) {
  715. AfterInvokeExpr = true;
  716. const auto& alt2 = msg.GetBlock4().GetAlt2();
  717. VisitKeyword(alt2.GetToken1());
  718. Visit(alt2.GetRule_pragma_value2());
  719. VisitRepeated(alt2.GetBlock3());
  720. VisitKeyword(alt2.GetToken4());
  721. } else {
  722. Visit(msg.GetBlock4());
  723. }
  724. }
  725. void VisitSelect(const TRule_select_stmt& msg) {
  726. NewLine();
  727. Visit(msg.GetRule_select_kind_parenthesis1());
  728. for (const auto& block : msg.GetBlock2()) {
  729. NewLine();
  730. Visit(block.GetRule_select_op1());
  731. NewLine();
  732. Visit(block.GetRule_select_kind_parenthesis2());
  733. }
  734. }
  735. void VisitSelectUnparenthesized(const TRule_select_unparenthesized_stmt& msg) {
  736. NewLine();
  737. Visit(msg.GetRule_select_kind_partial1());
  738. for (const auto& block : msg.GetBlock2()) {
  739. NewLine();
  740. Visit(block.GetRule_select_op1());
  741. NewLine();
  742. Visit(block.GetRule_select_kind_parenthesis2());
  743. }
  744. }
  745. void VisitNamedNodes(const TRule_named_nodes_stmt& msg) {
  746. NewLine();
  747. Visit(msg.GetRule_bind_parameter_list1());
  748. Visit(msg.GetToken2());
  749. ExprLineIndent = CurrentIndent;
  750. switch (msg.GetBlock3().Alt_case()) {
  751. case TRule_named_nodes_stmt::TBlock3::kAlt1: {
  752. const auto& alt = msg.GetBlock3().GetAlt1();
  753. Visit(alt);
  754. break;
  755. }
  756. case TRule_named_nodes_stmt::TBlock3::kAlt2: {
  757. const auto& alt = msg.GetBlock3().GetAlt2();
  758. const auto& subselect = alt.GetRule_subselect_stmt1();
  759. switch (subselect.GetBlock1().Alt_case()) {
  760. case TRule_subselect_stmt::TBlock1::kAlt1: {
  761. const auto& alt = subselect.GetBlock1().GetAlt1();
  762. Visit(alt.GetToken1());
  763. NewLine();
  764. PushCurrentIndent();
  765. Visit(alt.GetRule_select_stmt2());
  766. PopCurrentIndent();
  767. NewLine();
  768. Visit(alt.GetToken3());
  769. break;
  770. }
  771. case TRule_subselect_stmt::TBlock1::kAlt2: {
  772. const auto& alt = subselect.GetBlock1().GetAlt2();
  773. Out(" (");
  774. NewLine();
  775. PushCurrentIndent();
  776. Visit(alt);
  777. PopCurrentIndent();
  778. NewLine();
  779. Out(')');
  780. break;
  781. }
  782. default:
  783. ythrow yexception() << "Alt is not supported";
  784. }
  785. break;
  786. }
  787. default:
  788. ythrow yexception() << "Alt is not supported";
  789. }
  790. ExprLineIndent = 0;
  791. }
  792. void VisitAlterDatabase(const TRule_alter_database_stmt& msg) {
  793. NewLine();
  794. VisitAllFields(TRule_alter_database_stmt::GetDescriptor(), msg);
  795. }
  796. void VisitCreateTable(const TRule_create_table_stmt& msg) {
  797. NewLine();
  798. Visit(msg.GetToken1());
  799. Visit(msg.GetBlock2());
  800. Visit(msg.GetBlock3());
  801. Visit(msg.GetBlock4());
  802. Visit(msg.GetRule_simple_table_ref5());
  803. Visit(msg.GetToken6());
  804. PushCurrentIndent();
  805. NewLine();
  806. Visit(msg.GetRule_create_table_entry7());
  807. for (const auto& b : msg.GetBlock8()) {
  808. Visit(b.GetToken1());
  809. NewLine();
  810. Visit(b.GetRule_create_table_entry2());
  811. }
  812. if (msg.HasBlock9()) {
  813. Visit(msg.GetBlock9());
  814. }
  815. PopCurrentIndent();
  816. NewLine();
  817. Visit(msg.GetToken10());
  818. if (msg.HasBlock11()) {
  819. NewLine();
  820. Visit(msg.GetBlock11());
  821. }
  822. if (msg.HasBlock12()) {
  823. NewLine();
  824. Visit(msg.GetBlock12());
  825. }
  826. if (msg.HasBlock13()) {
  827. NewLine();
  828. Visit(msg.GetBlock13());
  829. }
  830. if (msg.HasBlock14()) {
  831. NewLine();
  832. Visit(msg.GetBlock14());
  833. }
  834. if (msg.HasBlock15()) {
  835. NewLine();
  836. Visit(msg.GetBlock15());
  837. }
  838. }
  839. void VisitDropTable(const TRule_drop_table_stmt& msg) {
  840. NewLine();
  841. VisitAllFields(TRule_drop_table_stmt::GetDescriptor(), msg);
  842. }
  843. void VisitAnalyze(const TRule_analyze_stmt& msg) {
  844. NewLine();
  845. VisitAllFields(TRule_analyze_stmt::GetDescriptor(), msg);
  846. }
  847. void VisitBackup(const TRule_backup_stmt& msg) {
  848. NewLine();
  849. VisitAllFields(TRule_backup_stmt::GetDescriptor(), msg);
  850. }
  851. void VisitRestore(const TRule_restore_stmt& msg) {
  852. NewLine();
  853. VisitAllFields(TRule_restore_stmt::GetDescriptor(), msg);
  854. }
  855. void VisitUse(const TRule_use_stmt& msg) {
  856. NewLine();
  857. VisitAllFields(TRule_use_stmt::GetDescriptor(), msg);
  858. }
  859. void VisitAlterSequence(const TRule_alter_sequence_stmt& msg) {
  860. PosFromToken(msg.GetToken1());
  861. NewLine();
  862. VisitAllFields(TRule_alter_sequence_stmt::GetDescriptor(), msg);
  863. }
  864. void VisitShowCreateTable(const TRule_show_create_table_stmt& msg) {
  865. NewLine();
  866. VisitAllFields(TRule_show_create_table_stmt::GetDescriptor(), msg);
  867. }
  868. void VisitIntoTable(const TRule_into_table_stmt& msg) {
  869. NewLine();
  870. VisitAllFields(TRule_into_table_stmt::GetDescriptor(), msg);
  871. }
  872. void VisitCommit(const TRule_commit_stmt& msg) {
  873. NewLine();
  874. VisitAllFields(TRule_commit_stmt::GetDescriptor(), msg);
  875. }
  876. void VisitUpdate(const TRule_update_stmt& msg) {
  877. NewLine();
  878. Visit(msg.GetToken2());
  879. Visit(msg.GetRule_simple_table_ref3());
  880. switch (msg.GetBlock4().Alt_case()) {
  881. case TRule_update_stmt_TBlock4::kAlt1: {
  882. const auto& alt = msg.GetBlock4().GetAlt1();
  883. NewLine();
  884. Visit(alt.GetToken1());
  885. const auto& choice = alt.GetRule_set_clause_choice2();
  886. NewLine();
  887. switch (choice.Alt_case()) {
  888. case TRule_set_clause_choice::kAltSetClauseChoice1: {
  889. const auto& clauses = choice.GetAlt_set_clause_choice1().GetRule_set_clause_list1();
  890. NewLine();
  891. PushCurrentIndent();
  892. Visit(clauses.GetRule_set_clause1());
  893. for (auto& block : clauses.GetBlock2()) {
  894. Visit(block.GetToken1());
  895. NewLine();
  896. Visit(block.GetRule_set_clause2());
  897. }
  898. PopCurrentIndent();
  899. NewLine();
  900. break;
  901. }
  902. case TRule_set_clause_choice::kAltSetClauseChoice2: {
  903. const auto& multiColumn = choice.GetAlt_set_clause_choice2().GetRule_multiple_column_assignment1();
  904. const auto& targets = multiColumn.GetRule_set_target_list1();
  905. Visit(targets.GetToken1());
  906. NewLine();
  907. PushCurrentIndent();
  908. Visit(targets.GetRule_set_target2());
  909. for (auto& block : targets.GetBlock3()) {
  910. Visit(block.GetToken1());
  911. NewLine();
  912. Visit(block.GetRule_set_target2());
  913. }
  914. NewLine();
  915. PopCurrentIndent();
  916. Visit(targets.GetToken4());
  917. Visit(multiColumn.GetToken2());
  918. Visit(multiColumn.GetToken3());
  919. NewLine();
  920. const auto& simpleValues = multiColumn.GetRule_simple_values_source4();
  921. switch (simpleValues.Alt_case()) {
  922. case TRule_simple_values_source::kAltSimpleValuesSource1: {
  923. const auto& exprs = simpleValues.GetAlt_simple_values_source1().GetRule_expr_list1();
  924. NewLine();
  925. PushCurrentIndent();
  926. Visit(exprs.GetRule_expr1());
  927. for (const auto& block : exprs.GetBlock2()) {
  928. Visit(block.GetToken1());
  929. NewLine();
  930. Visit(block.GetRule_expr2());
  931. }
  932. PopCurrentIndent();
  933. NewLine();
  934. break;
  935. }
  936. case TRule_simple_values_source::kAltSimpleValuesSource2: {
  937. NewLine();
  938. PushCurrentIndent();
  939. Visit(simpleValues.GetAlt_simple_values_source2());
  940. PopCurrentIndent();
  941. NewLine();
  942. break;
  943. }
  944. default:
  945. ythrow yexception() << "Alt is not supported";
  946. }
  947. NewLine();
  948. Visit(multiColumn.GetToken5());
  949. break;
  950. }
  951. default:
  952. ythrow yexception() << "Alt is not supported";
  953. }
  954. PopCurrentIndent();
  955. if (alt.HasBlock3()) {
  956. NewLine();
  957. Visit(alt.GetBlock3());
  958. }
  959. PopCurrentIndent();
  960. break;
  961. }
  962. case TRule_update_stmt_TBlock4::kAlt2: {
  963. const auto& alt = msg.GetBlock4().GetAlt2();
  964. NewLine();
  965. Visit(alt.GetToken1());
  966. Visit(alt.GetRule_into_values_source2());
  967. break;
  968. }
  969. default:
  970. ythrow yexception() << "Alt is not supported";
  971. }
  972. }
  973. void VisitDelete(const TRule_delete_stmt& msg) {
  974. NewLine();
  975. Visit(msg.GetToken2());
  976. Visit(msg.GetToken3());
  977. Visit(msg.GetRule_simple_table_ref4());
  978. if (msg.HasBlock5()) {
  979. switch (msg.GetBlock5().Alt_case()) {
  980. case TRule_delete_stmt_TBlock5::kAlt1: {
  981. const auto& alt = msg.GetBlock5().GetAlt1();
  982. NewLine();
  983. Visit(alt);
  984. break;
  985. }
  986. case TRule_delete_stmt_TBlock5::kAlt2: {
  987. const auto& alt = msg.GetBlock5().GetAlt2();
  988. NewLine();
  989. Visit(alt);
  990. break;
  991. }
  992. default:
  993. ythrow yexception() << "Alt is not supported";
  994. }
  995. }
  996. }
  997. void VisitRollback(const TRule_rollback_stmt& msg) {
  998. NewLine();
  999. VisitAllFields(TRule_rollback_stmt::GetDescriptor(), msg);
  1000. }
  1001. void VisitDeclare(const TRule_declare_stmt& msg) {
  1002. NewLine();
  1003. VisitAllFields(TRule_declare_stmt::GetDescriptor(), msg);
  1004. }
  1005. void VisitImport(const TRule_import_stmt& msg) {
  1006. NewLine();
  1007. VisitAllFields(TRule_import_stmt::GetDescriptor(), msg);
  1008. }
  1009. void VisitExport(const TRule_export_stmt& msg) {
  1010. NewLine();
  1011. VisitKeyword(msg.GetToken1());
  1012. NewLine();
  1013. PushCurrentIndent();
  1014. const auto& list = msg.GetRule_bind_parameter_list2();
  1015. Visit(list.GetRule_bind_parameter1());
  1016. for (auto& b : list.GetBlock2()) {
  1017. Visit(b.GetToken1());
  1018. NewLine();
  1019. Visit(b.GetRule_bind_parameter2());
  1020. }
  1021. PopCurrentIndent();
  1022. NewLine();
  1023. }
  1024. void VisitAlterTable(const TRule_alter_table_stmt& msg) {
  1025. NewLine();
  1026. VisitKeyword(msg.GetToken1());
  1027. VisitKeyword(msg.GetToken2());
  1028. Visit(msg.GetRule_simple_table_ref3());
  1029. NewLine();
  1030. PushCurrentIndent();
  1031. Visit(msg.GetRule_alter_table_action4());
  1032. for (auto& b : msg.GetBlock5()) {
  1033. Visit(b.GetToken1());
  1034. NewLine();
  1035. Visit(b.GetRule_alter_table_action2());
  1036. }
  1037. PopCurrentIndent();
  1038. NewLine();
  1039. }
  1040. void VisitAlterTableStore(const TRule_alter_table_store_stmt& msg) {
  1041. NewLine();
  1042. VisitAllFields(TRule_alter_table_store_stmt::GetDescriptor(), msg);
  1043. }
  1044. void VisitAlterExternalTable(const TRule_alter_external_table_stmt& msg) {
  1045. NewLine();
  1046. VisitKeyword(msg.GetToken1());
  1047. VisitKeyword(msg.GetToken2());
  1048. VisitKeyword(msg.GetToken3());
  1049. Visit(msg.GetRule_simple_table_ref4());
  1050. NewLine();
  1051. PushCurrentIndent();
  1052. Visit(msg.GetRule_alter_external_table_action5());
  1053. for (auto& b : msg.GetBlock6()) {
  1054. Visit(b.GetToken1());
  1055. NewLine();
  1056. Visit(b.GetRule_alter_external_table_action2());
  1057. }
  1058. PopCurrentIndent();
  1059. NewLine();
  1060. }
  1061. void VisitDo(const TRule_do_stmt& msg) {
  1062. VisitKeyword(msg.GetToken1());
  1063. switch (msg.GetBlock2().Alt_case()) {
  1064. case TRule_do_stmt_TBlock2::kAlt1: { // CALL
  1065. PushCurrentIndent();
  1066. NewLine();
  1067. const auto& alt = msg.GetBlock2().GetAlt1().GetRule_call_action1();
  1068. Visit(alt.GetBlock1());
  1069. AfterInvokeExpr = true;
  1070. Visit(alt.GetToken2());
  1071. if (alt.HasBlock3()) {
  1072. Visit(alt.GetBlock3());
  1073. }
  1074. Visit(alt.GetToken4());
  1075. PopCurrentIndent();
  1076. NewLine();
  1077. break;
  1078. }
  1079. case TRule_do_stmt_TBlock2::kAlt2: { // INLINE
  1080. const auto& alt = msg.GetBlock2().GetAlt2().GetRule_inline_action1();
  1081. VisitKeyword(alt.GetToken1());
  1082. PushCurrentIndent();
  1083. NewLine();
  1084. Visit(alt.GetRule_define_action_or_subquery_body2());
  1085. PopCurrentIndent();
  1086. NewLine();
  1087. VisitKeyword(alt.GetToken3());
  1088. VisitKeyword(alt.GetToken4());
  1089. break;
  1090. }
  1091. default:
  1092. ythrow yexception() << "Alt is not supported";
  1093. }
  1094. }
  1095. void VisitAction(const TRule_define_action_or_subquery_stmt& msg) {
  1096. NewLine();
  1097. VisitKeyword(msg.GetToken1());
  1098. VisitKeyword(msg.GetToken2());
  1099. Visit(msg.GetRule_bind_parameter3());
  1100. AfterInvokeExpr = true;
  1101. Visit(msg.GetToken4());
  1102. if (msg.HasBlock5()) {
  1103. Visit(msg.GetBlock5());
  1104. }
  1105. Visit(msg.GetToken6());
  1106. VisitKeyword(msg.GetToken7()); // AS
  1107. NewLine();
  1108. PushCurrentIndent();
  1109. Visit(msg.GetRule_define_action_or_subquery_body8());
  1110. PopCurrentIndent();
  1111. NewLine();
  1112. VisitKeyword(msg.GetToken9());
  1113. VisitKeyword(msg.GetToken10());
  1114. }
  1115. void VisitIf(const TRule_if_stmt& msg) {
  1116. NewLine();
  1117. VisitAllFields(TRule_if_stmt::GetDescriptor(), msg);
  1118. }
  1119. void VisitFor(const TRule_for_stmt& msg) {
  1120. NewLine();
  1121. VisitAllFields(TRule_for_stmt::GetDescriptor(), msg);
  1122. }
  1123. void VisitValues(const TRule_values_stmt& msg) {
  1124. NewLine();
  1125. VisitKeyword(msg.GetToken1());
  1126. const auto& rowList = msg.GetRule_values_source_row_list2();
  1127. PushCurrentIndent();
  1128. NewLine();
  1129. Visit(rowList.GetRule_values_source_row1());
  1130. for (const auto& b : rowList.GetBlock2()) {
  1131. Visit(b.GetToken1());
  1132. NewLine();
  1133. Visit(b.GetRule_values_source_row2());
  1134. }
  1135. PopCurrentIndent();
  1136. NewLine();
  1137. }
  1138. void VisitGrantPermissions(const TRule_grant_permissions_stmt& msg) {
  1139. NewLine();
  1140. VisitAllFields(TRule_grant_permissions_stmt::GetDescriptor(), msg);
  1141. }
  1142. void VisitRevokePermissions(const TRule_revoke_permissions_stmt& msg) {
  1143. NewLine();
  1144. VisitAllFields(TRule_revoke_permissions_stmt::GetDescriptor(), msg);
  1145. }
  1146. void VisitCreateUser(const TRule_create_user_stmt& msg) {
  1147. NewLine();
  1148. VisitAllFields(TRule_create_user_stmt::GetDescriptor(), msg);
  1149. }
  1150. void VisitAlterUser(const TRule_alter_user_stmt& msg) {
  1151. NewLine();
  1152. VisitAllFields(TRule_alter_user_stmt::GetDescriptor(), msg);
  1153. }
  1154. void VisitCreateGroup(const TRule_create_group_stmt& msg) {
  1155. NewLine();
  1156. VisitAllFields(TRule_create_group_stmt::GetDescriptor(), msg);
  1157. }
  1158. void VisitAlterGroup(const TRule_alter_group_stmt& msg) {
  1159. NewLine();
  1160. VisitAllFields(TRule_alter_group_stmt::GetDescriptor(), msg);
  1161. }
  1162. void VisitDropRole(const TRule_drop_role_stmt& msg) {
  1163. NewLine();
  1164. VisitAllFields(TRule_drop_role_stmt::GetDescriptor(), msg);
  1165. }
  1166. void VisitUpsertObject(const TRule_upsert_object_stmt& msg) {
  1167. NewLine();
  1168. VisitAllFields(TRule_upsert_object_stmt::GetDescriptor(), msg);
  1169. }
  1170. void VisitCreateObject(const TRule_create_object_stmt& msg) {
  1171. NewLine();
  1172. VisitAllFields(TRule_create_object_stmt::GetDescriptor(), msg);
  1173. }
  1174. void VisitAlterObject(const TRule_alter_object_stmt& msg) {
  1175. NewLine();
  1176. VisitAllFields(TRule_alter_object_stmt::GetDescriptor(), msg);
  1177. }
  1178. void VisitDropObject(const TRule_drop_object_stmt& msg) {
  1179. NewLine();
  1180. VisitAllFields(TRule_drop_object_stmt::GetDescriptor(), msg);
  1181. }
  1182. void VisitCreateTopic(const TRule_create_topic_stmt& msg) {
  1183. NewLine();
  1184. VisitKeyword(msg.GetToken1());
  1185. VisitKeyword(msg.GetToken2());
  1186. Visit(msg.GetBlock3());
  1187. Visit(msg.GetRule_topic_ref4());
  1188. if (msg.HasBlock5()) {
  1189. auto& b = msg.GetBlock5().GetRule_create_topic_entries1();
  1190. Visit(b.GetToken1());
  1191. NewLine();
  1192. PushCurrentIndent();
  1193. Visit(b.GetRule_create_topic_entry2());
  1194. for (auto& subEntry : b.GetBlock3()) {
  1195. Visit(subEntry.GetToken1());
  1196. NewLine();
  1197. Visit(subEntry.GetRule_create_topic_entry2());
  1198. }
  1199. NewLine();
  1200. PopCurrentIndent();
  1201. Visit(b.GetToken4());
  1202. }
  1203. if (msg.HasBlock6()) {
  1204. auto& b = msg.GetBlock6().GetRule_with_topic_settings1();
  1205. VisitKeyword(b.GetToken1());
  1206. VisitKeyword(b.GetToken2());
  1207. PushCurrentIndent();
  1208. NewLine();
  1209. Visit(b.GetRule_topic_settings3());
  1210. PopCurrentIndent();
  1211. NewLine();
  1212. VisitKeyword(b.GetToken4());
  1213. }
  1214. }
  1215. void VisitAlterTopic(const TRule_alter_topic_stmt& msg) {
  1216. NewLine();
  1217. VisitKeyword(msg.GetToken1());
  1218. VisitKeyword(msg.GetToken2());
  1219. Visit(msg.GetBlock3());
  1220. Visit(msg.GetRule_topic_ref4());
  1221. NewLine();
  1222. PushCurrentIndent();
  1223. Visit(msg.GetRule_alter_topic_action5());
  1224. for (auto& b : msg.GetBlock6()) {
  1225. Visit(b.GetToken1());
  1226. NewLine();
  1227. Visit(b.GetRule_alter_topic_action2());
  1228. }
  1229. PopCurrentIndent();
  1230. NewLine();
  1231. }
  1232. void VisitDropTopic(const TRule_drop_topic_stmt& msg) {
  1233. NewLine();
  1234. VisitAllFields(TRule_drop_topic_stmt::GetDescriptor(), msg);
  1235. }
  1236. void VisitCreateExternalDataSource(const TRule_create_external_data_source_stmt& msg) {
  1237. NewLine();
  1238. VisitAllFields(TRule_create_external_data_source_stmt::GetDescriptor(), msg);
  1239. }
  1240. void VisitAlterExternalDataSource(const TRule_alter_external_data_source_stmt& msg) {
  1241. NewLine();
  1242. VisitToken(msg.GetToken1());
  1243. VisitToken(msg.GetToken2());
  1244. VisitToken(msg.GetToken3());
  1245. VisitToken(msg.GetToken4());
  1246. Visit(msg.GetRule_object_ref5());
  1247. NewLine();
  1248. PushCurrentIndent();
  1249. Visit(msg.GetRule_alter_external_data_source_action6());
  1250. for (const auto& action : msg.GetBlock7()) {
  1251. Visit(action.GetToken1()); // comma
  1252. NewLine();
  1253. Visit(action.GetRule_alter_external_data_source_action2());
  1254. }
  1255. PopCurrentIndent();
  1256. NewLine();
  1257. }
  1258. void VisitDropExternalDataSource(const TRule_drop_external_data_source_stmt& msg) {
  1259. NewLine();
  1260. VisitAllFields(TRule_drop_external_data_source_stmt::GetDescriptor(), msg);
  1261. }
  1262. void VisitCreateView(const TRule_create_view_stmt& msg) {
  1263. NewLine();
  1264. VisitAllFields(TRule_create_view_stmt::GetDescriptor(), msg);
  1265. }
  1266. void VisitDropView(const TRule_drop_view_stmt& msg) {
  1267. NewLine();
  1268. VisitAllFields(TRule_drop_view_stmt::GetDescriptor(), msg);
  1269. }
  1270. void VisitCreateAsyncReplication(const TRule_create_replication_stmt& msg) {
  1271. NewLine();
  1272. VisitAllFields(TRule_create_replication_stmt::GetDescriptor(), msg);
  1273. }
  1274. void VisitAlterAsyncReplication(const TRule_alter_replication_stmt& msg) {
  1275. NewLine();
  1276. VisitAllFields(TRule_alter_replication_stmt::GetDescriptor(), msg);
  1277. }
  1278. void VisitDropAsyncReplication(const TRule_drop_replication_stmt& msg) {
  1279. NewLine();
  1280. VisitAllFields(TRule_drop_replication_stmt::GetDescriptor(), msg);
  1281. }
  1282. void VisitCreateTransfer(const TRule_create_transfer_stmt& msg) {
  1283. NewLine();
  1284. VisitAllFields(TRule_create_transfer_stmt::GetDescriptor(), msg);
  1285. }
  1286. void VisitAlterTransfer(const TRule_alter_transfer_stmt& msg) {
  1287. NewLine();
  1288. VisitAllFields(TRule_alter_transfer_stmt::GetDescriptor(), msg);
  1289. }
  1290. void VisitDropTransfer(const TRule_drop_transfer_stmt& msg) {
  1291. NewLine();
  1292. VisitAllFields(TRule_drop_transfer_stmt::GetDescriptor(), msg);
  1293. }
  1294. void VisitCreateResourcePool(const TRule_create_resource_pool_stmt& msg) {
  1295. NewLine();
  1296. VisitAllFields(TRule_create_resource_pool_stmt::GetDescriptor(), msg);
  1297. }
  1298. void VisitAlterResourcePool(const TRule_alter_resource_pool_stmt& msg) {
  1299. NewLine();
  1300. VisitToken(msg.GetToken1());
  1301. VisitToken(msg.GetToken2());
  1302. VisitToken(msg.GetToken3());
  1303. Visit(msg.GetRule_object_ref4());
  1304. NewLine();
  1305. PushCurrentIndent();
  1306. Visit(msg.GetRule_alter_resource_pool_action5());
  1307. for (const auto& action : msg.GetBlock6()) {
  1308. Visit(action.GetToken1()); // comma
  1309. NewLine();
  1310. Visit(action.GetRule_alter_resource_pool_action2());
  1311. }
  1312. PopCurrentIndent();
  1313. NewLine();
  1314. }
  1315. void VisitDropResourcePool(const TRule_drop_resource_pool_stmt& msg) {
  1316. NewLine();
  1317. VisitAllFields(TRule_drop_resource_pool_stmt::GetDescriptor(), msg);
  1318. }
  1319. void VisitCreateBackupCollection(const TRule_create_backup_collection_stmt& msg) {
  1320. NewLine();
  1321. VisitAllFields(TRule_create_backup_collection_stmt::GetDescriptor(), msg);
  1322. }
  1323. void VisitAlterBackupCollection(const TRule_alter_backup_collection_stmt& msg) {
  1324. NewLine();
  1325. VisitToken(msg.GetToken1());
  1326. Visit(msg.GetRule_backup_collection2());
  1327. NewLine();
  1328. PushCurrentIndent();
  1329. switch (msg.GetBlock3().Alt_case()) {
  1330. case TRule_alter_backup_collection_stmt_TBlock3::kAlt1: {
  1331. Visit(msg.GetBlock3().GetAlt1().GetRule_alter_backup_collection_actions1().GetRule_alter_backup_collection_action1());
  1332. for (const auto& action : msg.GetBlock3().GetAlt1().GetRule_alter_backup_collection_actions1().GetBlock2()) {
  1333. Visit(action.GetToken1()); // comma
  1334. NewLine();
  1335. Visit(action.GetRule_alter_backup_collection_action2());
  1336. }
  1337. break;
  1338. }
  1339. case TRule_alter_backup_collection_stmt_TBlock3::kAlt2: {
  1340. Visit(msg.GetBlock3().GetAlt2().GetRule_alter_backup_collection_entries1().GetRule_alter_backup_collection_entry1());
  1341. for (const auto& entry : msg.GetBlock3().GetAlt2().GetRule_alter_backup_collection_entries1().GetBlock2()) {
  1342. Visit(entry.GetToken1()); // comma
  1343. NewLine();
  1344. Visit(entry.GetRule_alter_backup_collection_entry2());
  1345. }
  1346. break;
  1347. }
  1348. default:
  1349. ythrow yexception() << "Alt is not supported";
  1350. }
  1351. PopCurrentIndent();
  1352. NewLine();
  1353. }
  1354. void VisitDropBackupCollection(const TRule_drop_backup_collection_stmt& msg) {
  1355. NewLine();
  1356. VisitAllFields(TRule_drop_backup_collection_stmt::GetDescriptor(), msg);
  1357. }
  1358. void VisitCreateResourcePoolClassifier(const TRule_create_resource_pool_classifier_stmt& msg) {
  1359. NewLine();
  1360. VisitAllFields(TRule_create_resource_pool_classifier_stmt::GetDescriptor(), msg);
  1361. }
  1362. void VisitAlterResourcePoolClassifier(const TRule_alter_resource_pool_classifier_stmt& msg) {
  1363. NewLine();
  1364. VisitToken(msg.GetToken1());
  1365. VisitToken(msg.GetToken2());
  1366. VisitToken(msg.GetToken3());
  1367. VisitToken(msg.GetToken4());
  1368. Visit(msg.GetRule_object_ref5());
  1369. NewLine();
  1370. PushCurrentIndent();
  1371. Visit(msg.GetRule_alter_resource_pool_classifier_action6());
  1372. for (const auto& action : msg.GetBlock7()) {
  1373. Visit(action.GetToken1()); // comma
  1374. NewLine();
  1375. Visit(action.GetRule_alter_resource_pool_classifier_action2());
  1376. }
  1377. PopCurrentIndent();
  1378. NewLine();
  1379. }
  1380. void VisitDropResourcePoolClassifier(const TRule_drop_resource_pool_classifier_stmt& msg) {
  1381. NewLine();
  1382. VisitAllFields(TRule_drop_resource_pool_classifier_stmt::GetDescriptor(), msg);
  1383. }
  1384. void VisitAllFields(const NProtoBuf::Descriptor* descr, const NProtoBuf::Message& msg) {
  1385. VisitAllFieldsImpl<TPrettyVisitor, &TPrettyVisitor::Visit>(this, descr, msg);
  1386. }
  1387. void WriteComments(bool completeLine) {
  1388. while (LastComment < Comments.size()) {
  1389. const auto& c = Comments[LastComment];
  1390. if (c.Line > LastLine || !completeLine && c.Line == LastLine && c.LinePos > LastColumn) {
  1391. break;
  1392. }
  1393. AddComment(c.Content);
  1394. ++LastComment;
  1395. }
  1396. }
  1397. void PosFromToken(const TToken& token) {
  1398. LastLine = token.GetLine();
  1399. LastColumn = token.GetColumn();
  1400. WriteComments(false);
  1401. }
  1402. void VisitToken(const TToken& token) {
  1403. VisitTokenImpl(token, false);
  1404. }
  1405. void VisitKeyword(const TToken& token) {
  1406. VisitTokenImpl(token, true);
  1407. }
  1408. void VisitTokenImpl(const TToken& token, bool forceKeyword) {
  1409. PosFromToken(token);
  1410. auto str = token.GetValue();
  1411. if (str == "<EOF>") {
  1412. return;
  1413. }
  1414. //Cerr << str << "\n";
  1415. auto currentScope = Scopes.back();
  1416. if (!SkipSpaceAfterUnaryOp && !InMultiTokenOp) {
  1417. if (AfterLess && str == ">") {
  1418. Out(' ');
  1419. } else if (AfterDigits && str == ".") {
  1420. Out(' ');
  1421. } else if (OutColumn && (currentScope == EScope::DoubleQuestion || str != "?")
  1422. && str != ":" && str != "." && str != "," && str != ";" && str != ")" && str != "]"
  1423. && str != "}" && str != "|>" && str != "::" && !AfterNamespace && !AfterBracket
  1424. && !AfterInvokeExpr && !AfterDollarOrAt && !AfterDot && (!AfterQuestion || str != "?")
  1425. && (!InsideType || (str != "<" && str != ">" && str != "<>"))
  1426. && (!InsideType || !AfterLess)
  1427. && (!AfterKeyExpr || str != "[")
  1428. ) {
  1429. Out(' ');
  1430. }
  1431. }
  1432. SkipSpaceAfterUnaryOp = false;
  1433. if (AfterUnaryOp) {
  1434. if (str == "+" || str == "-" || str == "~") {
  1435. SkipSpaceAfterUnaryOp = true;
  1436. }
  1437. AfterUnaryOp = false;
  1438. }
  1439. AfterInvokeExpr = false;
  1440. AfterNamespace = (str == "::");
  1441. AfterBracket = (str == "(" || str == "[" || str == "{" || str == "<|");
  1442. AfterDot = (str == ".");
  1443. AfterDigits = !str.empty() && AllOf(str, [](char c) { return c >= '0' && c <= '9'; });
  1444. AfterQuestion = (str == "?");
  1445. AfterLess = (str == "<");
  1446. AfterKeyExpr = false;
  1447. AfterComment = false;
  1448. if (forceKeyword) {
  1449. str = to_upper(str);
  1450. } else if (currentScope == EScope::Default) {
  1451. if (auto p = StaticData.Keywords.find(to_upper(str)); p != StaticData.Keywords.end()) {
  1452. str = *p;
  1453. }
  1454. }
  1455. AfterDollarOrAt = (str == "$" || str == "@");
  1456. const auto& markedInfo = MarkedTokens[TokenIndex];
  1457. if (markedInfo.ClosingBracket) {
  1458. Y_ENSURE(!MarkTokenStack.empty());
  1459. auto beginTokenIndex = MarkTokenStack.back();
  1460. if (markedInfo.BracketForcedExpansion || ParsedTokens[beginTokenIndex].Line != ParsedTokens[TokenIndex].Line) {
  1461. // multiline
  1462. PopCurrentIndent();
  1463. NewLine();
  1464. }
  1465. MarkTokenStack.pop_back();
  1466. }
  1467. if (InCondExpr) {
  1468. if (str == "=") {
  1469. str = "==";
  1470. } else if (str == "<>") {
  1471. str = "!=";
  1472. }
  1473. }
  1474. if (!AnsiLexer && ParsedTokens[TokenIndex].Name == "STRING_VALUE") {
  1475. TStringBuf checkStr = str;
  1476. if (checkStr.SkipPrefix("\"") && checkStr.ChopSuffix("\"") && !checkStr.Contains("'")) {
  1477. str = TStringBuilder() << '\'' << checkStr << '\'';
  1478. }
  1479. }
  1480. Out(str);
  1481. if (TokenIndex + 1 >= ParsedTokens.size() || ParsedTokens[TokenIndex + 1].Line > LastLine) {
  1482. WriteComments(true);
  1483. }
  1484. if (str == ";") {
  1485. NewLine();
  1486. }
  1487. if (markedInfo.OpeningBracket) {
  1488. MarkTokenStack.push_back(TokenIndex);
  1489. if (markedInfo.BracketForcedExpansion || ParsedTokens[TokenIndex].Line != ParsedTokens[markedInfo.ClosingBracketIndex].Line) {
  1490. // multiline
  1491. PushCurrentIndent();
  1492. NewLine();
  1493. }
  1494. }
  1495. if (str == "," && !MarkTokenStack.empty()) {
  1496. const bool addNewline =
  1497. (TokenIndex + 1 < ParsedTokens.size() && ParsedTokens[TokenIndex].Line != ParsedTokens[TokenIndex + 1].Line)
  1498. || (TokenIndex > 0 && ParsedTokens[TokenIndex - 1].Line != ParsedTokens[TokenIndex].Line);
  1499. // add line for trailing comma
  1500. if (addNewline) {
  1501. NewLine();
  1502. }
  1503. }
  1504. TokenIndex++;
  1505. }
  1506. void VisitIntoValuesSource(const TRule_into_values_source& msg) {
  1507. switch (msg.Alt_case()) {
  1508. case TRule_into_values_source::kAltIntoValuesSource1: {
  1509. const auto& alt = msg.GetAlt_into_values_source1();
  1510. if (alt.HasBlock1()) {
  1511. const auto& columns = alt.GetBlock1().GetRule_pure_column_list1();
  1512. Visit(columns.GetToken1());
  1513. NewLine();
  1514. PushCurrentIndent();
  1515. Visit(columns.GetRule_an_id2());
  1516. for (const auto& block : columns.GetBlock3()) {
  1517. Visit(block.GetToken1());
  1518. NewLine();
  1519. Visit(block.GetRule_an_id2());
  1520. }
  1521. PopCurrentIndent();
  1522. NewLine();
  1523. Visit(columns.GetToken4());
  1524. NewLine();
  1525. }
  1526. Visit(alt.GetRule_values_source2());
  1527. break;
  1528. }
  1529. case TRule_into_values_source::kAltIntoValuesSource2: {
  1530. VisitAllFields(TRule_into_values_source::GetDescriptor(), msg);
  1531. break;
  1532. }
  1533. default:
  1534. ythrow yexception() << "Alt is not supported";
  1535. }
  1536. }
  1537. void VisitSelectKind(const TRule_select_kind& msg) {
  1538. if (msg.HasBlock1()) {
  1539. Visit(msg.GetBlock1());
  1540. }
  1541. Visit(msg.GetBlock2());
  1542. if (msg.HasBlock3()) {
  1543. NewLine();
  1544. Visit(msg.GetBlock3());
  1545. }
  1546. }
  1547. void VisitProcessCore(const TRule_process_core& msg) {
  1548. Visit(msg.GetToken1());
  1549. if (msg.HasBlock2()) {
  1550. Visit(msg.GetBlock2());
  1551. }
  1552. Visit(msg.GetRule_named_single_source3());
  1553. VisitRepeated(msg.GetBlock4());
  1554. if (msg.HasBlock5()) {
  1555. NewLine();
  1556. const auto& block5 = msg.GetBlock5();
  1557. Visit(block5.GetToken1());
  1558. Visit(block5.GetRule_using_call_expr2());
  1559. if (block5.HasBlock3()) {
  1560. Visit(block5.GetBlock3());
  1561. }
  1562. if (block5.HasBlock4()) {
  1563. NewLine();
  1564. Visit(block5.GetBlock4());
  1565. }
  1566. if (block5.HasBlock5()) {
  1567. NewLine();
  1568. const auto& whereBlock = block5.GetBlock5();
  1569. Visit(whereBlock.GetToken1());
  1570. NewLine();
  1571. PushCurrentIndent();
  1572. Visit(whereBlock.GetRule_expr2());
  1573. PopCurrentIndent();
  1574. NewLine();
  1575. }
  1576. if (block5.HasBlock6()) {
  1577. NewLine();
  1578. const auto& havingBlock = block5.GetBlock6();
  1579. Visit(havingBlock.GetToken1());
  1580. NewLine();
  1581. PushCurrentIndent();
  1582. Visit(havingBlock.GetRule_expr2());
  1583. PopCurrentIndent();
  1584. NewLine();
  1585. }
  1586. if (block5.HasBlock7()) {
  1587. NewLine();
  1588. Visit(block5.GetBlock7());
  1589. }
  1590. }
  1591. }
  1592. void VisitReduceCore(const TRule_reduce_core& msg) {
  1593. Visit(msg.GetToken1());
  1594. Visit(msg.GetRule_named_single_source2());
  1595. VisitRepeated(msg.GetBlock3());
  1596. if (msg.HasBlock4()) {
  1597. NewLine();
  1598. Visit(msg.GetBlock4());
  1599. }
  1600. NewLine();
  1601. Visit(msg.GetToken5());
  1602. const auto& columns = msg.GetRule_column_list6();
  1603. NewLine();
  1604. PushCurrentIndent();
  1605. Visit(columns.GetRule_column_name1());
  1606. for (const auto& block : columns.GetBlock2()) {
  1607. Visit(block.GetToken1());
  1608. NewLine();
  1609. Visit(block.GetRule_column_name2());
  1610. }
  1611. if (columns.HasBlock3()) {
  1612. Visit(columns.GetBlock3());
  1613. }
  1614. PopCurrentIndent();
  1615. NewLine();
  1616. Visit(msg.GetToken7());
  1617. if (msg.HasBlock8()) {
  1618. Visit(msg.GetBlock8());
  1619. }
  1620. Visit(msg.GetRule_using_call_expr9());
  1621. if (msg.HasBlock10()) {
  1622. Visit(msg.GetBlock10());
  1623. }
  1624. if (msg.HasBlock11()) {
  1625. NewLine();
  1626. const auto& whereBlock = msg.GetBlock11();
  1627. Visit(whereBlock.GetToken1());
  1628. NewLine();
  1629. PushCurrentIndent();
  1630. Visit(whereBlock.GetRule_expr2());
  1631. PopCurrentIndent();
  1632. NewLine();
  1633. }
  1634. if (msg.HasBlock12()) {
  1635. NewLine();
  1636. const auto& havingBlock = msg.GetBlock12();
  1637. Visit(havingBlock.GetToken1());
  1638. NewLine();
  1639. PushCurrentIndent();
  1640. Visit(havingBlock.GetRule_expr2());
  1641. PopCurrentIndent();
  1642. NewLine();
  1643. }
  1644. if (msg.HasBlock13()) {
  1645. NewLine();
  1646. Visit(msg.GetBlock13());
  1647. }
  1648. }
  1649. void VisitSortSpecificationList(const TRule_sort_specification_list& msg) {
  1650. NewLine();
  1651. PushCurrentIndent();
  1652. Visit(msg.GetRule_sort_specification1());
  1653. for (const auto& block : msg.GetBlock2()) {
  1654. Visit(block.GetToken1());
  1655. NewLine();
  1656. Visit(block.GetRule_sort_specification2());
  1657. }
  1658. PopCurrentIndent();
  1659. NewLine();
  1660. }
  1661. void VisitSelectCore(const TRule_select_core& msg) {
  1662. if (msg.HasBlock1()) {
  1663. Visit(msg.GetBlock1());
  1664. NewLine();
  1665. }
  1666. Visit(msg.GetToken2());
  1667. if (msg.HasBlock3()) {
  1668. Visit(msg.GetBlock3());
  1669. }
  1670. Visit(msg.GetRule_opt_set_quantifier4());
  1671. NewLine();
  1672. PushCurrentIndent();
  1673. Visit(msg.GetRule_result_column5());
  1674. for (const auto& block : msg.GetBlock6()) {
  1675. Visit(block.GetToken1());
  1676. NewLine();
  1677. Visit(block.GetRule_result_column2());
  1678. }
  1679. if (msg.HasBlock7()) {
  1680. Visit(msg.GetBlock7());
  1681. }
  1682. PopCurrentIndent();
  1683. NewLine();
  1684. if (msg.HasBlock8()) {
  1685. NewLine();
  1686. Visit(msg.GetBlock8());
  1687. }
  1688. if (msg.HasBlock9()) {
  1689. NewLine();
  1690. Visit(msg.GetBlock9());
  1691. }
  1692. if (msg.HasBlock10()) {
  1693. NewLine();
  1694. const auto& whereBlock = msg.GetBlock10();
  1695. Visit(whereBlock.GetToken1());
  1696. NewLine();
  1697. PushCurrentIndent();
  1698. Visit(whereBlock.GetRule_expr2());
  1699. PopCurrentIndent();
  1700. NewLine();
  1701. }
  1702. if (msg.HasBlock11()) {
  1703. NewLine();
  1704. Visit(msg.GetBlock11());
  1705. }
  1706. if (msg.HasBlock12()) {
  1707. NewLine();
  1708. const auto& havingBlock = msg.GetBlock12();
  1709. Visit(havingBlock.GetToken1());
  1710. NewLine();
  1711. PushCurrentIndent();
  1712. Visit(havingBlock.GetRule_expr2());
  1713. PopCurrentIndent();
  1714. NewLine();
  1715. }
  1716. if (msg.HasBlock13()) {
  1717. NewLine();
  1718. Visit(msg.GetBlock13());
  1719. }
  1720. if (msg.HasBlock14()) {
  1721. NewLine();
  1722. Visit(msg.GetBlock14());
  1723. }
  1724. }
  1725. void VisitRowPatternRecognitionClause(const TRule_row_pattern_recognition_clause& msg) {
  1726. VisitToken(msg.GetToken1());
  1727. VisitToken(msg.GetToken2());
  1728. NewLine();
  1729. PushCurrentIndent();
  1730. if (msg.HasBlock3()) {
  1731. Visit(msg.GetBlock3());
  1732. NewLine();
  1733. }
  1734. if (msg.HasBlock4()) {
  1735. Visit(msg.GetBlock4());
  1736. NewLine();
  1737. }
  1738. if (msg.HasBlock5()) {
  1739. const auto& block = msg.GetBlock5().GetRule_row_pattern_measures1();
  1740. VisitToken(block.GetToken1());
  1741. NewLine();
  1742. PushCurrentIndent();
  1743. const auto& measureList = block.GetRule_row_pattern_measure_list2();
  1744. Visit(measureList.GetRule_row_pattern_measure_definition1());
  1745. for (const auto& measureDefinitionBlock : measureList.GetBlock2()) {
  1746. VisitToken(measureDefinitionBlock.GetToken1());
  1747. NewLine();
  1748. Visit(measureDefinitionBlock.GetRule_row_pattern_measure_definition2());
  1749. }
  1750. PopCurrentIndent();
  1751. NewLine();
  1752. }
  1753. if (msg.HasBlock6()) {
  1754. Visit(msg.GetBlock6());
  1755. NewLine();
  1756. }
  1757. const auto& common = msg.GetRule_row_pattern_common_syntax7();
  1758. if (common.HasBlock1()) {
  1759. Visit(common.GetBlock1());
  1760. NewLine();
  1761. }
  1762. if (common.HasBlock2()) {
  1763. Visit(common.GetBlock2());
  1764. }
  1765. VisitToken(common.GetToken3());
  1766. VisitToken(common.GetToken4());
  1767. Visit(common.GetRule_row_pattern5());
  1768. VisitToken(common.GetToken6());
  1769. NewLine();
  1770. if (common.HasBlock7()) {
  1771. const auto& block = common.GetBlock7().GetRule_row_pattern_subset_clause1();
  1772. VisitToken(block.GetToken1());
  1773. NewLine();
  1774. PushCurrentIndent();
  1775. const auto& subsetList = block.GetRule_row_pattern_subset_list2();
  1776. Visit(subsetList.GetRule_row_pattern_subset_item1());
  1777. for (const auto& subsetItemBlock : subsetList.GetBlock2()) {
  1778. VisitToken(subsetItemBlock.GetToken1());
  1779. NewLine();
  1780. Visit(subsetItemBlock.GetRule_row_pattern_subset_item2());
  1781. }
  1782. PopCurrentIndent();
  1783. NewLine();
  1784. }
  1785. VisitToken(common.GetToken8());
  1786. NewLine();
  1787. PushCurrentIndent();
  1788. const auto& definitionList = common.GetRule_row_pattern_definition_list9();
  1789. Visit(definitionList.GetRule_row_pattern_definition1());
  1790. for (const auto& definitionBlock : definitionList.GetBlock2()) {
  1791. VisitToken(definitionBlock.GetToken1());
  1792. NewLine();
  1793. Visit(definitionBlock.GetRule_row_pattern_definition2());
  1794. }
  1795. PopCurrentIndent();
  1796. NewLine();
  1797. PopCurrentIndent();
  1798. NewLine();
  1799. VisitToken(msg.GetToken8());
  1800. }
  1801. void VisitJoinSource(const TRule_join_source& msg) {
  1802. if (msg.HasBlock1()) {
  1803. Visit(msg.GetBlock1());
  1804. }
  1805. Visit(msg.GetRule_flatten_source2());
  1806. for (const auto& block : msg.GetBlock3()) {
  1807. NewLine();
  1808. Visit(block.GetRule_join_op1());
  1809. if (block.HasBlock2()) {
  1810. Visit(block.GetBlock2());
  1811. }
  1812. Visit(block.GetRule_flatten_source3());
  1813. if (block.HasBlock4()) {
  1814. NewLine();
  1815. Visit(block.GetBlock4());
  1816. }
  1817. }
  1818. }
  1819. void VisitJoinConstraint(const TRule_join_constraint& msg) {
  1820. if (msg.Alt_case() == TRule_join_constraint::kAltJoinConstraint1) {
  1821. const auto& alt = msg.GetAlt_join_constraint1();
  1822. Visit(alt.GetToken1());
  1823. NewLine();
  1824. PushCurrentIndent();
  1825. Visit(alt.GetRule_expr2());
  1826. PopCurrentIndent();
  1827. NewLine();
  1828. } else {
  1829. VisitAllFields(TRule_join_constraint::GetDescriptor(), msg);
  1830. }
  1831. }
  1832. void VisitSingleSource(const TRule_single_source& msg) {
  1833. switch (msg.Alt_case()) {
  1834. case TRule_single_source::kAltSingleSource1: {
  1835. const auto& alt = msg.GetAlt_single_source1();
  1836. Visit(alt);
  1837. break;
  1838. }
  1839. case TRule_single_source::kAltSingleSource2: {
  1840. const auto& alt = msg.GetAlt_single_source2();
  1841. Visit(alt.GetToken1());
  1842. NewLine();
  1843. PushCurrentIndent();
  1844. Visit(alt.GetRule_select_stmt2());
  1845. PopCurrentIndent();
  1846. NewLine();
  1847. Visit(alt.GetToken3());
  1848. break;
  1849. }
  1850. case TRule_single_source::kAltSingleSource3: {
  1851. const auto& alt = msg.GetAlt_single_source3();
  1852. Visit(alt.GetToken1());
  1853. NewLine();
  1854. PushCurrentIndent();
  1855. Visit(alt.GetRule_values_stmt2());
  1856. PopCurrentIndent();
  1857. NewLine();
  1858. Visit(alt.GetToken3());
  1859. break;
  1860. }
  1861. default:
  1862. ythrow yexception() << "Alt is not supported";
  1863. }
  1864. }
  1865. void VisitFlattenSource(const TRule_flatten_source& msg) {
  1866. const auto& namedSingleSource = msg.GetRule_named_single_source1();
  1867. bool indentBeforeSource = namedSingleSource.GetRule_single_source1().Alt_case() == TRule_single_source::kAltSingleSource1;
  1868. if (indentBeforeSource) {
  1869. NewLine();
  1870. PushCurrentIndent();
  1871. }
  1872. Visit(namedSingleSource);
  1873. if (indentBeforeSource) {
  1874. PopCurrentIndent();
  1875. NewLine();
  1876. }
  1877. if (msg.HasBlock2()) {
  1878. NewLine();
  1879. PushCurrentIndent();
  1880. Visit(msg.GetBlock2());
  1881. PopCurrentIndent();
  1882. NewLine();
  1883. }
  1884. }
  1885. void VisitNamedSingleSource(const TRule_named_single_source& msg) {
  1886. Visit(msg.GetRule_single_source1());
  1887. if (msg.HasBlock2()) {
  1888. Visit(msg.GetBlock2());
  1889. }
  1890. if (msg.HasBlock3()) {
  1891. const auto& block3 = msg.GetBlock3();
  1892. Visit(block3.GetBlock1());
  1893. if (block3.HasBlock2()) {
  1894. const auto& columns = block3.GetBlock2().GetRule_pure_column_list1();
  1895. Visit(columns.GetToken1());
  1896. NewLine();
  1897. PushCurrentIndent();
  1898. Visit(columns.GetRule_an_id2());
  1899. for (const auto& block : columns.GetBlock3()) {
  1900. Visit(block.GetToken1());
  1901. NewLine();
  1902. Visit(block.GetRule_an_id2());
  1903. }
  1904. NewLine();
  1905. PopCurrentIndent();
  1906. Visit(columns.GetToken4());
  1907. }
  1908. }
  1909. if (msg.HasBlock4()) {
  1910. NewLine();
  1911. Visit(msg.GetBlock4());
  1912. }
  1913. }
  1914. void VisitTableHints(const TRule_table_hints& msg) {
  1915. Visit(msg.GetToken1());
  1916. const auto& block2 = msg.GetBlock2();
  1917. if (block2.Alt_case() == TRule_table_hints::TBlock2::kAlt2) {
  1918. const auto& alt = block2.GetAlt2();
  1919. Visit(alt.GetToken1());
  1920. NewLine();
  1921. PushCurrentIndent();
  1922. Visit(alt.GetRule_table_hint2());
  1923. for (const auto& block : alt.GetBlock3()) {
  1924. Visit(block.GetToken1());
  1925. NewLine();
  1926. Visit(block.GetRule_table_hint2());
  1927. }
  1928. NewLine();
  1929. PopCurrentIndent();
  1930. Visit(alt.GetToken4());
  1931. } else {
  1932. Visit(block2);
  1933. }
  1934. }
  1935. void VisitSimpleTableRef(const TRule_simple_table_ref& msg) {
  1936. Visit(msg.GetRule_simple_table_ref_core1());
  1937. if (msg.HasBlock2()) {
  1938. Visit(msg.GetBlock2());
  1939. }
  1940. }
  1941. void VisitIntoSimpleTableRef(const TRule_into_simple_table_ref& msg) {
  1942. Visit(msg.GetRule_simple_table_ref1());
  1943. if (msg.HasBlock2()) {
  1944. const auto& block2 = msg.GetBlock2();
  1945. NewLine();
  1946. PushCurrentIndent();
  1947. Visit(block2.GetToken1());
  1948. Visit(block2.GetToken2());
  1949. const auto& columns = block2.GetRule_pure_column_list3();
  1950. Visit(columns.GetToken1());
  1951. NewLine();
  1952. PushCurrentIndent();
  1953. Visit(columns.GetRule_an_id2());
  1954. for (const auto& block : columns.GetBlock3()) {
  1955. Visit(block.GetToken1());
  1956. NewLine();
  1957. Visit(block.GetRule_an_id2());
  1958. }
  1959. PopCurrentIndent();
  1960. NewLine();
  1961. Visit(columns.GetToken4());
  1962. PopCurrentIndent();
  1963. }
  1964. }
  1965. void VisitSelectKindPartial(const TRule_select_kind_partial& msg) {
  1966. Visit(msg.GetRule_select_kind1());
  1967. if (msg.HasBlock2()) {
  1968. NewLine();
  1969. Visit(msg.GetBlock2());
  1970. }
  1971. }
  1972. void VisitFlattenByArg(const TRule_flatten_by_arg& msg) {
  1973. switch (msg.Alt_case()) {
  1974. case TRule_flatten_by_arg::kAltFlattenByArg1: {
  1975. const auto& alt = msg.GetAlt_flatten_by_arg1();
  1976. Visit(alt);
  1977. break;
  1978. }
  1979. case TRule_flatten_by_arg::kAltFlattenByArg2: {
  1980. const auto& alt = msg.GetAlt_flatten_by_arg2();
  1981. Visit(alt.GetToken1());
  1982. NewLine();
  1983. PushCurrentIndent();
  1984. const auto& exprs = alt.GetRule_named_expr_list2();
  1985. Visit(exprs.GetRule_named_expr1());
  1986. for (const auto& block : exprs.GetBlock2()) {
  1987. Visit(block.GetToken1());
  1988. NewLine();
  1989. Visit(block.GetRule_named_expr2());
  1990. }
  1991. if (alt.HasBlock3()) {
  1992. Visit(alt.GetBlock3());
  1993. }
  1994. NewLine();
  1995. PopCurrentIndent();
  1996. Visit(alt.GetToken4());
  1997. break;
  1998. }
  1999. default:
  2000. ythrow yexception() << "Alt is not supported";
  2001. }
  2002. }
  2003. void VisitWithoutColumnList(const TRule_without_column_list& msg) {
  2004. NewLine();
  2005. PushCurrentIndent();
  2006. Visit(msg.GetRule_without_column_name1());
  2007. for (const auto& block : msg.GetBlock2()) {
  2008. Visit(block.GetToken1());
  2009. NewLine();
  2010. Visit(block.GetRule_without_column_name2());
  2011. }
  2012. if (msg.HasBlock3()) {
  2013. Visit(msg.GetBlock3());
  2014. }
  2015. PopCurrentIndent();
  2016. NewLine();
  2017. }
  2018. void VisitTableRef(const TRule_table_ref& msg) {
  2019. if (msg.HasBlock1()) {
  2020. Visit(msg.GetBlock1());
  2021. }
  2022. if (msg.HasBlock2()) {
  2023. Visit(msg.GetBlock2());
  2024. }
  2025. const auto& block3 = msg.GetBlock3();
  2026. switch (block3.Alt_case()) {
  2027. case TRule_table_ref::TBlock3::kAlt1: {
  2028. const auto& alt = block3.GetAlt1();
  2029. const auto& key = alt.GetRule_table_key1();
  2030. Visit(key.GetRule_id_table_or_type1());
  2031. Visit(key.GetBlock2());
  2032. break;
  2033. }
  2034. case TRule_table_ref::TBlock3::kAlt2: {
  2035. const auto& alt = block3.GetAlt2();
  2036. Visit(alt.GetRule_an_id_expr1());
  2037. AfterInvokeExpr = true;
  2038. Visit(alt.GetToken2());
  2039. if (alt.HasBlock3()) {
  2040. Visit(alt.GetBlock3());
  2041. }
  2042. Visit(alt.GetToken4());
  2043. break;
  2044. }
  2045. case TRule_table_ref::TBlock3::kAlt3: {
  2046. const auto& alt = block3.GetAlt3();
  2047. Visit(alt.GetRule_bind_parameter1());
  2048. if (alt.HasBlock2()) {
  2049. AfterInvokeExpr = true;
  2050. Visit(alt.GetBlock2());
  2051. }
  2052. if (alt.HasBlock3()) {
  2053. Visit(alt.GetBlock3());
  2054. }
  2055. break;
  2056. }
  2057. default:
  2058. ythrow yexception() << "Alt is not supported";
  2059. }
  2060. if (msg.HasBlock4()) {
  2061. Visit(msg.GetBlock4());
  2062. }
  2063. }
  2064. void VisitGroupingElementList(const TRule_grouping_element_list& msg) {
  2065. NewLine();
  2066. PushCurrentIndent();
  2067. Visit(msg.GetRule_grouping_element1());
  2068. for (const auto& block : msg.GetBlock2()) {
  2069. Visit(block.GetToken1());
  2070. NewLine();
  2071. Visit(block.GetRule_grouping_element2());
  2072. }
  2073. PopCurrentIndent();
  2074. NewLine();
  2075. }
  2076. void VisitGroupByClause(const TRule_group_by_clause& msg) {
  2077. Visit(msg.GetToken1());
  2078. if (msg.HasBlock2()) {
  2079. Visit(msg.GetBlock2());
  2080. }
  2081. Visit(msg.GetToken3());
  2082. Visit(msg.GetRule_opt_set_quantifier4());
  2083. Visit(msg.GetRule_grouping_element_list5());
  2084. if (msg.HasBlock6()) {
  2085. NewLine();
  2086. PushCurrentIndent();
  2087. Visit(msg.GetBlock6());
  2088. PopCurrentIndent();
  2089. NewLine();
  2090. }
  2091. }
  2092. void VisitWindowDefinitionList(const TRule_window_definition_list& msg) {
  2093. NewLine();
  2094. PushCurrentIndent();
  2095. Visit(msg.GetRule_window_definition1());
  2096. for (const auto& block : msg.GetBlock2()) {
  2097. Visit(block.GetToken1());
  2098. NewLine();
  2099. Visit(block.GetRule_window_definition2());
  2100. }
  2101. PopCurrentIndent();
  2102. NewLine();
  2103. }
  2104. void VisitWindowSpecification(const TRule_window_specification& msg) {
  2105. Visit(msg.GetToken1());
  2106. const auto& details = msg.GetRule_window_specification_details2();
  2107. const bool needsNewline = details.HasBlock1() || details.HasBlock2() ||
  2108. details.HasBlock3() || details.HasBlock4();
  2109. if (needsNewline) {
  2110. NewLine();
  2111. PushCurrentIndent();
  2112. }
  2113. if (details.HasBlock1()) {
  2114. NewLine();
  2115. Visit(details.GetBlock1());
  2116. }
  2117. if (details.HasBlock2()) {
  2118. NewLine();
  2119. Visit(details.GetBlock2());
  2120. }
  2121. if (details.HasBlock3()) {
  2122. NewLine();
  2123. Visit(details.GetBlock3());
  2124. }
  2125. if (details.HasBlock4()) {
  2126. NewLine();
  2127. Visit(details.GetBlock4());
  2128. }
  2129. if (needsNewline) {
  2130. NewLine();
  2131. PopCurrentIndent();
  2132. }
  2133. Visit(msg.GetToken3());
  2134. }
  2135. void VisitWindowParitionClause(const TRule_window_partition_clause& msg) {
  2136. Visit(msg.GetToken1());
  2137. if (msg.HasBlock2()) {
  2138. Visit(msg.GetBlock2());
  2139. }
  2140. Visit(msg.GetToken3());
  2141. const auto& exprs = msg.GetRule_named_expr_list4();
  2142. PushCurrentIndent();
  2143. NewLine();
  2144. Visit(exprs.GetRule_named_expr1());
  2145. for (const auto& block : exprs.GetBlock2()) {
  2146. Visit(block.GetToken1());
  2147. NewLine();
  2148. Visit(block.GetRule_named_expr2());
  2149. }
  2150. PopCurrentIndent();
  2151. NewLine();
  2152. }
  2153. void VisitLambdaBody(const TRule_lambda_body& msg) {
  2154. PushCurrentIndent();
  2155. NewLine();
  2156. SkipSemicolons(msg.GetBlock1());
  2157. for (const auto& block : msg.GetBlock2()) {
  2158. Visit(block.GetRule_lambda_stmt1());
  2159. SkipSemicolons(block.GetBlock2(), /* printOne = */ true);
  2160. NewLine();
  2161. }
  2162. Visit(msg.GetToken3());
  2163. ExprLineIndent = CurrentIndent;
  2164. Visit(msg.GetRule_expr4());
  2165. SkipSemicolons(msg.GetBlock5(), /* printOne = */ true);
  2166. ExprLineIndent = 0;
  2167. PopCurrentIndent();
  2168. NewLine();
  2169. }
  2170. void VisitInAtomExpr(const TRule_in_atom_expr& msg) {
  2171. if (msg.Alt_case() == TRule_in_atom_expr::kAltInAtomExpr7) {
  2172. const auto& alt = msg.GetAlt_in_atom_expr7();
  2173. Visit(alt.GetToken1());
  2174. NewLine();
  2175. PushCurrentIndent();
  2176. Visit(alt.GetRule_select_stmt2());
  2177. NewLine();
  2178. PopCurrentIndent();
  2179. Visit(alt.GetToken3());
  2180. } else {
  2181. VisitAllFields(TRule_in_atom_expr::GetDescriptor(), msg);
  2182. }
  2183. }
  2184. void VisitSelectKindParenthesis(const TRule_select_kind_parenthesis& msg) {
  2185. if (msg.Alt_case() == TRule_select_kind_parenthesis::kAltSelectKindParenthesis2) {
  2186. const auto& alt = msg.GetAlt_select_kind_parenthesis2();
  2187. Visit(alt.GetToken1());
  2188. NewLine();
  2189. PushCurrentIndent();
  2190. Visit(alt.GetRule_select_kind_partial2());
  2191. PopCurrentIndent();
  2192. NewLine();
  2193. Visit(alt.GetToken3());
  2194. } else {
  2195. VisitAllFields(TRule_select_kind_parenthesis::GetDescriptor(), msg);
  2196. }
  2197. }
  2198. void VisitCastExpr(const TRule_cast_expr& msg) {
  2199. Visit(msg.GetToken1());
  2200. AfterInvokeExpr = true;
  2201. Visit(msg.GetToken2());
  2202. Visit(msg.GetRule_expr3());
  2203. Visit(msg.GetToken4());
  2204. Visit(msg.GetRule_type_name_or_bind5());
  2205. Visit(msg.GetToken6());
  2206. }
  2207. void VisitBitCastExpr(const TRule_bitcast_expr& msg) {
  2208. Visit(msg.GetToken1());
  2209. AfterInvokeExpr = true;
  2210. Visit(msg.GetToken2());
  2211. Visit(msg.GetRule_expr3());
  2212. Visit(msg.GetToken4());
  2213. Visit(msg.GetRule_type_name_simple5());
  2214. Visit(msg.GetToken6());
  2215. }
  2216. void VisitExtOrderByClause(const TRule_ext_order_by_clause& msg) {
  2217. if (msg.HasBlock1()) {
  2218. Visit(msg.GetBlock1());
  2219. }
  2220. Visit(msg.GetRule_order_by_clause2());
  2221. }
  2222. void VisitKeyExpr(const TRule_key_expr& msg) {
  2223. AfterKeyExpr = true;
  2224. VisitAllFields(TRule_key_expr::GetDescriptor(), msg);
  2225. }
  2226. void VisitExistsExpr(const TRule_exists_expr& msg) {
  2227. VisitKeyword(msg.GetToken1());
  2228. VisitToken(msg.GetToken2());
  2229. NewLine();
  2230. PushCurrentIndent();
  2231. Visit(msg.GetBlock3());
  2232. PopCurrentIndent();
  2233. NewLine();
  2234. VisitToken(msg.GetToken4());
  2235. }
  2236. void VisitCaseExpr(const TRule_case_expr& msg) {
  2237. VisitKeyword(msg.GetToken1());
  2238. if (msg.HasBlock2()) {
  2239. Visit(msg.GetBlock2());
  2240. }
  2241. NewLine();
  2242. PushCurrentIndent();
  2243. for (const auto& block : msg.GetBlock3()) {
  2244. Visit(block);
  2245. NewLine();
  2246. }
  2247. if (msg.HasBlock4()) {
  2248. const auto& block = msg.GetBlock4();
  2249. VisitKeyword(block.GetToken1());
  2250. Visit(block.GetRule_expr2());
  2251. }
  2252. PopCurrentIndent();
  2253. NewLine();
  2254. Visit(msg.GetToken5());
  2255. }
  2256. void VisitWithTableSettingsExpr(const TRule_with_table_settings& msg) {
  2257. VisitKeyword(msg.GetToken1());
  2258. Visit(msg.GetToken2());
  2259. const bool needIndent = msg.Block4Size() > 0; // more then one setting
  2260. if (needIndent) {
  2261. NewLine();
  2262. PushCurrentIndent();
  2263. Visit(msg.GetRule_table_settings_entry3()); // first setting
  2264. for (const auto& entry : msg.GetBlock4()) {
  2265. Visit(entry.GetToken1()); // comma
  2266. NewLine();
  2267. Visit(entry.GetRule_table_settings_entry2()); // other settings
  2268. }
  2269. PopCurrentIndent();
  2270. NewLine();
  2271. } else {
  2272. Visit(msg.GetRule_table_settings_entry3());
  2273. }
  2274. Visit(msg.GetToken5());
  2275. }
  2276. void VisitTableSettingValue(const TRule_table_setting_value& msg) {
  2277. switch (msg.GetAltCase()) {
  2278. case TRule_table_setting_value::kAltTableSettingValue5: {
  2279. // | ttl_tier_list ON an_id (AS (SECONDS | MILLISECONDS | MICROSECONDS | NANOSECONDS))?
  2280. const auto& ttlSettings = msg.GetAlt_table_setting_value5();
  2281. const auto& tierList = ttlSettings.GetRule_ttl_tier_list1();
  2282. const bool needIndent = tierList.HasBlock2() && tierList.GetBlock2().Block2Size() > 0; // more then one tier
  2283. if (needIndent) {
  2284. NewLine();
  2285. PushCurrentIndent();
  2286. Visit(tierList.GetRule_expr1());
  2287. VisitTtlTierAction(tierList.GetBlock2().GetRule_ttl_tier_action1());
  2288. for (const auto& tierEntry : tierList.GetBlock2().GetBlock2()) {
  2289. Visit(tierEntry.GetToken1()); // comma
  2290. NewLine();
  2291. Visit(tierEntry.GetRule_expr2());
  2292. VisitTtlTierAction(tierEntry.GetRule_ttl_tier_action3());
  2293. }
  2294. PopCurrentIndent();
  2295. NewLine();
  2296. } else {
  2297. Visit(tierList.GetRule_expr1());
  2298. if (tierList.HasBlock2()) {
  2299. VisitTtlTierAction(tierList.GetBlock2().GetRule_ttl_tier_action1());
  2300. }
  2301. }
  2302. VisitKeyword(ttlSettings.GetToken2());
  2303. Visit(ttlSettings.GetRule_an_id3());
  2304. if (ttlSettings.HasBlock4()) {
  2305. VisitKeyword(ttlSettings.GetBlock4().GetToken1());
  2306. VisitKeyword(ttlSettings.GetBlock4().GetToken2());
  2307. }
  2308. } break;
  2309. default:
  2310. VisitAllFields(TRule_table_setting_value::GetDescriptor(), msg);
  2311. }
  2312. }
  2313. void VisitTtlTierAction(const TRule_ttl_tier_action& msg) {
  2314. switch (msg.GetAltCase()) {
  2315. case TRule_ttl_tier_action::kAltTtlTierAction1:
  2316. // | TO EXTERNAL DATA SOURCE an_id
  2317. VisitKeyword(msg.GetAlt_ttl_tier_action1().GetToken1());
  2318. VisitKeyword(msg.GetAlt_ttl_tier_action1().GetToken2());
  2319. VisitKeyword(msg.GetAlt_ttl_tier_action1().GetToken3());
  2320. VisitKeyword(msg.GetAlt_ttl_tier_action1().GetToken4());
  2321. Visit(msg.GetAlt_ttl_tier_action1().GetRule_an_id5());
  2322. break;
  2323. case TRule_ttl_tier_action::kAltTtlTierAction2:
  2324. // | DELETE
  2325. VisitKeyword(msg.GetAlt_ttl_tier_action2().GetToken1());
  2326. break;
  2327. case TRule_ttl_tier_action::ALT_NOT_SET:
  2328. break;
  2329. }
  2330. }
  2331. void VisitExpr(const TRule_expr& msg) {
  2332. if (msg.HasAlt_expr2()) {
  2333. Visit(msg.GetAlt_expr2());
  2334. return;
  2335. }
  2336. const auto& orExpr = msg.GetAlt_expr1();
  2337. auto getExpr = [](const TRule_expr::TAlt1::TBlock2& b) -> const TRule_or_subexpr& { return b.GetRule_or_subexpr2(); };
  2338. auto getOp = [](const TRule_expr::TAlt1::TBlock2& b) -> const TToken& { return b.GetToken1(); };
  2339. VisitBinaryOp(orExpr.GetRule_or_subexpr1(), getOp, getExpr, orExpr.GetBlock2().begin(), orExpr.GetBlock2().end());
  2340. }
  2341. void VisitCondExpr(const TRule_cond_expr& msg) {
  2342. if (msg.Alt_case() == TRule_cond_expr::kAltCondExpr5) {
  2343. for (const auto& block : msg.GetAlt_cond_expr5().GetBlock1()) {
  2344. InCondExpr = true;
  2345. Visit(block.GetBlock1());
  2346. InCondExpr = false;
  2347. Visit(block.GetRule_eq_subexpr2());
  2348. }
  2349. } else {
  2350. VisitAllFields(TRule_cond_expr::GetDescriptor(), msg);
  2351. }
  2352. }
  2353. void VisitOrSubexpr(const TRule_or_subexpr& msg) {
  2354. auto getExpr = [](const TRule_or_subexpr::TBlock2& b) -> const TRule_and_subexpr& { return b.GetRule_and_subexpr2(); };
  2355. auto getOp = [](const TRule_or_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
  2356. VisitBinaryOp(msg.GetRule_and_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
  2357. }
  2358. void VisitAndSubexpr(const TRule_and_subexpr& msg) {
  2359. auto getExpr = [](const TRule_and_subexpr::TBlock2& b) -> const TRule_xor_subexpr& { return b.GetRule_xor_subexpr2(); };
  2360. auto getOp = [](const TRule_and_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
  2361. VisitBinaryOp(msg.GetRule_xor_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
  2362. }
  2363. void VisitEqSubexpr(const TRule_eq_subexpr& msg) {
  2364. auto getExpr = [](const TRule_eq_subexpr::TBlock2& b) -> const TRule_neq_subexpr& { return b.GetRule_neq_subexpr2(); };
  2365. auto getOp = [](const TRule_eq_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
  2366. VisitBinaryOp(msg.GetRule_neq_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
  2367. }
  2368. void VisitNeqSubexpr(const TRule_neq_subexpr& msg) {
  2369. bool pushedIndent = false;
  2370. VisitNeqSubexprImpl(msg, pushedIndent, true);
  2371. }
  2372. void VisitNeqSubexprImpl(const TRule_neq_subexpr& msg, bool& pushedIndent, bool top) {
  2373. auto getExpr = [](const TRule_neq_subexpr::TBlock2& b) -> const TRule_bit_subexpr& { return b.GetRule_bit_subexpr2(); };
  2374. auto getOp = [](const TRule_neq_subexpr::TBlock2& b) -> const TRule_neq_subexpr::TBlock2::TBlock1& { return b.GetBlock1(); };
  2375. VisitBinaryOp(msg.GetRule_bit_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
  2376. if (msg.HasBlock3()) {
  2377. const auto& b = msg.GetBlock3();
  2378. switch (b.Alt_case()) {
  2379. case TRule_neq_subexpr_TBlock3::kAlt1: {
  2380. const auto& alt = b.GetAlt1();
  2381. const bool hasFirstNewline = LastLine != ParsedTokens[TokenIndex].Line;
  2382. // 2 is `??` size in tokens
  2383. const bool hasSecondNewline = ParsedTokens[TokenIndex].Line != ParsedTokens[TokenIndex + 2].Line;
  2384. const ui32 currentOutLine = OutLine;
  2385. if (currentOutLine != OutLine || (hasFirstNewline && hasSecondNewline)) {
  2386. NewLine();
  2387. if (!pushedIndent) {
  2388. PushCurrentIndent();
  2389. pushedIndent = true;
  2390. }
  2391. }
  2392. Visit(alt.GetRule_double_question1());
  2393. if (hasFirstNewline || hasSecondNewline) {
  2394. NewLine();
  2395. if (!pushedIndent) {
  2396. PushCurrentIndent();
  2397. pushedIndent = true;
  2398. }
  2399. }
  2400. VisitNeqSubexprImpl(alt.GetRule_neq_subexpr2(), pushedIndent, false);
  2401. if (pushedIndent && top) {
  2402. PopCurrentIndent();
  2403. pushedIndent = false;
  2404. }
  2405. break;
  2406. }
  2407. case TRule_neq_subexpr_TBlock3::kAlt2:
  2408. Visit(b.GetAlt2());
  2409. break;
  2410. default:
  2411. ythrow yexception() << "Alt is not supported";
  2412. }
  2413. }
  2414. }
  2415. void VisitBitSubexpr(const TRule_bit_subexpr& msg) {
  2416. auto getExpr = [](const TRule_bit_subexpr::TBlock2& b) -> const TRule_add_subexpr& { return b.GetRule_add_subexpr2(); };
  2417. auto getOp = [](const TRule_bit_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
  2418. VisitBinaryOp(msg.GetRule_add_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
  2419. }
  2420. void VisitAddSubexpr(const TRule_add_subexpr& msg) {
  2421. auto getExpr = [](const TRule_add_subexpr::TBlock2& b) -> const TRule_mul_subexpr& { return b.GetRule_mul_subexpr2(); };
  2422. auto getOp = [](const TRule_add_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
  2423. VisitBinaryOp(msg.GetRule_mul_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
  2424. }
  2425. void VisitMulSubexpr(const TRule_mul_subexpr& msg) {
  2426. auto getExpr = [](const TRule_mul_subexpr::TBlock2& b) -> const TRule_con_subexpr& { return b.GetRule_con_subexpr2(); };
  2427. auto getOp = [](const TRule_mul_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
  2428. VisitBinaryOp(msg.GetRule_con_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
  2429. }
  2430. ui32 BinaryOpTokenSize(const TToken&) {
  2431. return 1;
  2432. }
  2433. ui32 BinaryOpTokenSize(const TRule_neq_subexpr::TBlock2::TBlock1& block) {
  2434. switch (block.Alt_case()) {
  2435. case TRule_neq_subexpr::TBlock2::TBlock1::kAlt1:
  2436. case TRule_neq_subexpr::TBlock2::TBlock1::kAlt3:
  2437. case TRule_neq_subexpr::TBlock2::TBlock1::kAlt5:
  2438. case TRule_neq_subexpr::TBlock2::TBlock1::kAlt6:
  2439. case TRule_neq_subexpr::TBlock2::TBlock1::kAlt7:
  2440. return 1;
  2441. case TRule_neq_subexpr::TBlock2::TBlock1::kAlt2:
  2442. return 2;
  2443. case TRule_neq_subexpr::TBlock2::TBlock1::kAlt4:
  2444. return 3;
  2445. default:
  2446. ythrow yexception() << "Alt is not supported";
  2447. }
  2448. }
  2449. void VisitShiftRight(const TRule_shift_right& msg) {
  2450. VisitToken(msg.GetToken1());
  2451. InMultiTokenOp = true;
  2452. VisitToken(msg.GetToken2());
  2453. InMultiTokenOp = false;
  2454. }
  2455. void VisitRotRight(const TRule_rot_right& msg) {
  2456. VisitToken(msg.GetToken1());
  2457. InMultiTokenOp = true;
  2458. VisitToken(msg.GetToken2());
  2459. VisitToken(msg.GetToken3());
  2460. InMultiTokenOp = false;
  2461. }
  2462. template <typename TExpr, typename TGetOp, typename TGetExpr, typename TIter>
  2463. void VisitBinaryOp(const TExpr& expr, TGetOp getOp, TGetExpr getExpr, TIter begin, TIter end) {
  2464. Visit(expr);
  2465. bool pushedIndent = false;
  2466. for (; begin != end; ++begin) {
  2467. const auto op = getOp(*begin);
  2468. const auto opSize = BinaryOpTokenSize(op);
  2469. const bool hasFirstNewline = LastLine != ParsedTokens[TokenIndex].Line;
  2470. const bool hasSecondNewline = ParsedTokens[TokenIndex].Line != ParsedTokens[TokenIndex + opSize].Line;
  2471. const ui32 currentOutLine = OutLine;
  2472. if (currentOutLine != OutLine || hasFirstNewline || hasSecondNewline) {
  2473. NewLine();
  2474. if (!pushedIndent && CurrentIndent == ExprLineIndent) {
  2475. PushCurrentIndent();
  2476. pushedIndent = true;
  2477. }
  2478. }
  2479. Visit(op);
  2480. if (hasFirstNewline && hasSecondNewline) {
  2481. NewLine();
  2482. }
  2483. Visit(getExpr(*begin));
  2484. }
  2485. if (pushedIndent) {
  2486. PopCurrentIndent();
  2487. }
  2488. }
  2489. void PushCurrentIndent() {
  2490. CurrentIndent += OneIndent;
  2491. BlockFirstLine = OutLine;
  2492. if (OutColumn > 0) {
  2493. ++BlockFirstLine;
  2494. }
  2495. }
  2496. void PopCurrentIndent() {
  2497. CurrentIndent -= OneIndent;
  2498. }
  2499. private:
  2500. const TStaticData& StaticData;
  2501. const TParsedTokenList& ParsedTokens;
  2502. const TParsedTokenList& Comments;
  2503. const bool AnsiLexer;
  2504. TStringBuilder SB;
  2505. ui32 OutColumn = 0;
  2506. ui32 OutLine = 1;
  2507. ui32 LastLine = 0;
  2508. ui32 LastColumn = 0;
  2509. ui32 LastComment = 0;
  2510. ui32 CommentLines = 0;
  2511. i32 CurrentIndent = 0;
  2512. TVector<EScope> Scopes;
  2513. TMaybe<bool> AddLine;
  2514. TMaybe<ui32> StmtCoreAltCase;
  2515. ui64 InsideType = 0;
  2516. bool AfterNamespace = false;
  2517. bool AfterBracket = false;
  2518. bool AfterInvokeExpr = false;
  2519. bool AfterUnaryOp = false;
  2520. bool SkipSpaceAfterUnaryOp = false;
  2521. bool AfterDollarOrAt = false;
  2522. bool AfterDot = false;
  2523. bool AfterDigits = false;
  2524. bool AfterQuestion = false;
  2525. bool AfterLess = false;
  2526. bool AfterKeyExpr = false;
  2527. bool AfterComment = false;
  2528. bool InMultiTokenOp = false;
  2529. bool InCondExpr = false;
  2530. ui32 ForceExpandedLine = 0;
  2531. ui32 ForceExpandedColumn = 0;
  2532. ui32 BlockFirstLine = 1;
  2533. i32 ExprLineIndent = 0;
  2534. ui32 TokenIndex = 0;
  2535. TMarkTokenStack MarkTokenStack;
  2536. TVector<TTokenInfo> MarkedTokens;
  2537. ui64 InsideExpr = 0;
  2538. };
  2539. template <typename T>
  2540. TPrettyFunctor MakePrettyFunctor(void (TPrettyVisitor::*memberPtr)(const T& msg)) {
  2541. return [memberPtr](TPrettyVisitor& visitor, const NProtoBuf::Message& rawMsg) {
  2542. (visitor.*memberPtr)(dynamic_cast<const T&>(rawMsg));
  2543. };
  2544. }
  2545. template <typename T>
  2546. TObfuscatingFunctor MakeObfuscatingFunctor(void (TObfuscatingVisitor::*memberPtr)(const T& msg)) {
  2547. return [memberPtr](TObfuscatingVisitor& visitor, const NProtoBuf::Message& rawMsg) {
  2548. (visitor.*memberPtr)(dynamic_cast<const T&>(rawMsg));
  2549. };
  2550. }
  2551. TStaticData::TStaticData()
  2552. : Keywords(GetKeywords())
  2553. , ScopeDispatch({
  2554. {TRule_type_name::GetDescriptor(), EScope::TypeName},
  2555. {TRule_type_name_composite::GetDescriptor(), EScope::TypeName},
  2556. {TRule_double_question::GetDescriptor(), EScope::DoubleQuestion},
  2557. {TRule_id::GetDescriptor(), EScope::Identifier},
  2558. {TRule_id_or_type::GetDescriptor(), EScope::Identifier},
  2559. {TRule_id_schema::GetDescriptor(), EScope::Identifier},
  2560. {TRule_id_expr::GetDescriptor(), EScope::Identifier},
  2561. {TRule_id_expr_in::GetDescriptor(), EScope::Identifier},
  2562. {TRule_id_window::GetDescriptor(), EScope::Identifier},
  2563. {TRule_id_table::GetDescriptor(), EScope::Identifier},
  2564. {TRule_id_without::GetDescriptor(), EScope::Identifier},
  2565. {TRule_id_hint::GetDescriptor(), EScope::Identifier},
  2566. {TRule_identifier::GetDescriptor(), EScope::Identifier},
  2567. {TRule_id_table_or_type::GetDescriptor(), EScope::Identifier},
  2568. {TRule_bind_parameter::GetDescriptor(), EScope::Identifier},
  2569. {TRule_an_id_as_compat::GetDescriptor(), EScope::Identifier},
  2570. })
  2571. , PrettyVisitDispatch({
  2572. {TToken::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitToken)},
  2573. {TRule_value_constructor::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitValueConstructor)},
  2574. {TRule_into_values_source::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitIntoValuesSource)},
  2575. {TRule_select_kind::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelectKind)},
  2576. {TRule_process_core::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitProcessCore)},
  2577. {TRule_reduce_core::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitReduceCore)},
  2578. {TRule_sort_specification_list::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSortSpecificationList)},
  2579. {TRule_select_core::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelectCore)},
  2580. {TRule_row_pattern_recognition_clause::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitRowPatternRecognitionClause)},
  2581. {TRule_join_source::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitJoinSource)},
  2582. {TRule_join_constraint::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitJoinConstraint)},
  2583. {TRule_single_source::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSingleSource)},
  2584. {TRule_flatten_source::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitFlattenSource)},
  2585. {TRule_named_single_source::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitNamedSingleSource)},
  2586. {TRule_table_hints::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitTableHints)},
  2587. {TRule_simple_table_ref::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSimpleTableRef)},
  2588. {TRule_into_simple_table_ref::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitIntoSimpleTableRef)},
  2589. {TRule_select_kind_partial::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelectKindPartial)},
  2590. {TRule_flatten_by_arg::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitFlattenByArg)},
  2591. {TRule_without_column_list::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWithoutColumnList)},
  2592. {TRule_table_ref::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitTableRef)},
  2593. {TRule_grouping_element_list::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitGroupingElementList)},
  2594. {TRule_group_by_clause::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitGroupByClause)},
  2595. {TRule_window_definition_list::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWindowDefinitionList)},
  2596. {TRule_window_specification::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWindowSpecification)},
  2597. {TRule_window_partition_clause::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWindowParitionClause)},
  2598. {TRule_lambda_body::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitLambdaBody)},
  2599. {TRule_in_atom_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitInAtomExpr)},
  2600. {TRule_select_kind_parenthesis::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelectKindParenthesis)},
  2601. {TRule_cast_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCastExpr)},
  2602. {TRule_bitcast_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitBitCastExpr)},
  2603. {TRule_ext_order_by_clause::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitExtOrderByClause)},
  2604. {TRule_key_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitKeyExpr)},
  2605. {TRule_define_action_or_subquery_body::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDefineActionOrSubqueryBody)},
  2606. {TRule_exists_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitExistsExpr)},
  2607. {TRule_case_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCaseExpr)},
  2608. {TRule_with_table_settings::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWithTableSettingsExpr)},
  2609. {TRule_table_setting_value::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitTableSettingValue)},
  2610. {TRule_ttl_tier_action::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitTtlTierAction)},
  2611. {TRule_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitExpr)},
  2612. {TRule_cond_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCondExpr)},
  2613. {TRule_or_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitOrSubexpr)},
  2614. {TRule_and_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAndSubexpr)},
  2615. {TRule_eq_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitEqSubexpr)},
  2616. {TRule_neq_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitNeqSubexpr)},
  2617. {TRule_bit_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitBitSubexpr)},
  2618. {TRule_add_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAddSubexpr)},
  2619. {TRule_mul_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitMulSubexpr)},
  2620. {TRule_rot_right::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitRotRight)},
  2621. {TRule_shift_right::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitShiftRight)},
  2622. {TRule_pragma_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitPragma)},
  2623. {TRule_select_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelect)},
  2624. {TRule_select_unparenthesized_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelectUnparenthesized)},
  2625. {TRule_named_nodes_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitNamedNodes)},
  2626. {TRule_create_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateTable)},
  2627. {TRule_drop_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropTable)},
  2628. {TRule_use_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitUse)},
  2629. {TRule_into_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitIntoTable)},
  2630. {TRule_commit_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCommit)},
  2631. {TRule_update_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitUpdate)},
  2632. {TRule_delete_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDelete)},
  2633. {TRule_rollback_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitRollback)},
  2634. {TRule_declare_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDeclare)},
  2635. {TRule_import_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitImport)},
  2636. {TRule_export_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitExport)},
  2637. {TRule_alter_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterTable)},
  2638. {TRule_alter_external_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterExternalTable)},
  2639. {TRule_do_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDo)},
  2640. {TRule_define_action_or_subquery_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAction)},
  2641. {TRule_if_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitIf)},
  2642. {TRule_for_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitFor)},
  2643. {TRule_values_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitValues)},
  2644. {TRule_create_user_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateUser)},
  2645. {TRule_alter_user_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterUser)},
  2646. {TRule_create_group_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateGroup)},
  2647. {TRule_alter_group_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterGroup)},
  2648. {TRule_drop_role_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropRole)},
  2649. {TRule_upsert_object_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitUpsertObject)},
  2650. {TRule_create_object_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateObject)},
  2651. {TRule_alter_object_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterObject)},
  2652. {TRule_drop_object_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropObject)},
  2653. {TRule_create_external_data_source_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateExternalDataSource)},
  2654. {TRule_alter_external_data_source_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterExternalDataSource)},
  2655. {TRule_drop_external_data_source_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropExternalDataSource)},
  2656. {TRule_create_replication_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateAsyncReplication)},
  2657. {TRule_alter_replication_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterAsyncReplication)},
  2658. {TRule_drop_replication_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropAsyncReplication)},
  2659. {TRule_create_transfer_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateTransfer)},
  2660. {TRule_alter_transfer_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterTransfer)},
  2661. {TRule_drop_transfer_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropTransfer)},
  2662. {TRule_create_topic_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateTopic)},
  2663. {TRule_alter_topic_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterTopic)},
  2664. {TRule_drop_topic_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropTopic)},
  2665. {TRule_grant_permissions_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitGrantPermissions)},
  2666. {TRule_revoke_permissions_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitRevokePermissions)},
  2667. {TRule_alter_table_store_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterTableStore)},
  2668. {TRule_create_view_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateView)},
  2669. {TRule_drop_view_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropView)},
  2670. {TRule_create_resource_pool_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateResourcePool)},
  2671. {TRule_alter_resource_pool_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterResourcePool)},
  2672. {TRule_drop_resource_pool_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropResourcePool)},
  2673. {TRule_create_backup_collection_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateBackupCollection)},
  2674. {TRule_alter_backup_collection_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterBackupCollection)},
  2675. {TRule_drop_backup_collection_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropBackupCollection)},
  2676. {TRule_analyze_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAnalyze)},
  2677. {TRule_create_resource_pool_classifier_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateResourcePoolClassifier)},
  2678. {TRule_alter_resource_pool_classifier_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterResourcePoolClassifier)},
  2679. {TRule_drop_resource_pool_classifier_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropResourcePoolClassifier)},
  2680. {TRule_backup_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitBackup)},
  2681. {TRule_restore_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitRestore)},
  2682. {TRule_alter_sequence_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterSequence)},
  2683. {TRule_alter_database_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterDatabase)},
  2684. {TRule_show_create_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitShowCreateTable)},
  2685. })
  2686. , ObfuscatingVisitDispatch({
  2687. {TToken::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitToken)},
  2688. {TRule_literal_value::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitLiteralValue)},
  2689. {TRule_pragma_value::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitPragmaValue)},
  2690. {TRule_atom_expr::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitAtomExpr)},
  2691. {TRule_in_atom_expr::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitInAtomExpr)},
  2692. {TRule_unary_casual_subexpr::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitUnaryCasualSubexpr)},
  2693. {TRule_in_unary_casual_subexpr::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitInUnaryCasualSubexpr)},
  2694. })
  2695. {
  2696. // ensure that all statements have a visitor
  2697. auto coreDescr = TRule_sql_stmt_core::GetDescriptor();
  2698. for (int i = 0; i < coreDescr->field_count(); ++i) {
  2699. const NProtoBuf::FieldDescriptor* fd = coreDescr->field(i);
  2700. if (fd->cpp_type() != NProtoBuf::FieldDescriptor::CPPTYPE_MESSAGE) {
  2701. continue;
  2702. }
  2703. auto altDescr = fd->message_type();
  2704. for (int j = 0; j < altDescr->field_count(); ++j) {
  2705. auto fd2 = altDescr->field(j);
  2706. if (fd2->cpp_type() != NProtoBuf::FieldDescriptor::CPPTYPE_MESSAGE) {
  2707. continue;
  2708. }
  2709. auto stmtMessage = fd2->message_type();
  2710. Y_ENSURE(PrettyVisitDispatch.contains(stmtMessage), TStringBuilder() << "Missing visitor for " << stmtMessage->name());
  2711. }
  2712. }
  2713. }
  2714. class TSqlFormatter : public NSQLFormat::ISqlFormatter {
  2715. public:
  2716. TSqlFormatter(const NSQLTranslationV1::TLexers& lexers,
  2717. const NSQLTranslationV1::TParsers& parsers,
  2718. const NSQLTranslation::TTranslationSettings& settings)
  2719. : Lexers(lexers)
  2720. , Parsers(parsers)
  2721. , Settings(settings)
  2722. {}
  2723. bool Format(const TString& query, TString& formattedQuery, NYql::TIssues& issues, EFormatMode mode) override {
  2724. formattedQuery = (mode == EFormatMode::Obfuscate) ? "" : query;
  2725. auto parsedSettings = Settings;
  2726. if (!NSQLTranslation::ParseTranslationSettings(query, parsedSettings, issues)) {
  2727. return false;
  2728. }
  2729. if (parsedSettings.PgParser) {
  2730. return mode != EFormatMode::Obfuscate;
  2731. }
  2732. if (mode == EFormatMode::Obfuscate) {
  2733. auto message = NSQLTranslationV1::SqlAST(Parsers, query, parsedSettings.File, issues, NSQLTranslation::SQL_MAX_PARSER_ERRORS, parsedSettings.AnsiLexer, parsedSettings.Antlr4Parser, parsedSettings.Arena);
  2734. if (!message) {
  2735. return false;
  2736. }
  2737. TObfuscatingVisitor visitor;
  2738. return Format(visitor.Process(*message), formattedQuery, issues, EFormatMode::Pretty);
  2739. }
  2740. auto lexer = NSQLTranslationV1::MakeLexer(Lexers, parsedSettings.AnsiLexer, parsedSettings.Antlr4Parser);
  2741. TVector<TString> statements;
  2742. if (!NSQLTranslationV1::SplitQueryToStatements(query, lexer, statements, issues, parsedSettings.File)) {
  2743. return false;
  2744. }
  2745. TStringBuilder finalFormattedQuery;
  2746. bool prevAddLine = false;
  2747. TMaybe<ui32> prevStmtCoreAltCase;
  2748. for (const TString& currentQuery : statements) {
  2749. TVector<NSQLTranslation::TParsedToken> comments;
  2750. TParsedTokenList parsedTokens, stmtTokens;
  2751. auto onNextRawToken = [&](NSQLTranslation::TParsedToken&& token) {
  2752. stmtTokens.push_back(token);
  2753. if (token.Name == "COMMENT") {
  2754. comments.emplace_back(std::move(token));
  2755. } else if (token.Name != "WS" && token.Name != "EOF") {
  2756. parsedTokens.emplace_back(std::move(token));
  2757. }
  2758. };
  2759. if (!lexer->Tokenize(currentQuery, parsedSettings.File, onNextRawToken, issues, NSQLTranslation::SQL_MAX_PARSER_ERRORS)) {
  2760. return false;
  2761. }
  2762. NYql::TIssues parserIssues;
  2763. auto message = NSQLTranslationV1::SqlAST(Parsers, currentQuery, parsedSettings.File, parserIssues, NSQLTranslation::SQL_MAX_PARSER_ERRORS, parsedSettings.AnsiLexer, parsedSettings.Antlr4Parser, parsedSettings.Arena);
  2764. if (!message) {
  2765. finalFormattedQuery << currentQuery;
  2766. if (!currentQuery.EndsWith("\n")) {
  2767. finalFormattedQuery << "\n";
  2768. }
  2769. continue;
  2770. }
  2771. TPrettyVisitor visitor(parsedTokens, comments, parsedSettings.AnsiLexer);
  2772. bool addLineBefore = false;
  2773. bool addLineAfter = false;
  2774. TMaybe<ui32> stmtCoreAltCase;
  2775. auto currentFormattedQuery = visitor.Process(*message, addLineBefore, addLineAfter, stmtCoreAltCase);
  2776. TParsedTokenList stmtFormattedTokens;
  2777. auto onNextFormattedToken = [&](NSQLTranslation::TParsedToken&& token) {
  2778. stmtFormattedTokens.push_back(token);
  2779. };
  2780. if (!lexer->Tokenize(currentFormattedQuery, parsedSettings.File, onNextFormattedToken, issues, NSQLTranslation::SQL_MAX_PARSER_ERRORS)) {
  2781. return false;
  2782. }
  2783. if (!Validate(stmtTokens, stmtFormattedTokens)) {
  2784. issues.AddIssue(NYql::TIssue({}, TStringBuilder() << "Validation failed: " << currentQuery.Quote() << " != " << currentFormattedQuery.Quote()));
  2785. return false;
  2786. }
  2787. const bool differentStmtAltCase = prevStmtCoreAltCase.Defined() && stmtCoreAltCase != prevStmtCoreAltCase;
  2788. if ((addLineBefore || prevAddLine || differentStmtAltCase) && !finalFormattedQuery.empty()) {
  2789. finalFormattedQuery << "\n";
  2790. }
  2791. prevAddLine = addLineAfter;
  2792. prevStmtCoreAltCase = stmtCoreAltCase;
  2793. finalFormattedQuery << currentFormattedQuery;
  2794. if (parsedTokens.back().Name != "SEMICOLON") {
  2795. finalFormattedQuery << ";\n";
  2796. }
  2797. }
  2798. formattedQuery = finalFormattedQuery;
  2799. return true;
  2800. }
  2801. private:
  2802. const NSQLTranslationV1::TLexers Lexers;
  2803. const NSQLTranslationV1::TParsers Parsers;
  2804. const NSQLTranslation::TTranslationSettings Settings;
  2805. };
  2806. }
  2807. ISqlFormatter::TPtr MakeSqlFormatter(const NSQLTranslationV1::TLexers& lexers,
  2808. const NSQLTranslationV1::TParsers& parsers,
  2809. const NSQLTranslation::TTranslationSettings& settings) {
  2810. return ISqlFormatter::TPtr(new TSqlFormatter(lexers, parsers, settings));
  2811. }
  2812. ISqlFormatter::TPtr MakeSqlFormatter(const NSQLTranslation::TTranslationSettings& settings) {
  2813. return MakeSqlFormatter(NSQLTranslationV1::MakeAllLexers(), NSQLTranslationV1::MakeAllParsers(), settings);
  2814. }
  2815. TString MutateQuery(const NSQLTranslationV1::TLexers& lexers,
  2816. const TString& query, const NSQLTranslation::TTranslationSettings& settings) {
  2817. auto parsedSettings = settings;
  2818. NYql::TIssues issues;
  2819. if (!NSQLTranslation::ParseTranslationSettings(query, parsedSettings, issues)) {
  2820. throw yexception() << issues.ToString();
  2821. }
  2822. auto lexer = NSQLTranslationV1::MakeLexer(lexers, parsedSettings.AnsiLexer, parsedSettings.Antlr4Parser);
  2823. TVector<NSQLTranslation::TParsedToken> allTokens;
  2824. auto onNextToken = [&](NSQLTranslation::TParsedToken&& token) {
  2825. if (token.Name != "EOF") {
  2826. allTokens.push_back(token);
  2827. }
  2828. };
  2829. if (!lexer->Tokenize(query, parsedSettings.File, onNextToken, issues, NSQLTranslation::SQL_MAX_PARSER_ERRORS)) {
  2830. throw yexception() << issues.ToString();
  2831. }
  2832. TStringBuilder newQueryBuilder;
  2833. ui32 index = 0;
  2834. for (const auto& x : allTokens) {
  2835. newQueryBuilder << " /*" << index++ << "*/ ";
  2836. newQueryBuilder << x.Content;
  2837. }
  2838. newQueryBuilder << " /*" << index++ << "*/ ";
  2839. return newQueryBuilder;
  2840. }
  2841. bool SqlFormatSimple(const NSQLTranslationV1::TLexers& lexers,
  2842. const NSQLTranslationV1::TParsers& parsers,
  2843. const TString& query, TString& formattedQuery, TString& error) {
  2844. try {
  2845. google::protobuf::Arena arena;
  2846. NSQLTranslation::TTranslationSettings settings;
  2847. settings.Arena = &arena;
  2848. auto formatter = MakeSqlFormatter(lexers, parsers, settings);
  2849. NYql::TIssues issues;
  2850. const bool result = formatter->Format(query, formattedQuery, issues);
  2851. if (!result) {
  2852. error = issues.ToString();
  2853. }
  2854. return result;
  2855. } catch (const std::exception& e) {
  2856. error = e.what();
  2857. return false;
  2858. }
  2859. }
  2860. THashSet<TString> GetKeywords() {
  2861. TString grammar;
  2862. // ANTLR4-MIGRATION: just change SQLv1 to SQLv1Antlr4
  2863. Y_ENSURE(NResource::FindExact("SQLv1.g.in", &grammar));
  2864. THashSet<TString> res;
  2865. TVector<TString> lines;
  2866. Split(grammar, "\n", lines);
  2867. for (auto s : lines) {
  2868. s = StripString(s);
  2869. if (s.StartsWith("//")) {
  2870. continue;
  2871. }
  2872. auto pos1 = s.find(':');
  2873. auto pos2 = s.find(';');
  2874. if (pos1 == TString::npos || pos2 == TString::npos || pos2 < pos1 + 2) {
  2875. continue;
  2876. }
  2877. auto before = s.substr(0, pos1);
  2878. auto after = s.substr(pos1 + 1, pos2 - pos1 - 1);
  2879. SubstGlobal(after, " ", "");
  2880. SubstGlobal(after, "'", "");
  2881. if (after == before) {
  2882. //Cerr << before << "\n";
  2883. res.insert(before);
  2884. }
  2885. }
  2886. return res;
  2887. }
  2888. } // namespace NSQLFormat