Parser.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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. NonnullRefPtr<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), expression.release_nonnull() });
  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. m_offset = rule_start->offset;
  444. return nullptr;
  445. }
  446. }
  447. RefPtr<AST::Node> Parser::parse_list_expression()
  448. {
  449. consume_while(is_whitespace);
  450. auto rule_start = push_start();
  451. Vector<RefPtr<AST::Node>> nodes;
  452. do {
  453. auto expr = parse_expression();
  454. if (!expr)
  455. break;
  456. nodes.append(move(expr));
  457. } while (!consume_while(is_whitespace).is_empty());
  458. if (nodes.is_empty())
  459. return nullptr;
  460. return create<AST::ListConcatenate>(move(nodes)); // Concatenate List
  461. }
  462. RefPtr<AST::Node> Parser::parse_expression()
  463. {
  464. auto rule_start = push_start();
  465. auto starting_char = peek();
  466. auto read_concat = [&](auto expr) -> RefPtr<AST::Node> {
  467. if (is_whitespace(peek()))
  468. return expr;
  469. if (auto next_expr = parse_expression())
  470. return create<AST::Juxtaposition>(move(expr), move(next_expr));
  471. return expr;
  472. };
  473. if (strchr("&|){} ;<>\n", starting_char) != nullptr)
  474. return nullptr;
  475. if (isdigit(starting_char)) {
  476. ScopedValueRollback offset_rollback { m_offset };
  477. auto redir = parse_redirection();
  478. if (redir)
  479. return nullptr;
  480. }
  481. if (starting_char == '$') {
  482. if (auto variable = parse_variable())
  483. return read_concat(variable);
  484. if (auto inline_exec = parse_evaluate())
  485. return read_concat(inline_exec);
  486. }
  487. if (starting_char == '#')
  488. return parse_comment();
  489. if (starting_char == '(') {
  490. consume();
  491. auto list = parse_list_expression();
  492. if (!expect(')')) {
  493. m_offset = rule_start->offset;
  494. return nullptr;
  495. }
  496. return read_concat(create<AST::CastToList>(move(list))); // Cast To List
  497. }
  498. return read_concat(parse_string_composite());
  499. }
  500. RefPtr<AST::Node> Parser::parse_string_composite()
  501. {
  502. auto rule_start = push_start();
  503. if (auto string = parse_string()) {
  504. if (auto next_part = parse_string_composite())
  505. return create<AST::Juxtaposition>(move(string), move(next_part)); // Concatenate String StringComposite
  506. return string;
  507. }
  508. if (auto variable = parse_variable()) {
  509. if (auto next_part = parse_string_composite())
  510. return create<AST::Juxtaposition>(move(variable), move(next_part)); // Concatenate Variable StringComposite
  511. return variable;
  512. }
  513. if (auto glob = parse_glob()) {
  514. if (auto next_part = parse_string_composite())
  515. return create<AST::Juxtaposition>(move(glob), move(next_part)); // Concatenate Glob StringComposite
  516. return glob;
  517. }
  518. if (auto bareword = parse_bareword()) {
  519. if (auto next_part = parse_string_composite())
  520. return create<AST::Juxtaposition>(move(bareword), move(next_part)); // Concatenate Bareword StringComposite
  521. return bareword;
  522. }
  523. if (auto inline_command = parse_evaluate()) {
  524. if (auto next_part = parse_string_composite())
  525. return create<AST::Juxtaposition>(move(inline_command), move(next_part)); // Concatenate Execute StringComposite
  526. return inline_command;
  527. }
  528. return nullptr;
  529. }
  530. RefPtr<AST::Node> Parser::parse_string()
  531. {
  532. auto rule_start = push_start();
  533. if (at_end())
  534. return nullptr;
  535. if (peek() == '"') {
  536. consume();
  537. auto inner = parse_doublequoted_string_inner();
  538. if (!inner)
  539. inner = create<AST::SyntaxError>("Unexpected EOF in string");
  540. if (!expect('"')) {
  541. inner = create<AST::DoubleQuotedString>(move(inner));
  542. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating double quote"));
  543. return inner;
  544. }
  545. return create<AST::DoubleQuotedString>(move(inner)); // Double Quoted String
  546. }
  547. if (peek() == '\'') {
  548. consume();
  549. auto text = consume_while(is_not('\''));
  550. bool is_error = false;
  551. if (!expect('\''))
  552. is_error = true;
  553. auto result = create<AST::StringLiteral>(move(text)); // String Literal
  554. if (is_error)
  555. result->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating single quote"));
  556. return move(result);
  557. }
  558. return nullptr;
  559. }
  560. RefPtr<AST::Node> Parser::parse_doublequoted_string_inner()
  561. {
  562. auto rule_start = push_start();
  563. if (at_end())
  564. return nullptr;
  565. StringBuilder builder;
  566. while (!at_end() && peek() != '"') {
  567. if (peek() == '\\') {
  568. consume();
  569. if (at_end()) {
  570. break;
  571. }
  572. auto ch = consume();
  573. switch (ch) {
  574. case '\\':
  575. default:
  576. builder.append(ch);
  577. break;
  578. case 'x': {
  579. if (m_input.length() <= m_offset + 2)
  580. break;
  581. auto first_nibble = tolower(consume());
  582. auto second_nibble = tolower(consume());
  583. if (!isxdigit(first_nibble) || !isxdigit(second_nibble)) {
  584. builder.append(first_nibble);
  585. builder.append(second_nibble);
  586. break;
  587. }
  588. builder.append(to_byte(first_nibble, second_nibble));
  589. break;
  590. }
  591. case 'a':
  592. builder.append('\a');
  593. break;
  594. case 'b':
  595. builder.append('\b');
  596. break;
  597. case 'e':
  598. builder.append('\x1b');
  599. break;
  600. case 'f':
  601. builder.append('\f');
  602. break;
  603. case 'r':
  604. builder.append('\r');
  605. break;
  606. case 'n':
  607. builder.append('\n');
  608. break;
  609. }
  610. continue;
  611. }
  612. if (peek() == '$') {
  613. auto string_literal = create<AST::StringLiteral>(builder.to_string()); // String Literal
  614. if (auto variable = parse_variable()) {
  615. auto inner = create<AST::StringPartCompose>(
  616. move(string_literal),
  617. move(variable)); // Compose String Variable
  618. if (auto string = parse_doublequoted_string_inner()) {
  619. return create<AST::StringPartCompose>(move(inner), move(string)); // Compose Composition Composition
  620. }
  621. return inner;
  622. }
  623. if (auto evaluate = parse_evaluate()) {
  624. auto composition = create<AST::StringPartCompose>(
  625. move(string_literal),
  626. move(evaluate)); // Compose String Sequence
  627. if (auto string = parse_doublequoted_string_inner()) {
  628. return create<AST::StringPartCompose>(move(composition), move(string)); // Compose Composition Composition
  629. }
  630. return composition;
  631. }
  632. }
  633. builder.append(consume());
  634. }
  635. return create<AST::StringLiteral>(builder.to_string()); // String Literal
  636. }
  637. RefPtr<AST::Node> Parser::parse_variable()
  638. {
  639. auto rule_start = push_start();
  640. if (at_end())
  641. return nullptr;
  642. if (peek() != '$')
  643. return nullptr;
  644. consume();
  645. switch (peek()) {
  646. case '$':
  647. case '?':
  648. case '*':
  649. case '#':
  650. return create<AST::SpecialVariable>(consume()); // Variable Special
  651. default:
  652. break;
  653. }
  654. auto name = consume_while(is_word_character);
  655. if (name.length() == 0) {
  656. putback();
  657. return nullptr;
  658. }
  659. return create<AST::SimpleVariable>(move(name)); // Variable Simple
  660. }
  661. RefPtr<AST::Node> Parser::parse_evaluate()
  662. {
  663. auto rule_start = push_start();
  664. if (at_end())
  665. return nullptr;
  666. if (peek() != '$')
  667. return nullptr;
  668. consume();
  669. if (peek() == '(') {
  670. consume();
  671. auto inner = parse_pipe_sequence();
  672. if (!inner)
  673. inner = create<AST::SyntaxError>("Unexpected EOF in list");
  674. if (!expect(')'))
  675. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating close paren"));
  676. return create<AST::Execute>(move(inner), true);
  677. }
  678. auto inner = parse_expression();
  679. if (!inner) {
  680. inner = create<AST::SyntaxError>("Expected a command");
  681. } else {
  682. if (inner->is_list()) {
  683. auto execute_inner = create<AST::Execute>(move(inner), true);
  684. inner = execute_inner;
  685. } else {
  686. auto dyn_inner = create<AST::DynamicEvaluate>(move(inner));
  687. inner = dyn_inner;
  688. }
  689. }
  690. return inner;
  691. }
  692. RefPtr<AST::Node> Parser::parse_comment()
  693. {
  694. if (at_end())
  695. return nullptr;
  696. if (peek() != '#')
  697. return nullptr;
  698. consume();
  699. auto text = consume_while(is_not('\n'));
  700. return create<AST::Comment>(move(text)); // Comment
  701. }
  702. RefPtr<AST::Node> Parser::parse_bareword()
  703. {
  704. auto rule_start = push_start();
  705. StringBuilder builder;
  706. auto is_acceptable_bareword_character = [](char c) {
  707. return strchr("\\\"'*$&#|(){} ?;<>\n", c) == nullptr;
  708. };
  709. while (!at_end()) {
  710. char ch = peek();
  711. if (ch == '\\') {
  712. consume();
  713. if (!at_end()) {
  714. ch = consume();
  715. if (is_acceptable_bareword_character(ch))
  716. builder.append('\\');
  717. }
  718. builder.append(ch);
  719. continue;
  720. }
  721. if (is_acceptable_bareword_character(ch)) {
  722. builder.append(consume());
  723. continue;
  724. }
  725. break;
  726. }
  727. if (builder.is_empty())
  728. return nullptr;
  729. auto current_end = m_offset;
  730. auto string = builder.to_string();
  731. if (string.starts_with('~')) {
  732. String username;
  733. RefPtr<AST::Node> tilde, text;
  734. auto first_slash_index = string.index_of("/");
  735. if (first_slash_index.has_value()) {
  736. username = string.substring_view(1, first_slash_index.value() - 1);
  737. string = string.substring_view(first_slash_index.value(), string.length() - first_slash_index.value());
  738. } else {
  739. username = string.substring_view(1, string.length() - 1);
  740. string = "";
  741. }
  742. // Synthesize a Tilde Node with the correct positioning information.
  743. {
  744. m_offset -= string.length();
  745. tilde = create<AST::Tilde>(move(username));
  746. }
  747. if (string.is_empty())
  748. return tilde;
  749. // Synthesize a BarewordLiteral Node with the correct positioning information.
  750. {
  751. m_offset = tilde->position().end_offset;
  752. auto text_start = push_start();
  753. m_offset = current_end;
  754. text = create<AST::BarewordLiteral>(move(string));
  755. }
  756. return create<AST::Juxtaposition>(move(tilde), move(text)); // Juxtaposition Varible Bareword
  757. }
  758. if (string.starts_with("\\~")) {
  759. // Un-escape the tilde, but only at the start (where it would be an expansion)
  760. string = string.substring(1, string.length() - 1);
  761. }
  762. return create<AST::BarewordLiteral>(move(string)); // Bareword Literal
  763. }
  764. RefPtr<AST::Node> Parser::parse_glob()
  765. {
  766. auto rule_start = push_start();
  767. auto bareword_part = parse_bareword();
  768. if (at_end())
  769. return bareword_part;
  770. char ch = peek();
  771. if (ch == '*' || ch == '?') {
  772. consume();
  773. StringBuilder textbuilder;
  774. if (bareword_part) {
  775. StringView text;
  776. if (bareword_part->is_bareword()) {
  777. auto bareword = static_cast<AST::BarewordLiteral*>(bareword_part.ptr());
  778. text = bareword->text();
  779. } else {
  780. // FIXME: Allow composition of tilde+bareword with globs: '~/foo/bar/baz*'
  781. putback();
  782. bareword_part->set_is_syntax_error(*create<AST::SyntaxError>(String::format("Unexpected %s inside a glob", bareword_part->class_name().characters())));
  783. return bareword_part;
  784. }
  785. textbuilder.append(text);
  786. }
  787. textbuilder.append(ch);
  788. auto glob_after = parse_glob();
  789. if (glob_after) {
  790. if (glob_after->is_glob()) {
  791. auto glob = static_cast<AST::BarewordLiteral*>(glob_after.ptr());
  792. textbuilder.append(glob->text());
  793. } else if (glob_after->is_bareword()) {
  794. auto bareword = static_cast<AST::BarewordLiteral*>(glob_after.ptr());
  795. textbuilder.append(bareword->text());
  796. } else {
  797. ASSERT_NOT_REACHED();
  798. }
  799. }
  800. return create<AST::Glob>(textbuilder.to_string()); // Glob
  801. }
  802. return bareword_part;
  803. }
  804. StringView Parser::consume_while(Function<bool(char)> condition)
  805. {
  806. auto start_offset = m_offset;
  807. while (!at_end() && condition(peek()))
  808. consume();
  809. return m_input.substring_view(start_offset, m_offset - start_offset);
  810. }