Parser.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  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 "Parser.h"
  27. #include <ctype.h>
  28. #include <stdio.h>
  29. #include <unistd.h>
  30. char Parser::peek()
  31. {
  32. if (m_offset == m_input.length())
  33. return 0;
  34. ASSERT(m_offset < m_input.length());
  35. return m_input[m_offset];
  36. }
  37. char Parser::consume()
  38. {
  39. auto ch = peek();
  40. ++m_offset;
  41. return ch;
  42. }
  43. void Parser::putback()
  44. {
  45. ASSERT(m_offset > 0);
  46. --m_offset;
  47. }
  48. bool Parser::expect(char ch)
  49. {
  50. return expect(StringView { &ch, 1 });
  51. }
  52. bool Parser::expect(const StringView& expected)
  53. {
  54. if (expected.length() + m_offset > m_input.length())
  55. return false;
  56. for (size_t i = 0; i < expected.length(); ++i) {
  57. if (peek() != expected[i])
  58. return false;
  59. consume();
  60. }
  61. return true;
  62. }
  63. template<typename A, typename... Args>
  64. RefPtr<A> Parser::create(Args... args)
  65. {
  66. return adopt(*new A(AST::Position { m_rule_start_offsets.last(), m_offset }, args...));
  67. }
  68. [[nodiscard]] OwnPtr<Parser::ScopedOffset> Parser::push_start()
  69. {
  70. return make<ScopedOffset>(m_rule_start_offsets, m_offset);
  71. }
  72. static constexpr bool is_whitespace(char c)
  73. {
  74. return c == ' ' || c == '\t';
  75. }
  76. static constexpr bool is_word_character(char c)
  77. {
  78. return (c <= '9' && c >= '0') || (c <= 'Z' && c >= 'A') || (c <= 'z' && c >= 'a') || c == '_';
  79. }
  80. static constexpr bool is_digit(char c)
  81. {
  82. return c <= '9' && c >= '0';
  83. }
  84. static constexpr auto is_not(char c)
  85. {
  86. return [c](char ch) { return ch != c; };
  87. }
  88. static constexpr auto is_any_of(StringView s)
  89. {
  90. return [s](char ch) { return s.contains(ch); };
  91. }
  92. static inline char to_byte(char a, char b)
  93. {
  94. char buf[3] { a, b, 0 };
  95. return strtol(buf, nullptr, 16);
  96. }
  97. RefPtr<AST::Node> Parser::parse()
  98. {
  99. m_offset = 0;
  100. auto toplevel = parse_toplevel();
  101. if (m_offset < m_input.length()) {
  102. // Parsing stopped midway, this is a syntax error.
  103. auto error_start = push_start();
  104. m_offset = m_input.length();
  105. auto syntax_error_node = create<AST::SyntaxError>("Unexpected tokens past the end");
  106. if (toplevel)
  107. return create<AST::Join>(move(toplevel), move(syntax_error_node));
  108. return syntax_error_node;
  109. }
  110. return toplevel;
  111. }
  112. RefPtr<AST::Node> Parser::parse_toplevel()
  113. {
  114. auto rule_start = push_start();
  115. if (auto sequence = parse_sequence())
  116. return create<AST::Execute>(sequence);
  117. return nullptr;
  118. }
  119. RefPtr<AST::Node> Parser::parse_sequence()
  120. {
  121. consume_while(is_any_of(" \t\n;")); // ignore whitespaces or terminators without effect.
  122. auto rule_start = push_start();
  123. auto var_decls = parse_variable_decls();
  124. switch (peek()) {
  125. case '}':
  126. return var_decls;
  127. case ';':
  128. case '\n': {
  129. if (!var_decls)
  130. break;
  131. consume_while(is_any_of("\n;"));
  132. auto rest = parse_sequence();
  133. if (rest)
  134. return create<AST::Sequence>(move(var_decls), move(rest));
  135. return var_decls;
  136. }
  137. default:
  138. break;
  139. }
  140. RefPtr<AST::Node> first = nullptr;
  141. if (auto control_structure = parse_control_structure())
  142. first = control_structure;
  143. if (!first)
  144. first = parse_or_logical_sequence();
  145. if (!first)
  146. return var_decls;
  147. if (var_decls)
  148. first = create<AST::Sequence>(move(var_decls), move(first));
  149. consume_while(is_whitespace);
  150. switch (peek()) {
  151. case ';':
  152. case '\n':
  153. consume_while(is_any_of("\n;"));
  154. if (auto expr = parse_sequence()) {
  155. return create<AST::Sequence>(move(first), move(expr)); // Sequence
  156. }
  157. return first;
  158. case '&': {
  159. auto execute_pipe_seq = first->would_execute() ? first : static_cast<RefPtr<AST::Node>>(create<AST::Execute>(first));
  160. consume();
  161. auto bg = create<AST::Background>(move(first)); // Execute Background
  162. if (auto rest = parse_sequence())
  163. return create<AST::Sequence>(move(bg), move(rest)); // Sequence Background Sequence
  164. return bg;
  165. }
  166. default:
  167. return first;
  168. }
  169. }
  170. RefPtr<AST::Node> Parser::parse_variable_decls()
  171. {
  172. auto rule_start = push_start();
  173. consume_while(is_whitespace);
  174. auto offset_before_name = m_offset;
  175. auto var_name = consume_while(is_word_character);
  176. if (var_name.is_empty())
  177. return nullptr;
  178. if (!expect('=')) {
  179. m_offset = offset_before_name;
  180. return nullptr;
  181. }
  182. auto name_expr = create<AST::BarewordLiteral>(move(var_name));
  183. auto start = push_start();
  184. auto expression = parse_expression();
  185. if (!expression || expression->is_syntax_error()) {
  186. m_offset = start->offset;
  187. if (peek() == '(') {
  188. consume();
  189. auto command = parse_pipe_sequence();
  190. if (!command)
  191. m_offset = start->offset;
  192. else if (!expect(')'))
  193. command->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating close paren"));
  194. expression = command;
  195. }
  196. }
  197. if (!expression) {
  198. if (is_whitespace(peek())) {
  199. auto string_start = push_start();
  200. expression = create<AST::StringLiteral>("");
  201. } else {
  202. m_offset = offset_before_name;
  203. return nullptr;
  204. }
  205. }
  206. Vector<AST::VariableDeclarations::Variable> variables;
  207. variables.append({ move(name_expr), move(expression) });
  208. if (consume_while(is_whitespace).is_empty())
  209. return create<AST::VariableDeclarations>(move(variables));
  210. auto rest = parse_variable_decls();
  211. if (!rest)
  212. return create<AST::VariableDeclarations>(move(variables));
  213. ASSERT(rest->is_variable_decls());
  214. auto* rest_decl = static_cast<AST::VariableDeclarations*>(rest.ptr());
  215. variables.append(rest_decl->variables());
  216. return create<AST::VariableDeclarations>(move(variables));
  217. }
  218. RefPtr<AST::Node> Parser::parse_or_logical_sequence()
  219. {
  220. consume_while(is_whitespace);
  221. auto rule_start = push_start();
  222. auto and_sequence = parse_and_logical_sequence();
  223. if (!and_sequence)
  224. return nullptr;
  225. consume_while(is_whitespace);
  226. auto saved_offset = m_offset;
  227. if (!expect("||")) {
  228. m_offset = saved_offset;
  229. return and_sequence;
  230. }
  231. auto right_and_sequence = parse_and_logical_sequence();
  232. if (!right_and_sequence)
  233. right_and_sequence = create<AST::SyntaxError>("Expected an expression after '||'");
  234. return create<AST::Or>(create<AST::Execute>(move(and_sequence)), create<AST::Execute>(move(right_and_sequence)));
  235. }
  236. RefPtr<AST::Node> Parser::parse_and_logical_sequence()
  237. {
  238. consume_while(is_whitespace);
  239. auto rule_start = push_start();
  240. auto pipe_sequence = parse_pipe_sequence();
  241. if (!pipe_sequence)
  242. return nullptr;
  243. consume_while(is_whitespace);
  244. auto saved_offset = m_offset;
  245. if (!expect("&&")) {
  246. m_offset = saved_offset;
  247. return pipe_sequence;
  248. }
  249. auto right_and_sequence = parse_and_logical_sequence();
  250. if (!right_and_sequence)
  251. right_and_sequence = create<AST::SyntaxError>("Expected an expression after '&&'");
  252. return create<AST::And>(create<AST::Execute>(move(pipe_sequence)), create<AST::Execute>(move(right_and_sequence)));
  253. }
  254. RefPtr<AST::Node> Parser::parse_pipe_sequence()
  255. {
  256. auto rule_start = push_start();
  257. auto command = parse_command();
  258. if (!command)
  259. return nullptr;
  260. consume_while(is_whitespace);
  261. if (peek() != '|')
  262. return command;
  263. consume();
  264. if (auto pipe_seq = parse_pipe_sequence()) {
  265. return create<AST::Pipe>(move(command), move(pipe_seq)); // Pipe
  266. }
  267. putback();
  268. return command;
  269. }
  270. RefPtr<AST::Node> Parser::parse_command()
  271. {
  272. auto rule_start = push_start();
  273. consume_while(is_whitespace);
  274. auto redir = parse_redirection();
  275. if (!redir) {
  276. auto list_expr = parse_list_expression();
  277. if (!list_expr)
  278. return nullptr;
  279. auto cast = create<AST::CastToCommand>(move(list_expr)); // Cast List Command
  280. auto next_command = parse_command();
  281. if (!next_command)
  282. return cast;
  283. return create<AST::Join>(move(cast), move(next_command)); // Join List Command
  284. }
  285. auto command = parse_command();
  286. if (!command)
  287. return redir;
  288. return create<AST::Join>(move(redir), command); // Join Command Command
  289. }
  290. RefPtr<AST::Node> Parser::parse_control_structure()
  291. {
  292. auto rule_start = push_start();
  293. consume_while(is_whitespace);
  294. if (auto for_loop = parse_for_loop())
  295. return for_loop;
  296. return nullptr;
  297. }
  298. RefPtr<AST::Node> Parser::parse_for_loop()
  299. {
  300. auto rule_start = push_start();
  301. if (!expect("for")) {
  302. m_offset = rule_start->offset;
  303. return nullptr;
  304. }
  305. if (consume_while(is_any_of(" \t\n")).is_empty()) {
  306. m_offset = rule_start->offset;
  307. return nullptr;
  308. }
  309. auto variable_name = consume_while(is_word_character);
  310. Optional<size_t> in_start_position;
  311. if (variable_name.is_empty()) {
  312. variable_name = "it";
  313. } else {
  314. consume_while(is_whitespace);
  315. auto in_error_start = push_start();
  316. in_start_position = in_error_start->offset;
  317. if (!expect("in")) {
  318. auto syntax_error = create<AST::SyntaxError>("Expected 'in' after a variable name in a 'for' loop");
  319. return create<AST::ForLoop>(move(variable_name), move(syntax_error), nullptr); // ForLoop Var Iterated Block
  320. }
  321. }
  322. consume_while(is_whitespace);
  323. RefPtr<AST::Node> iterated_expression;
  324. {
  325. auto iter_error_start = push_start();
  326. iterated_expression = parse_expression();
  327. if (!iterated_expression) {
  328. auto syntax_error = create<AST::SyntaxError>("Expected an expression in 'for' loop");
  329. return create<AST::ForLoop>(move(variable_name), move(syntax_error), nullptr, move(in_start_position)); // ForLoop Var Iterated Block
  330. }
  331. }
  332. consume_while(is_any_of(" \t\n"));
  333. {
  334. auto obrace_error_start = push_start();
  335. if (!expect('{')) {
  336. auto syntax_error = create<AST::SyntaxError>("Expected an open brace '{' to start a 'for' loop body");
  337. return create<AST::ForLoop>(move(variable_name), move(iterated_expression), move(syntax_error), move(in_start_position)); // ForLoop Var Iterated Block
  338. }
  339. }
  340. auto body = parse_toplevel();
  341. {
  342. auto cbrace_error_start = push_start();
  343. if (!expect('}')) {
  344. auto error_start = push_start();
  345. RefPtr<AST::SyntaxError> syntax_error = create<AST::SyntaxError>("Expected a close brace '}' to end a 'for' loop body");
  346. if (body)
  347. body->set_is_syntax_error(*syntax_error);
  348. else
  349. body = syntax_error;
  350. }
  351. }
  352. return create<AST::ForLoop>(move(variable_name), move(iterated_expression), move(body), move(in_start_position)); // ForLoop Var Iterated Block
  353. }
  354. RefPtr<AST::Node> Parser::parse_redirection()
  355. {
  356. auto rule_start = push_start();
  357. auto pipe_fd = 0;
  358. auto number = consume_while(is_digit);
  359. if (number.is_empty()) {
  360. pipe_fd = -1;
  361. } else {
  362. auto fd = number.to_int();
  363. ASSERT(fd.has_value());
  364. pipe_fd = fd.value();
  365. }
  366. switch (peek()) {
  367. case '>': {
  368. consume();
  369. if (peek() == '>') {
  370. consume();
  371. consume_while(is_whitespace);
  372. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  373. auto path = parse_expression();
  374. if (!path) {
  375. if (!at_end()) {
  376. // Eat a character and hope the problem goes away
  377. consume();
  378. }
  379. return create<AST::SyntaxError>("Expected a path");
  380. }
  381. return create<AST::WriteAppendRedirection>(pipe_fd, move(path)); // Redirection WriteAppend
  382. }
  383. if (peek() == '&') {
  384. consume();
  385. // FIXME: 'fd>&-' Syntax not the best. needs discussion.
  386. if (peek() == '-') {
  387. consume();
  388. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  389. return create<AST::CloseFdRedirection>(pipe_fd); // Redirection CloseFd
  390. }
  391. int dest_pipe_fd = 0;
  392. auto number = consume_while(is_digit);
  393. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  394. if (number.is_empty()) {
  395. dest_pipe_fd = -1;
  396. } else {
  397. auto fd = number.to_int();
  398. ASSERT(fd.has_value());
  399. dest_pipe_fd = fd.value();
  400. }
  401. auto redir = create<AST::Fd2FdRedirection>(pipe_fd, dest_pipe_fd); // Redirection Fd2Fd
  402. if (dest_pipe_fd == -1)
  403. redir->set_is_syntax_error(*create<AST::SyntaxError>("Expected a file descriptor"));
  404. return redir;
  405. }
  406. consume_while(is_whitespace);
  407. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  408. auto path = parse_expression();
  409. if (!path) {
  410. if (!at_end()) {
  411. // Eat a character and hope the problem goes away
  412. consume();
  413. }
  414. return create<AST::SyntaxError>("Expected a path");
  415. }
  416. return create<AST::WriteRedirection>(pipe_fd, move(path)); // Redirection Write
  417. }
  418. case '<': {
  419. consume();
  420. enum {
  421. Read,
  422. ReadWrite,
  423. } mode { Read };
  424. if (peek() == '>') {
  425. mode = ReadWrite;
  426. consume();
  427. }
  428. consume_while(is_whitespace);
  429. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDIN_FILENO;
  430. auto path = parse_expression();
  431. if (!path) {
  432. if (!at_end()) {
  433. // Eat a character and hope the problem goes away
  434. consume();
  435. }
  436. return create<AST::SyntaxError>("Expected a path");
  437. }
  438. if (mode == Read)
  439. return create<AST::ReadRedirection>(pipe_fd, move(path)); // Redirection Read
  440. return create<AST::ReadWriteRedirection>(pipe_fd, move(path)); // Redirection ReadWrite
  441. }
  442. default:
  443. return nullptr;
  444. }
  445. }
  446. RefPtr<AST::Node> Parser::parse_list_expression()
  447. {
  448. consume_while(is_whitespace);
  449. auto rule_start = push_start();
  450. Vector<RefPtr<AST::Node>> nodes;
  451. do {
  452. auto expr = parse_expression();
  453. if (!expr)
  454. break;
  455. nodes.append(move(expr));
  456. } while (!consume_while(is_whitespace).is_empty());
  457. if (nodes.is_empty())
  458. return nullptr;
  459. return create<AST::ListConcatenate>(move(nodes)); // Concatenate List
  460. }
  461. RefPtr<AST::Node> Parser::parse_expression()
  462. {
  463. auto rule_start = push_start();
  464. auto starting_char = peek();
  465. auto read_concat = [&](auto expr) -> RefPtr<AST::Node> {
  466. if (is_whitespace(peek()))
  467. return expr;
  468. if (auto next_expr = parse_expression())
  469. return create<AST::Juxtaposition>(move(expr), move(next_expr));
  470. return expr;
  471. };
  472. if (strchr("&|){} ;<>\n", starting_char) != nullptr)
  473. return nullptr;
  474. if (isdigit(starting_char)) {
  475. ScopedValueRollback offset_rollback { m_offset };
  476. auto redir = parse_redirection();
  477. if (redir)
  478. return nullptr;
  479. }
  480. if (starting_char == '$') {
  481. if (auto variable = parse_variable())
  482. return read_concat(variable);
  483. if (auto inline_exec = parse_evaluate())
  484. return read_concat(inline_exec);
  485. }
  486. if (starting_char == '#')
  487. return parse_comment();
  488. if (starting_char == '(') {
  489. consume();
  490. auto list = parse_list_expression();
  491. if (!expect(')')) {
  492. m_offset = rule_start->offset;
  493. return nullptr;
  494. }
  495. return read_concat(create<AST::CastToList>(move(list))); // Cast To List
  496. }
  497. return read_concat(parse_string_composite());
  498. }
  499. RefPtr<AST::Node> Parser::parse_string_composite()
  500. {
  501. auto rule_start = push_start();
  502. if (auto string = parse_string()) {
  503. if (auto next_part = parse_string_composite())
  504. return create<AST::Juxtaposition>(move(string), move(next_part)); // Concatenate String StringComposite
  505. return string;
  506. }
  507. if (auto variable = parse_variable()) {
  508. if (auto next_part = parse_string_composite())
  509. return create<AST::Juxtaposition>(move(variable), move(next_part)); // Concatenate Variable StringComposite
  510. return variable;
  511. }
  512. if (auto glob = parse_glob()) {
  513. if (auto next_part = parse_string_composite())
  514. return create<AST::Juxtaposition>(move(glob), move(next_part)); // Concatenate Glob StringComposite
  515. return glob;
  516. }
  517. if (auto bareword = parse_bareword()) {
  518. if (auto next_part = parse_string_composite())
  519. return create<AST::Juxtaposition>(move(bareword), move(next_part)); // Concatenate Bareword StringComposite
  520. return bareword;
  521. }
  522. if (auto inline_command = parse_evaluate()) {
  523. if (auto next_part = parse_string_composite())
  524. return create<AST::Juxtaposition>(move(inline_command), move(next_part)); // Concatenate Execute StringComposite
  525. return inline_command;
  526. }
  527. return nullptr;
  528. }
  529. RefPtr<AST::Node> Parser::parse_string()
  530. {
  531. auto rule_start = push_start();
  532. if (at_end())
  533. return nullptr;
  534. if (peek() == '"') {
  535. consume();
  536. auto inner = parse_doublequoted_string_inner();
  537. if (!inner)
  538. inner = create<AST::SyntaxError>("Unexpected EOF in string");
  539. if (!expect('"')) {
  540. inner = create<AST::DoubleQuotedString>(move(inner));
  541. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating double quote"));
  542. return inner;
  543. }
  544. return create<AST::DoubleQuotedString>(move(inner)); // Double Quoted String
  545. }
  546. if (peek() == '\'') {
  547. consume();
  548. auto text = consume_while(is_not('\''));
  549. bool is_error = false;
  550. if (!expect('\''))
  551. is_error = true;
  552. auto result = create<AST::StringLiteral>(move(text)); // String Literal
  553. if (is_error)
  554. result->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating single quote"));
  555. return move(result);
  556. }
  557. return nullptr;
  558. }
  559. RefPtr<AST::Node> Parser::parse_doublequoted_string_inner()
  560. {
  561. auto rule_start = push_start();
  562. if (at_end())
  563. return nullptr;
  564. StringBuilder builder;
  565. while (!at_end() && peek() != '"') {
  566. if (peek() == '\\') {
  567. consume();
  568. if (at_end()) {
  569. break;
  570. }
  571. auto ch = consume();
  572. switch (ch) {
  573. case '\\':
  574. default:
  575. builder.append(ch);
  576. break;
  577. case 'x': {
  578. if (m_input.length() <= m_offset + 2)
  579. break;
  580. auto first_nibble = tolower(consume());
  581. auto second_nibble = tolower(consume());
  582. if (!isxdigit(first_nibble) || !isxdigit(second_nibble)) {
  583. builder.append(first_nibble);
  584. builder.append(second_nibble);
  585. break;
  586. }
  587. builder.append(to_byte(first_nibble, second_nibble));
  588. break;
  589. }
  590. case 'a':
  591. builder.append('\a');
  592. break;
  593. case 'b':
  594. builder.append('\b');
  595. break;
  596. case 'e':
  597. builder.append('\x1b');
  598. break;
  599. case 'f':
  600. builder.append('\f');
  601. break;
  602. case 'r':
  603. builder.append('\r');
  604. break;
  605. case 'n':
  606. builder.append('\n');
  607. break;
  608. }
  609. continue;
  610. }
  611. if (peek() == '$') {
  612. auto string_literal = create<AST::StringLiteral>(builder.to_string()); // String Literal
  613. if (auto variable = parse_variable()) {
  614. auto inner = create<AST::StringPartCompose>(
  615. move(string_literal),
  616. move(variable)); // Compose String Variable
  617. if (auto string = parse_doublequoted_string_inner()) {
  618. return create<AST::StringPartCompose>(move(inner), move(string)); // Compose Composition Composition
  619. }
  620. return inner;
  621. }
  622. if (auto evaluate = parse_evaluate()) {
  623. auto composition = create<AST::StringPartCompose>(
  624. move(string_literal),
  625. move(evaluate)); // Compose String Sequence
  626. if (auto string = parse_doublequoted_string_inner()) {
  627. return create<AST::StringPartCompose>(move(composition), move(string)); // Compose Composition Composition
  628. }
  629. return composition;
  630. }
  631. }
  632. builder.append(consume());
  633. }
  634. return create<AST::StringLiteral>(builder.to_string()); // String Literal
  635. }
  636. RefPtr<AST::Node> Parser::parse_variable()
  637. {
  638. auto rule_start = push_start();
  639. if (at_end())
  640. return nullptr;
  641. if (peek() != '$')
  642. return nullptr;
  643. consume();
  644. switch (peek()) {
  645. case '$':
  646. case '?':
  647. case '*':
  648. case '#':
  649. return create<AST::SpecialVariable>(consume()); // Variable Special
  650. default:
  651. break;
  652. }
  653. auto name = consume_while(is_word_character);
  654. if (name.length() == 0) {
  655. putback();
  656. return nullptr;
  657. }
  658. return create<AST::SimpleVariable>(move(name)); // Variable Simple
  659. }
  660. RefPtr<AST::Node> Parser::parse_evaluate()
  661. {
  662. auto rule_start = push_start();
  663. if (at_end())
  664. return nullptr;
  665. if (peek() != '$')
  666. return nullptr;
  667. consume();
  668. if (peek() == '(') {
  669. consume();
  670. auto inner = parse_pipe_sequence();
  671. if (!inner)
  672. inner = create<AST::SyntaxError>("Unexpected EOF in list");
  673. if (!expect(')'))
  674. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating close paren"));
  675. return create<AST::Execute>(move(inner), true);
  676. }
  677. auto inner = parse_expression();
  678. if (!inner) {
  679. inner = create<AST::SyntaxError>("Expected a command");
  680. } else {
  681. if (inner->is_list()) {
  682. auto execute_inner = create<AST::Execute>(move(inner), true);
  683. inner = execute_inner;
  684. } else {
  685. auto dyn_inner = create<AST::DynamicEvaluate>(move(inner));
  686. inner = dyn_inner;
  687. }
  688. }
  689. return inner;
  690. }
  691. RefPtr<AST::Node> Parser::parse_comment()
  692. {
  693. if (at_end())
  694. return nullptr;
  695. if (peek() != '#')
  696. return nullptr;
  697. consume();
  698. auto text = consume_while(is_not('\n'));
  699. return create<AST::Comment>(move(text)); // Comment
  700. }
  701. RefPtr<AST::Node> Parser::parse_bareword()
  702. {
  703. auto rule_start = push_start();
  704. StringBuilder builder;
  705. auto is_acceptable_bareword_character = [](char c) {
  706. return strchr("\\\"'*$&#|(){} ?;<>\n", c) == nullptr;
  707. };
  708. while (!at_end()) {
  709. char ch = peek();
  710. if (ch == '\\') {
  711. consume();
  712. if (!at_end()) {
  713. ch = consume();
  714. if (is_acceptable_bareword_character(ch))
  715. builder.append('\\');
  716. }
  717. builder.append(ch);
  718. continue;
  719. }
  720. if (is_acceptable_bareword_character(ch)) {
  721. builder.append(consume());
  722. continue;
  723. }
  724. break;
  725. }
  726. if (builder.is_empty())
  727. return nullptr;
  728. auto current_end = m_offset;
  729. auto string = builder.to_string();
  730. if (string.starts_with('~')) {
  731. String username;
  732. RefPtr<AST::Node> tilde, text;
  733. auto first_slash_index = string.index_of("/");
  734. if (first_slash_index.has_value()) {
  735. username = string.substring_view(1, first_slash_index.value() - 1);
  736. string = string.substring_view(first_slash_index.value(), string.length() - first_slash_index.value());
  737. } else {
  738. username = string.substring_view(1, string.length() - 1);
  739. string = "";
  740. }
  741. // Synthesize a Tilde Node with the correct positioning information.
  742. {
  743. m_offset -= string.length();
  744. tilde = create<AST::Tilde>(move(username));
  745. }
  746. if (string.is_empty())
  747. return tilde;
  748. // Synthesize a BarewordLiteral Node with the correct positioning information.
  749. {
  750. m_offset = tilde->position().end_offset;
  751. auto text_start = push_start();
  752. m_offset = current_end;
  753. text = create<AST::BarewordLiteral>(move(string));
  754. }
  755. return create<AST::Juxtaposition>(move(tilde), move(text)); // Juxtaposition Varible Bareword
  756. }
  757. if (string.starts_with("\\~")) {
  758. // Un-escape the tilde, but only at the start (where it would be an expansion)
  759. string = string.substring(1, string.length() - 1);
  760. }
  761. return create<AST::BarewordLiteral>(move(string)); // Bareword Literal
  762. }
  763. RefPtr<AST::Node> Parser::parse_glob()
  764. {
  765. auto rule_start = push_start();
  766. auto bareword_part = parse_bareword();
  767. if (at_end())
  768. return bareword_part;
  769. char ch = peek();
  770. if (ch == '*' || ch == '?') {
  771. consume();
  772. StringBuilder textbuilder;
  773. if (bareword_part) {
  774. StringView text;
  775. if (bareword_part->is_bareword()) {
  776. auto bareword = static_cast<AST::BarewordLiteral*>(bareword_part.ptr());
  777. text = bareword->text();
  778. } else {
  779. // FIXME: Allow composition of tilde+bareword with globs: '~/foo/bar/baz*'
  780. putback();
  781. bareword_part->set_is_syntax_error(*create<AST::SyntaxError>(String::format("Unexpected %s inside a glob", bareword_part->class_name().characters())));
  782. return bareword_part;
  783. }
  784. textbuilder.append(text);
  785. }
  786. textbuilder.append(ch);
  787. auto glob_after = parse_glob();
  788. if (glob_after) {
  789. if (glob_after->is_glob()) {
  790. auto glob = static_cast<AST::BarewordLiteral*>(glob_after.ptr());
  791. textbuilder.append(glob->text());
  792. } else if (glob_after->is_bareword()) {
  793. auto bareword = static_cast<AST::BarewordLiteral*>(glob_after.ptr());
  794. textbuilder.append(bareword->text());
  795. } else {
  796. ASSERT_NOT_REACHED();
  797. }
  798. }
  799. return create<AST::Glob>(textbuilder.to_string()); // Glob
  800. }
  801. return bareword_part;
  802. }
  803. StringView Parser::consume_while(Function<bool(char)> condition)
  804. {
  805. auto start_offset = m_offset;
  806. while (!at_end() && condition(peek()))
  807. consume();
  808. return m_input.substring_view(start_offset, m_offset - start_offset);
  809. }