sql_format.cpp 116 KB

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