Formatter.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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::DynamicEvaluate* node)
  216. {
  217. will_visit(node);
  218. test_and_update_output_cursor(node);
  219. current_builder().append('$');
  220. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  221. NodeVisitor::visit(node);
  222. visited(node);
  223. }
  224. void Formatter::visit(const AST::DoubleQuotedString* node)
  225. {
  226. will_visit(node);
  227. test_and_update_output_cursor(node);
  228. current_builder().append("\"");
  229. TemporaryChange quotes { m_options.in_double_quotes, true };
  230. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  231. NodeVisitor::visit(node);
  232. current_builder().append("\"");
  233. visited(node);
  234. }
  235. void Formatter::visit(const AST::Fd2FdRedirection* node)
  236. {
  237. will_visit(node);
  238. test_and_update_output_cursor(node);
  239. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  240. current_builder().appendf(" %d>&%d", node->source_fd(), node->dest_fd());
  241. if (m_hit_node == node)
  242. ++m_output_cursor;
  243. visited(node);
  244. }
  245. void Formatter::visit(const AST::FunctionDeclaration* node)
  246. {
  247. will_visit(node);
  248. test_and_update_output_cursor(node);
  249. current_builder().append(node->name().name);
  250. current_builder().append('(');
  251. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  252. auto first = true;
  253. for (auto& arg : node->arguments()) {
  254. if (!first)
  255. current_builder().append(' ');
  256. first = false;
  257. current_builder().append(arg.name);
  258. }
  259. current_builder().append(") ");
  260. in_new_block([&] {
  261. if (node->block())
  262. node->block()->visit(*this);
  263. });
  264. visited(node);
  265. }
  266. void Formatter::visit(const AST::ForLoop* node)
  267. {
  268. will_visit(node);
  269. test_and_update_output_cursor(node);
  270. current_builder().append("for ");
  271. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  272. if (node->variable_name() != "it") {
  273. current_builder().append(node->variable_name());
  274. current_builder().append(" in ");
  275. }
  276. node->iterated_expression()->visit(*this);
  277. current_builder().append(' ');
  278. in_new_block([&] {
  279. if (node->block())
  280. node->block()->visit(*this);
  281. });
  282. visited(node);
  283. }
  284. void Formatter::visit(const AST::Glob* node)
  285. {
  286. will_visit(node);
  287. test_and_update_output_cursor(node);
  288. current_builder().append(node->text());
  289. visited(node);
  290. }
  291. void Formatter::visit(const AST::Execute* node)
  292. {
  293. will_visit(node);
  294. test_and_update_output_cursor(node);
  295. auto& builder = current_builder();
  296. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  297. ScopedValueRollback options_rollback { m_options };
  298. if (node->does_capture_stdout()) {
  299. builder.append("$");
  300. m_options.explicit_parentheses = true;
  301. }
  302. NodeVisitor::visit(node);
  303. visited(node);
  304. }
  305. void Formatter::visit(const AST::IfCond* node)
  306. {
  307. will_visit(node);
  308. test_and_update_output_cursor(node);
  309. current_builder().append("if ");
  310. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  311. node->condition()->visit(*this);
  312. current_builder().append(' ');
  313. in_new_block([&] {
  314. if (node->true_branch())
  315. node->true_branch()->visit(*this);
  316. });
  317. if (node->false_branch()) {
  318. current_builder().append(" else ");
  319. if (node->false_branch()->kind() != AST::Node::Kind::IfCond) {
  320. in_new_block([&] {
  321. node->false_branch()->visit(*this);
  322. });
  323. } else {
  324. node->false_branch()->visit(*this);
  325. }
  326. } else if (node->else_position().has_value()) {
  327. current_builder().append(" else ");
  328. }
  329. visited(node);
  330. }
  331. void Formatter::visit(const AST::Join* node)
  332. {
  333. will_visit(node);
  334. test_and_update_output_cursor(node);
  335. auto should_parenthesise = m_options.explicit_parentheses;
  336. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  337. TemporaryChange parens { m_options.explicit_parentheses, false };
  338. if (should_parenthesise)
  339. current_builder().append('(');
  340. NodeVisitor::visit(node);
  341. if (should_parenthesise)
  342. current_builder().append(')');
  343. visited(node);
  344. }
  345. void Formatter::visit(const AST::MatchExpr* node)
  346. {
  347. will_visit(node);
  348. test_and_update_output_cursor(node);
  349. current_builder().append("match ");
  350. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  351. node->matched_expr()->visit(*this);
  352. if (!node->expr_name().is_empty()) {
  353. current_builder().append(" as ");
  354. current_builder().append(node->expr_name());
  355. }
  356. current_builder().append(' ');
  357. in_new_block([&] {
  358. auto first_entry = true;
  359. for (auto& entry : node->entries()) {
  360. if (!first_entry)
  361. insert_separator();
  362. first_entry = false;
  363. auto first = true;
  364. for (auto& option : entry.options) {
  365. if (!first)
  366. current_builder().append(" | ");
  367. first = false;
  368. option.visit(*this);
  369. }
  370. current_builder().append(' ');
  371. if (entry.match_names.has_value() && !entry.match_names.value().is_empty()) {
  372. current_builder().append("as (");
  373. auto first = true;
  374. for (auto& name : entry.match_names.value()) {
  375. if (!first)
  376. current_builder().append(' ');
  377. first = false;
  378. current_builder().append(name);
  379. }
  380. current_builder().append(") ");
  381. }
  382. in_new_block([&] {
  383. if (entry.body)
  384. entry.body->visit(*this);
  385. });
  386. }
  387. });
  388. visited(node);
  389. }
  390. void Formatter::visit(const AST::Or* node)
  391. {
  392. will_visit(node);
  393. test_and_update_output_cursor(node);
  394. auto should_indent = m_parent_node && m_parent_node->kind() != AST::Node::Kind::Or;
  395. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  396. with_added_indent(should_indent ? 1 : 0, [&] {
  397. node->left()->visit(*this);
  398. current_builder().append(" \\");
  399. insert_separator();
  400. current_builder().append("|| ");
  401. node->right()->visit(*this);
  402. });
  403. visited(node);
  404. }
  405. void Formatter::visit(const AST::Pipe* 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::Pipe;
  410. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  411. node->left()->visit(*this);
  412. current_builder().append(" \\");
  413. with_added_indent(should_indent ? 1 : 0, [&] {
  414. insert_separator();
  415. current_builder().append("| ");
  416. node->right()->visit(*this);
  417. });
  418. visited(node);
  419. }
  420. void Formatter::visit(const AST::Range* node)
  421. {
  422. will_visit(node);
  423. test_and_update_output_cursor(node);
  424. current_builder().append('{');
  425. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  426. node->start()->visit(*this);
  427. current_builder().append("..");
  428. node->end()->visit(*this);
  429. current_builder().append('}');
  430. visited(node);
  431. }
  432. void Formatter::visit(const AST::ReadRedirection* node)
  433. {
  434. will_visit(node);
  435. test_and_update_output_cursor(node);
  436. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  437. if (node->fd() != 0)
  438. current_builder().appendf(" %d<", node->fd());
  439. else
  440. current_builder().append(" <");
  441. NodeVisitor::visit(node);
  442. visited(node);
  443. }
  444. void Formatter::visit(const AST::ReadWriteRedirection* node)
  445. {
  446. will_visit(node);
  447. test_and_update_output_cursor(node);
  448. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  449. if (node->fd() != 0)
  450. current_builder().appendf(" %d<>", node->fd());
  451. else
  452. current_builder().append(" <>");
  453. NodeVisitor::visit(node);
  454. visited(node);
  455. }
  456. void Formatter::visit(const AST::Sequence* node)
  457. {
  458. will_visit(node);
  459. test_and_update_output_cursor(node);
  460. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  461. node->left()->visit(*this);
  462. insert_separator();
  463. node->right()->visit(*this);
  464. visited(node);
  465. }
  466. void Formatter::visit(const AST::Subshell* node)
  467. {
  468. will_visit(node);
  469. test_and_update_output_cursor(node);
  470. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  471. in_new_block([&] {
  472. insert_separator();
  473. NodeVisitor::visit(node);
  474. insert_separator();
  475. });
  476. visited(node);
  477. }
  478. void Formatter::visit(const AST::SimpleVariable* node)
  479. {
  480. will_visit(node);
  481. test_and_update_output_cursor(node);
  482. current_builder().append('$');
  483. current_builder().append(node->name());
  484. visited(node);
  485. }
  486. void Formatter::visit(const AST::SpecialVariable* node)
  487. {
  488. will_visit(node);
  489. test_and_update_output_cursor(node);
  490. current_builder().append('$');
  491. current_builder().append(node->name());
  492. visited(node);
  493. }
  494. void Formatter::visit(const AST::Juxtaposition* node)
  495. {
  496. will_visit(node);
  497. test_and_update_output_cursor(node);
  498. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  499. NodeVisitor::visit(node);
  500. visited(node);
  501. }
  502. void Formatter::visit(const AST::StringLiteral* node)
  503. {
  504. will_visit(node);
  505. test_and_update_output_cursor(node);
  506. if (!m_options.in_double_quotes)
  507. current_builder().append("'");
  508. if (m_options.in_double_quotes) {
  509. for (auto ch : node->text()) {
  510. switch (ch) {
  511. case '"':
  512. case '\\':
  513. case '$':
  514. current_builder().append('\\');
  515. break;
  516. case '\n':
  517. current_builder().append("\\n");
  518. continue;
  519. case '\r':
  520. current_builder().append("\\r");
  521. continue;
  522. case '\t':
  523. current_builder().append("\\t");
  524. continue;
  525. case '\v':
  526. current_builder().append("\\v");
  527. continue;
  528. case '\f':
  529. current_builder().append("\\f");
  530. continue;
  531. case '\a':
  532. current_builder().append("\\a");
  533. continue;
  534. case '\e':
  535. current_builder().append("\\e");
  536. continue;
  537. default:
  538. break;
  539. }
  540. current_builder().append(ch);
  541. }
  542. } else {
  543. current_builder().append(node->text());
  544. }
  545. if (!m_options.in_double_quotes)
  546. current_builder().append("'");
  547. visited(node);
  548. }
  549. void Formatter::visit(const AST::StringPartCompose* node)
  550. {
  551. will_visit(node);
  552. test_and_update_output_cursor(node);
  553. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  554. NodeVisitor::visit(node);
  555. visited(node);
  556. }
  557. void Formatter::visit(const AST::SyntaxError* node)
  558. {
  559. will_visit(node);
  560. test_and_update_output_cursor(node);
  561. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  562. NodeVisitor::visit(node);
  563. visited(node);
  564. }
  565. void Formatter::visit(const AST::Tilde* node)
  566. {
  567. will_visit(node);
  568. test_and_update_output_cursor(node);
  569. current_builder().append(node->text());
  570. visited(node);
  571. }
  572. void Formatter::visit(const AST::VariableDeclarations* node)
  573. {
  574. will_visit(node);
  575. test_and_update_output_cursor(node);
  576. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  577. auto first = true;
  578. for (auto& entry : node->variables()) {
  579. if (!first)
  580. current_builder().append(' ');
  581. first = false;
  582. entry.name->visit(*this);
  583. current_builder().append('=');
  584. if (entry.value->is_command())
  585. current_builder().append('(');
  586. entry.value->visit(*this);
  587. if (entry.value->is_command())
  588. current_builder().append(')');
  589. }
  590. visited(node);
  591. }
  592. void Formatter::visit(const AST::WriteAppendRedirection* node)
  593. {
  594. will_visit(node);
  595. test_and_update_output_cursor(node);
  596. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  597. if (node->fd() != 1)
  598. current_builder().appendf(" %d>>", node->fd());
  599. else
  600. current_builder().append(" >>");
  601. NodeVisitor::visit(node);
  602. visited(node);
  603. }
  604. void Formatter::visit(const AST::WriteRedirection* node)
  605. {
  606. will_visit(node);
  607. test_and_update_output_cursor(node);
  608. TemporaryChange<const AST::Node*> parent { m_parent_node, node };
  609. if (node->fd() != 1)
  610. current_builder().appendf(" %d>", node->fd());
  611. else
  612. current_builder().append(" >");
  613. NodeVisitor::visit(node);
  614. visited(node);
  615. }
  616. }