Formatter.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Formatter.h"
  27. #include "AST.h"
  28. #include "Parser.h"
  29. #include <AK/TemporaryChange.h>
  30. namespace Shell {
  31. String Formatter::format()
  32. {
  33. auto node = Parser(m_source).parse();
  34. if (m_cursor >= 0)
  35. m_output_cursor = m_cursor;
  36. if (!node)
  37. return String();
  38. if (node->is_syntax_error())
  39. return m_source;
  40. if (m_cursor >= 0) {
  41. auto hit_test = node->hit_test_position(m_cursor);
  42. if (hit_test.matching_node)
  43. m_hit_node = hit_test.matching_node.ptr();
  44. else
  45. m_hit_node = nullptr;
  46. }
  47. m_parent_node = nullptr;
  48. node->visit(*this);
  49. auto string = m_builder.string_view();
  50. if (!string.ends_with(" "))
  51. m_builder.append(m_trivia);
  52. return m_builder.to_string();
  53. }
  54. void Formatter::with_added_indent(int indent, Function<void()> callback)
  55. {
  56. TemporaryChange indent_change { m_current_indent, m_current_indent + indent };
  57. callback();
  58. }
  59. void Formatter::in_new_block(Function<void()> callback)
  60. {
  61. current_builder().append('{');
  62. with_added_indent(1, [&] {
  63. insert_separator();
  64. callback();
  65. });
  66. insert_separator();
  67. current_builder().append('}');
  68. }
  69. void Formatter::test_and_update_output_cursor(const AST::Node* node)
  70. {
  71. if (!node)
  72. return;
  73. if (node != m_hit_node)
  74. return;
  75. m_output_cursor = current_builder().length() + m_cursor - node->position().start_offset;
  76. }
  77. void Formatter::visited(const AST::Node* node)
  78. {
  79. m_last_visited_node = node;
  80. }
  81. void Formatter::will_visit(const AST::Node* node)
  82. {
  83. if (!m_last_visited_node)
  84. return;
  85. if (!node)
  86. return;
  87. auto direct_sequence_child = !m_parent_node || m_parent_node->kind() == AST::Node::Kind::Sequence;
  88. if (direct_sequence_child && node->kind() != AST::Node::Kind::Sequence) {
  89. // Collapse more than one empty line to a single one.
  90. if (node->position().start_line.line_number - m_last_visited_node->position().end_line.line_number > 1)
  91. current_builder().append('\n');
  92. }
  93. }
  94. void Formatter::insert_separator()
  95. {
  96. current_builder().append('\n');
  97. insert_indent();
  98. }
  99. void Formatter::insert_indent()
  100. {
  101. for (size_t i = 0; i < m_current_indent; ++i)
  102. current_builder().append(" ");
  103. }
  104. void Formatter::visit(const AST::PathRedirectionNode* node)
  105. {
  106. will_visit(node);
  107. test_and_update_output_cursor(node);
  108. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  109. NodeVisitor::visit(node);
  110. visited(node);
  111. }
  112. void Formatter::visit(const AST::And* node)
  113. {
  114. will_visit(node);
  115. test_and_update_output_cursor(node);
  116. auto should_indent = m_parent_node && m_parent_node->kind() != AST::Node::Kind::And;
  117. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  118. with_added_indent(should_indent ? 1 : 0, [&] {
  119. node->left()->visit(*this);
  120. current_builder().append(" \\");
  121. insert_separator();
  122. current_builder().append("&& ");
  123. node->right()->visit(*this);
  124. });
  125. visited(node);
  126. }
  127. void Formatter::visit(const AST::ListConcatenate* node)
  128. {
  129. will_visit(node);
  130. test_and_update_output_cursor(node);
  131. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  132. auto first = true;
  133. for (auto& subnode : node->list()) {
  134. if (!first)
  135. current_builder().append(' ');
  136. first = false;
  137. subnode->visit(*this);
  138. }
  139. visited(node);
  140. }
  141. void Formatter::visit(const AST::Background* node)
  142. {
  143. will_visit(node);
  144. test_and_update_output_cursor(node);
  145. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  146. NodeVisitor::visit(node);
  147. current_builder().append(" &");
  148. visited(node);
  149. }
  150. void Formatter::visit(const AST::BarewordLiteral* node)
  151. {
  152. will_visit(node);
  153. test_and_update_output_cursor(node);
  154. current_builder().append(node->text());
  155. visited(node);
  156. }
  157. void Formatter::visit(const AST::BraceExpansion* node)
  158. {
  159. will_visit(node);
  160. test_and_update_output_cursor(node);
  161. current_builder().append('{');
  162. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  163. bool first = true;
  164. for (auto& entry : node->entries()) {
  165. if (!first)
  166. current_builder().append(',');
  167. first = false;
  168. entry.visit(*this);
  169. }
  170. current_builder().append('}');
  171. visited(node);
  172. }
  173. void Formatter::visit(const AST::CastToCommand* node)
  174. {
  175. will_visit(node);
  176. test_and_update_output_cursor(node);
  177. if (m_options.explicit_parentheses)
  178. current_builder().append('(');
  179. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  180. NodeVisitor::visit(node);
  181. if (m_options.explicit_parentheses)
  182. current_builder().append(')');
  183. visited(node);
  184. }
  185. void Formatter::visit(const AST::CastToList* node)
  186. {
  187. will_visit(node);
  188. test_and_update_output_cursor(node);
  189. current_builder().append('(');
  190. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  191. NodeVisitor::visit(node);
  192. current_builder().append(')');
  193. visited(node);
  194. }
  195. void Formatter::visit(const AST::CloseFdRedirection* node)
  196. {
  197. will_visit(node);
  198. test_and_update_output_cursor(node);
  199. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  200. current_builder().appendf(" %d>&-", node->fd());
  201. visited(node);
  202. }
  203. void Formatter::visit(const AST::CommandLiteral*)
  204. {
  205. ASSERT_NOT_REACHED();
  206. }
  207. void Formatter::visit(const AST::Comment* node)
  208. {
  209. will_visit(node);
  210. test_and_update_output_cursor(node);
  211. current_builder().append("#");
  212. current_builder().append(node->text());
  213. visited(node);
  214. }
  215. void Formatter::visit(const AST::ContinuationControl* node)
  216. {
  217. will_visit(node);
  218. test_and_update_output_cursor(node);
  219. if (node->continuation_kind() == AST::ContinuationControl::Break)
  220. current_builder().append("break");
  221. else if (node->continuation_kind() == AST::ContinuationControl::Continue)
  222. current_builder().append("continue");
  223. else
  224. ASSERT_NOT_REACHED();
  225. visited(node);
  226. }
  227. void Formatter::visit(const AST::DynamicEvaluate* node)
  228. {
  229. will_visit(node);
  230. test_and_update_output_cursor(node);
  231. current_builder().append('$');
  232. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  233. NodeVisitor::visit(node);
  234. visited(node);
  235. }
  236. void Formatter::visit(const AST::DoubleQuotedString* node)
  237. {
  238. will_visit(node);
  239. test_and_update_output_cursor(node);
  240. current_builder().append("\"");
  241. TemporaryChange quotes { m_options.in_double_quotes, true };
  242. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  243. NodeVisitor::visit(node);
  244. current_builder().append("\"");
  245. visited(node);
  246. }
  247. void Formatter::visit(const AST::Fd2FdRedirection* node)
  248. {
  249. will_visit(node);
  250. test_and_update_output_cursor(node);
  251. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  252. current_builder().appendf(" %d>&%d", node->source_fd(), node->dest_fd());
  253. if (m_hit_node == node)
  254. ++m_output_cursor;
  255. visited(node);
  256. }
  257. void Formatter::visit(const AST::FunctionDeclaration* node)
  258. {
  259. will_visit(node);
  260. test_and_update_output_cursor(node);
  261. current_builder().append(node->name().name);
  262. current_builder().append('(');
  263. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  264. auto first = true;
  265. for (auto& arg : node->arguments()) {
  266. if (!first)
  267. current_builder().append(' ');
  268. first = false;
  269. current_builder().append(arg.name);
  270. }
  271. current_builder().append(") ");
  272. in_new_block([&] {
  273. if (node->block())
  274. node->block()->visit(*this);
  275. });
  276. visited(node);
  277. }
  278. void Formatter::visit(const AST::ForLoop* node)
  279. {
  280. will_visit(node);
  281. test_and_update_output_cursor(node);
  282. auto is_loop = node->iterated_expression().is_null();
  283. current_builder().append(is_loop ? "loop" : "for ");
  284. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  285. if (!is_loop) {
  286. if (node->variable_name() != "it") {
  287. current_builder().append(node->variable_name());
  288. current_builder().append(" in ");
  289. }
  290. node->iterated_expression()->visit(*this);
  291. }
  292. current_builder().append(' ');
  293. in_new_block([&] {
  294. if (node->block())
  295. node->block()->visit(*this);
  296. });
  297. visited(node);
  298. }
  299. void Formatter::visit(const AST::Glob* node)
  300. {
  301. will_visit(node);
  302. test_and_update_output_cursor(node);
  303. current_builder().append(node->text());
  304. visited(node);
  305. }
  306. void Formatter::visit(const AST::Execute* node)
  307. {
  308. will_visit(node);
  309. test_and_update_output_cursor(node);
  310. auto& builder = current_builder();
  311. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  312. ScopedValueRollback options_rollback { m_options };
  313. if (node->does_capture_stdout()) {
  314. builder.append("$");
  315. m_options.explicit_parentheses = true;
  316. }
  317. NodeVisitor::visit(node);
  318. visited(node);
  319. }
  320. void Formatter::visit(const AST::IfCond* node)
  321. {
  322. will_visit(node);
  323. test_and_update_output_cursor(node);
  324. current_builder().append("if ");
  325. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  326. node->condition()->visit(*this);
  327. current_builder().append(' ');
  328. in_new_block([&] {
  329. if (node->true_branch())
  330. node->true_branch()->visit(*this);
  331. });
  332. if (node->false_branch()) {
  333. current_builder().append(" else ");
  334. if (node->false_branch()->kind() != AST::Node::Kind::IfCond) {
  335. in_new_block([&] {
  336. node->false_branch()->visit(*this);
  337. });
  338. } else {
  339. node->false_branch()->visit(*this);
  340. }
  341. } else if (node->else_position().has_value()) {
  342. current_builder().append(" else ");
  343. }
  344. visited(node);
  345. }
  346. void Formatter::visit(const AST::Join* node)
  347. {
  348. will_visit(node);
  349. test_and_update_output_cursor(node);
  350. auto should_parenthesise = m_options.explicit_parentheses;
  351. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  352. TemporaryChange parens { m_options.explicit_parentheses, false };
  353. if (should_parenthesise)
  354. current_builder().append('(');
  355. NodeVisitor::visit(node);
  356. if (should_parenthesise)
  357. current_builder().append(')');
  358. visited(node);
  359. }
  360. void Formatter::visit(const AST::MatchExpr* node)
  361. {
  362. will_visit(node);
  363. test_and_update_output_cursor(node);
  364. current_builder().append("match ");
  365. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  366. node->matched_expr()->visit(*this);
  367. if (!node->expr_name().is_empty()) {
  368. current_builder().append(" as ");
  369. current_builder().append(node->expr_name());
  370. }
  371. current_builder().append(' ');
  372. in_new_block([&] {
  373. auto first_entry = true;
  374. for (auto& entry : node->entries()) {
  375. if (!first_entry)
  376. insert_separator();
  377. first_entry = false;
  378. auto first = true;
  379. for (auto& option : entry.options) {
  380. if (!first)
  381. current_builder().append(" | ");
  382. first = false;
  383. option.visit(*this);
  384. }
  385. current_builder().append(' ');
  386. if (entry.match_names.has_value() && !entry.match_names.value().is_empty()) {
  387. current_builder().append("as (");
  388. auto first = true;
  389. for (auto& name : entry.match_names.value()) {
  390. if (!first)
  391. current_builder().append(' ');
  392. first = false;
  393. current_builder().append(name);
  394. }
  395. current_builder().append(") ");
  396. }
  397. in_new_block([&] {
  398. if (entry.body)
  399. entry.body->visit(*this);
  400. });
  401. }
  402. });
  403. visited(node);
  404. }
  405. void Formatter::visit(const AST::Or* node)
  406. {
  407. will_visit(node);
  408. test_and_update_output_cursor(node);
  409. auto should_indent = m_parent_node && m_parent_node->kind() != AST::Node::Kind::Or;
  410. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  411. with_added_indent(should_indent ? 1 : 0, [&] {
  412. node->left()->visit(*this);
  413. current_builder().append(" \\");
  414. insert_separator();
  415. current_builder().append("|| ");
  416. node->right()->visit(*this);
  417. });
  418. visited(node);
  419. }
  420. void Formatter::visit(const AST::Pipe* node)
  421. {
  422. will_visit(node);
  423. test_and_update_output_cursor(node);
  424. auto should_indent = m_parent_node && m_parent_node->kind() != AST::Node::Kind::Pipe;
  425. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  426. node->left()->visit(*this);
  427. current_builder().append(" \\");
  428. with_added_indent(should_indent ? 1 : 0, [&] {
  429. insert_separator();
  430. current_builder().append("| ");
  431. node->right()->visit(*this);
  432. });
  433. visited(node);
  434. }
  435. void Formatter::visit(const AST::Range* node)
  436. {
  437. will_visit(node);
  438. test_and_update_output_cursor(node);
  439. current_builder().append('{');
  440. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  441. node->start()->visit(*this);
  442. current_builder().append("..");
  443. node->end()->visit(*this);
  444. current_builder().append('}');
  445. visited(node);
  446. }
  447. void Formatter::visit(const AST::ReadRedirection* node)
  448. {
  449. will_visit(node);
  450. test_and_update_output_cursor(node);
  451. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  452. if (node->fd() != 0)
  453. current_builder().appendf(" %d<", node->fd());
  454. else
  455. current_builder().append(" <");
  456. NodeVisitor::visit(node);
  457. visited(node);
  458. }
  459. void Formatter::visit(const AST::ReadWriteRedirection* node)
  460. {
  461. will_visit(node);
  462. test_and_update_output_cursor(node);
  463. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  464. if (node->fd() != 0)
  465. current_builder().appendf(" %d<>", node->fd());
  466. else
  467. current_builder().append(" <>");
  468. NodeVisitor::visit(node);
  469. visited(node);
  470. }
  471. void Formatter::visit(const AST::Sequence* node)
  472. {
  473. will_visit(node);
  474. test_and_update_output_cursor(node);
  475. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  476. node->left()->visit(*this);
  477. insert_separator();
  478. node->right()->visit(*this);
  479. visited(node);
  480. }
  481. void Formatter::visit(const AST::Subshell* node)
  482. {
  483. will_visit(node);
  484. test_and_update_output_cursor(node);
  485. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  486. in_new_block([&] {
  487. insert_separator();
  488. NodeVisitor::visit(node);
  489. insert_separator();
  490. });
  491. visited(node);
  492. }
  493. void Formatter::visit(const AST::SimpleVariable* node)
  494. {
  495. will_visit(node);
  496. test_and_update_output_cursor(node);
  497. current_builder().append('$');
  498. current_builder().append(node->name());
  499. visited(node);
  500. }
  501. void Formatter::visit(const AST::SpecialVariable* node)
  502. {
  503. will_visit(node);
  504. test_and_update_output_cursor(node);
  505. current_builder().append('$');
  506. current_builder().append(node->name());
  507. visited(node);
  508. }
  509. void Formatter::visit(const AST::Juxtaposition* node)
  510. {
  511. will_visit(node);
  512. test_and_update_output_cursor(node);
  513. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  514. NodeVisitor::visit(node);
  515. visited(node);
  516. }
  517. void Formatter::visit(const AST::StringLiteral* node)
  518. {
  519. will_visit(node);
  520. test_and_update_output_cursor(node);
  521. if (!m_options.in_double_quotes)
  522. current_builder().append("'");
  523. if (m_options.in_double_quotes) {
  524. for (auto ch : node->text()) {
  525. switch (ch) {
  526. case '"':
  527. case '\\':
  528. case '$':
  529. current_builder().append('\\');
  530. break;
  531. case '\n':
  532. current_builder().append("\\n");
  533. continue;
  534. case '\r':
  535. current_builder().append("\\r");
  536. continue;
  537. case '\t':
  538. current_builder().append("\\t");
  539. continue;
  540. case '\v':
  541. current_builder().append("\\v");
  542. continue;
  543. case '\f':
  544. current_builder().append("\\f");
  545. continue;
  546. case '\a':
  547. current_builder().append("\\a");
  548. continue;
  549. case '\e':
  550. current_builder().append("\\e");
  551. continue;
  552. default:
  553. break;
  554. }
  555. current_builder().append(ch);
  556. }
  557. } else {
  558. current_builder().append(node->text());
  559. }
  560. if (!m_options.in_double_quotes)
  561. current_builder().append("'");
  562. visited(node);
  563. }
  564. void Formatter::visit(const AST::StringPartCompose* node)
  565. {
  566. will_visit(node);
  567. test_and_update_output_cursor(node);
  568. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  569. NodeVisitor::visit(node);
  570. visited(node);
  571. }
  572. void Formatter::visit(const AST::SyntaxError* node)
  573. {
  574. will_visit(node);
  575. test_and_update_output_cursor(node);
  576. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  577. NodeVisitor::visit(node);
  578. visited(node);
  579. }
  580. void Formatter::visit(const AST::Tilde* node)
  581. {
  582. will_visit(node);
  583. test_and_update_output_cursor(node);
  584. current_builder().append(node->text());
  585. visited(node);
  586. }
  587. void Formatter::visit(const AST::VariableDeclarations* node)
  588. {
  589. will_visit(node);
  590. test_and_update_output_cursor(node);
  591. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  592. auto first = true;
  593. for (auto& entry : node->variables()) {
  594. if (!first)
  595. current_builder().append(' ');
  596. first = false;
  597. entry.name->visit(*this);
  598. current_builder().append('=');
  599. if (entry.value->is_command())
  600. current_builder().append('(');
  601. entry.value->visit(*this);
  602. if (entry.value->is_command())
  603. current_builder().append(')');
  604. }
  605. visited(node);
  606. }
  607. void Formatter::visit(const AST::WriteAppendRedirection* node)
  608. {
  609. will_visit(node);
  610. test_and_update_output_cursor(node);
  611. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  612. if (node->fd() != 1)
  613. current_builder().appendf(" %d>>", node->fd());
  614. else
  615. current_builder().append(" >>");
  616. NodeVisitor::visit(node);
  617. visited(node);
  618. }
  619. void Formatter::visit(const AST::WriteRedirection* node)
  620. {
  621. will_visit(node);
  622. test_and_update_output_cursor(node);
  623. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  624. if (node->fd() != 1)
  625. current_builder().appendf(" %d>", node->fd());
  626. else
  627. current_builder().append(" >");
  628. NodeVisitor::visit(node);
  629. visited(node);
  630. }
  631. }