Parser.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476
  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 <AK/TemporaryChange.h>
  28. #include <ctype.h>
  29. #include <stdio.h>
  30. #include <unistd.h>
  31. namespace Shell {
  32. Parser::SavedOffset Parser::save_offset() const
  33. {
  34. return { m_offset, m_line };
  35. }
  36. char Parser::peek()
  37. {
  38. if (at_end())
  39. return 0;
  40. ASSERT(m_offset < m_input.length());
  41. auto ch = m_input[m_offset];
  42. if (ch == '\\' && m_input.length() > m_offset + 1 && m_input[m_offset + 1] == '\n') {
  43. m_offset += 2;
  44. ++m_line.line_number;
  45. m_line.line_column = 0;
  46. return peek();
  47. }
  48. return ch;
  49. }
  50. char Parser::consume()
  51. {
  52. if (at_end())
  53. return 0;
  54. auto ch = peek();
  55. ++m_offset;
  56. if (ch == '\n') {
  57. ++m_line.line_number;
  58. m_line.line_column = 0;
  59. } else {
  60. ++m_line.line_column;
  61. }
  62. return ch;
  63. }
  64. bool Parser::expect(char ch)
  65. {
  66. return expect(StringView { &ch, 1 });
  67. }
  68. bool Parser::expect(const StringView& expected)
  69. {
  70. auto offset_at_start = m_offset;
  71. auto line_at_start = line();
  72. if (expected.length() + m_offset > m_input.length())
  73. return false;
  74. for (size_t i = 0; i < expected.length(); ++i) {
  75. if (peek() != expected[i]) {
  76. restore_to(offset_at_start, line_at_start);
  77. return false;
  78. }
  79. consume();
  80. }
  81. return true;
  82. }
  83. template<typename A, typename... Args>
  84. NonnullRefPtr<A> Parser::create(Args... args)
  85. {
  86. return adopt(*new A(AST::Position { m_rule_start_offsets.last(), m_offset, m_rule_start_lines.last(), line() }, args...));
  87. }
  88. [[nodiscard]] OwnPtr<Parser::ScopedOffset> Parser::push_start()
  89. {
  90. return make<ScopedOffset>(m_rule_start_offsets, m_rule_start_lines, m_offset, m_line.line_number, m_line.line_column);
  91. }
  92. static constexpr bool is_whitespace(char c)
  93. {
  94. return c == ' ' || c == '\t';
  95. }
  96. static constexpr bool is_word_character(char c)
  97. {
  98. return (c <= '9' && c >= '0') || (c <= 'Z' && c >= 'A') || (c <= 'z' && c >= 'a') || c == '_';
  99. }
  100. static constexpr bool is_digit(char c)
  101. {
  102. return c <= '9' && c >= '0';
  103. }
  104. static constexpr auto is_not(char c)
  105. {
  106. return [c](char ch) { return ch != c; };
  107. }
  108. static inline char to_byte(char a, char b)
  109. {
  110. char buf[3] { a, b, 0 };
  111. return strtol(buf, nullptr, 16);
  112. }
  113. RefPtr<AST::Node> Parser::parse()
  114. {
  115. m_offset = 0;
  116. m_line = { 0, 0 };
  117. auto toplevel = parse_toplevel();
  118. if (m_offset < m_input.length()) {
  119. // Parsing stopped midway, this is a syntax error.
  120. auto error_start = push_start();
  121. while (!at_end())
  122. consume();
  123. auto syntax_error_node = create<AST::SyntaxError>("Unexpected tokens past the end");
  124. if (!toplevel)
  125. toplevel = move(syntax_error_node);
  126. else
  127. toplevel->set_is_syntax_error(*syntax_error_node);
  128. }
  129. return toplevel;
  130. }
  131. RefPtr<AST::Node> Parser::parse_toplevel()
  132. {
  133. auto rule_start = push_start();
  134. if (auto sequence = parse_sequence())
  135. return create<AST::Execute>(sequence.release_nonnull());
  136. return nullptr;
  137. }
  138. RefPtr<AST::Node> Parser::parse_sequence()
  139. {
  140. consume_while(is_any_of(" \t\n;")); // ignore whitespaces or terminators without effect.
  141. auto rule_start = push_start();
  142. auto var_decls = parse_variable_decls();
  143. auto pos_before_seps = save_offset();
  144. switch (peek()) {
  145. case '}':
  146. return var_decls;
  147. case ';':
  148. case '\n': {
  149. if (!var_decls)
  150. break;
  151. consume_while(is_any_of("\n;"));
  152. auto pos_after_seps = save_offset();
  153. auto rest = parse_sequence();
  154. if (rest)
  155. return create<AST::Sequence>(
  156. var_decls.release_nonnull(),
  157. rest.release_nonnull(),
  158. AST::Position { pos_before_seps.offset, pos_after_seps.offset, pos_before_seps.line, pos_after_seps.line });
  159. return var_decls;
  160. }
  161. default:
  162. break;
  163. }
  164. auto first = parse_function_decl();
  165. if (!first)
  166. first = parse_or_logical_sequence();
  167. if (!first)
  168. return var_decls;
  169. if (var_decls)
  170. first = create<AST::Sequence>(
  171. var_decls.release_nonnull(),
  172. first.release_nonnull(),
  173. AST::Position { pos_before_seps.offset, pos_before_seps.offset, pos_before_seps.line, pos_before_seps.line });
  174. consume_while(is_whitespace);
  175. pos_before_seps = save_offset();
  176. switch (peek()) {
  177. case ';':
  178. case '\n': {
  179. consume_while(is_any_of("\n;"));
  180. auto pos_after_seps = save_offset();
  181. if (auto expr = parse_sequence()) {
  182. return create<AST::Sequence>(
  183. first.release_nonnull(),
  184. expr.release_nonnull(),
  185. AST::Position { pos_before_seps.offset, pos_after_seps.offset, pos_before_seps.line, pos_after_seps.line }); // Sequence
  186. }
  187. return first;
  188. }
  189. case '&': {
  190. consume();
  191. auto pos_after_seps = save_offset();
  192. auto bg = create<AST::Background>(first.release_nonnull()); // Execute Background
  193. if (auto rest = parse_sequence())
  194. return create<AST::Sequence>(
  195. move(bg),
  196. rest.release_nonnull(),
  197. AST::Position { pos_before_seps.offset, pos_after_seps.offset, pos_before_seps.line, pos_before_seps.line }); // Sequence Background Sequence
  198. return bg;
  199. }
  200. default:
  201. return first;
  202. }
  203. }
  204. RefPtr<AST::Node> Parser::parse_variable_decls()
  205. {
  206. auto rule_start = push_start();
  207. consume_while(is_whitespace);
  208. auto pos_before_name = save_offset();
  209. auto var_name = consume_while(is_word_character);
  210. if (var_name.is_empty())
  211. return nullptr;
  212. if (!expect('=')) {
  213. restore_to(pos_before_name.offset, pos_before_name.line);
  214. return nullptr;
  215. }
  216. auto name_expr = create<AST::BarewordLiteral>(move(var_name));
  217. auto start = push_start();
  218. auto expression = parse_expression();
  219. if (!expression || expression->is_syntax_error()) {
  220. restore_to(*start);
  221. if (peek() == '(') {
  222. consume();
  223. auto command = parse_pipe_sequence();
  224. if (!command)
  225. restore_to(*start);
  226. else if (!expect(')'))
  227. command->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating close paren"));
  228. expression = command;
  229. }
  230. }
  231. if (!expression) {
  232. if (is_whitespace(peek())) {
  233. auto string_start = push_start();
  234. expression = create<AST::StringLiteral>("");
  235. } else {
  236. restore_to(pos_before_name.offset, pos_before_name.line);
  237. return nullptr;
  238. }
  239. }
  240. Vector<AST::VariableDeclarations::Variable> variables;
  241. variables.append({ move(name_expr), expression.release_nonnull() });
  242. if (consume_while(is_whitespace).is_empty())
  243. return create<AST::VariableDeclarations>(move(variables));
  244. auto rest = parse_variable_decls();
  245. if (!rest)
  246. return create<AST::VariableDeclarations>(move(variables));
  247. ASSERT(rest->is_variable_decls());
  248. auto* rest_decl = static_cast<AST::VariableDeclarations*>(rest.ptr());
  249. variables.append(rest_decl->variables());
  250. return create<AST::VariableDeclarations>(move(variables));
  251. }
  252. RefPtr<AST::Node> Parser::parse_function_decl()
  253. {
  254. auto rule_start = push_start();
  255. auto restore = [&] {
  256. restore_to(*rule_start);
  257. return nullptr;
  258. };
  259. consume_while(is_whitespace);
  260. auto pos_before_name = save_offset();
  261. auto function_name = consume_while(is_word_character);
  262. auto pos_after_name = save_offset();
  263. if (function_name.is_empty())
  264. return restore();
  265. if (!expect('('))
  266. return restore();
  267. Vector<AST::FunctionDeclaration::NameWithPosition> arguments;
  268. for (;;) {
  269. consume_while(is_whitespace);
  270. if (expect(')'))
  271. break;
  272. auto name_offset = m_offset;
  273. auto start_line = line();
  274. auto arg_name = consume_while(is_word_character);
  275. if (arg_name.is_empty()) {
  276. // FIXME: Should this be a syntax error, or just return?
  277. return restore();
  278. }
  279. arguments.append({ arg_name, { name_offset, m_offset, start_line, line() } });
  280. }
  281. consume_while(is_whitespace);
  282. {
  283. RefPtr<AST::Node> syntax_error;
  284. {
  285. auto obrace_error_start = push_start();
  286. syntax_error = create<AST::SyntaxError>("Expected an open brace '{' to start a function body");
  287. }
  288. if (!expect('{')) {
  289. return create<AST::FunctionDeclaration>(
  290. AST::FunctionDeclaration::NameWithPosition {
  291. move(function_name),
  292. { pos_before_name.offset, pos_after_name.offset, pos_before_name.line, pos_after_name.line } },
  293. move(arguments),
  294. move(syntax_error));
  295. }
  296. }
  297. auto body = parse_toplevel();
  298. {
  299. RefPtr<AST::SyntaxError> syntax_error;
  300. {
  301. auto cbrace_error_start = push_start();
  302. syntax_error = create<AST::SyntaxError>("Expected a close brace '}' to end a function body");
  303. }
  304. if (!expect('}')) {
  305. if (body)
  306. body->set_is_syntax_error(*syntax_error);
  307. else
  308. body = move(syntax_error);
  309. return create<AST::FunctionDeclaration>(
  310. AST::FunctionDeclaration::NameWithPosition {
  311. move(function_name),
  312. { pos_before_name.offset, pos_after_name.offset, pos_before_name.line, pos_after_name.line } },
  313. move(arguments),
  314. move(body));
  315. }
  316. }
  317. return create<AST::FunctionDeclaration>(
  318. AST::FunctionDeclaration::NameWithPosition {
  319. move(function_name),
  320. { pos_before_name.offset, pos_after_name.offset, pos_before_name.line, pos_after_name.line } },
  321. move(arguments),
  322. move(body));
  323. }
  324. RefPtr<AST::Node> Parser::parse_or_logical_sequence()
  325. {
  326. consume_while(is_whitespace);
  327. auto rule_start = push_start();
  328. auto and_sequence = parse_and_logical_sequence();
  329. if (!and_sequence)
  330. return nullptr;
  331. consume_while(is_whitespace);
  332. auto pos_before_or = save_offset();
  333. if (!expect("||"))
  334. return and_sequence;
  335. auto pos_after_or = save_offset();
  336. auto right_and_sequence = parse_and_logical_sequence();
  337. if (!right_and_sequence)
  338. right_and_sequence = create<AST::SyntaxError>("Expected an expression after '||'");
  339. return create<AST::Or>(
  340. and_sequence.release_nonnull(),
  341. right_and_sequence.release_nonnull(),
  342. AST::Position { pos_before_or.offset, pos_after_or.offset, pos_before_or.line, pos_after_or.line });
  343. }
  344. RefPtr<AST::Node> Parser::parse_and_logical_sequence()
  345. {
  346. consume_while(is_whitespace);
  347. auto rule_start = push_start();
  348. auto pipe_sequence = parse_pipe_sequence();
  349. if (!pipe_sequence)
  350. return nullptr;
  351. consume_while(is_whitespace);
  352. auto pos_before_and = save_offset();
  353. if (!expect("&&"))
  354. return pipe_sequence;
  355. auto pos_after_end = save_offset();
  356. auto right_and_sequence = parse_and_logical_sequence();
  357. if (!right_and_sequence)
  358. right_and_sequence = create<AST::SyntaxError>("Expected an expression after '&&'");
  359. return create<AST::And>(
  360. pipe_sequence.release_nonnull(),
  361. right_and_sequence.release_nonnull(),
  362. AST::Position { pos_before_and.offset, pos_after_end.offset, pos_before_and.line, pos_after_end.line });
  363. }
  364. RefPtr<AST::Node> Parser::parse_pipe_sequence()
  365. {
  366. auto rule_start = push_start();
  367. auto left = parse_control_structure();
  368. if (!left) {
  369. if (auto cmd = parse_command())
  370. left = cmd;
  371. else
  372. return nullptr;
  373. }
  374. consume_while(is_whitespace);
  375. if (peek() != '|')
  376. return left;
  377. auto before_pipe = save_offset();
  378. consume();
  379. if (auto pipe_seq = parse_pipe_sequence()) {
  380. return create<AST::Pipe>(left.release_nonnull(), pipe_seq.release_nonnull()); // Pipe
  381. }
  382. restore_to(before_pipe.offset, before_pipe.line);
  383. return left;
  384. }
  385. RefPtr<AST::Node> Parser::parse_command()
  386. {
  387. auto rule_start = push_start();
  388. consume_while(is_whitespace);
  389. auto redir = parse_redirection();
  390. if (!redir) {
  391. auto list_expr = parse_list_expression();
  392. if (!list_expr)
  393. return nullptr;
  394. auto cast = create<AST::CastToCommand>(list_expr.release_nonnull()); // Cast List Command
  395. auto next_command = parse_command();
  396. if (!next_command)
  397. return cast;
  398. return create<AST::Join>(move(cast), next_command.release_nonnull()); // Join List Command
  399. }
  400. auto command = parse_command();
  401. if (!command)
  402. return redir;
  403. return create<AST::Join>(redir.release_nonnull(), command.release_nonnull()); // Join Command Command
  404. }
  405. RefPtr<AST::Node> Parser::parse_control_structure()
  406. {
  407. auto rule_start = push_start();
  408. consume_while(is_whitespace);
  409. if (auto for_loop = parse_for_loop())
  410. return for_loop;
  411. if (auto if_expr = parse_if_expr())
  412. return if_expr;
  413. if (auto subshell = parse_subshell())
  414. return subshell;
  415. if (auto match = parse_match_expr())
  416. return match;
  417. return nullptr;
  418. }
  419. RefPtr<AST::Node> Parser::parse_for_loop()
  420. {
  421. auto rule_start = push_start();
  422. if (!expect("for"))
  423. return nullptr;
  424. if (consume_while(is_any_of(" \t\n")).is_empty()) {
  425. restore_to(*rule_start);
  426. return nullptr;
  427. }
  428. auto variable_name = consume_while(is_word_character);
  429. Optional<AST::Position> in_start_position;
  430. if (variable_name.is_empty()) {
  431. variable_name = "it";
  432. } else {
  433. consume_while(is_whitespace);
  434. auto in_error_start = push_start();
  435. if (!expect("in")) {
  436. auto syntax_error = create<AST::SyntaxError>("Expected 'in' after a variable name in a 'for' loop");
  437. return create<AST::ForLoop>(move(variable_name), move(syntax_error), nullptr); // ForLoop Var Iterated Block
  438. }
  439. in_start_position = AST::Position { in_error_start->offset, m_offset, in_error_start->line, line() };
  440. }
  441. consume_while(is_whitespace);
  442. RefPtr<AST::Node> iterated_expression;
  443. {
  444. auto iter_error_start = push_start();
  445. iterated_expression = parse_expression();
  446. if (!iterated_expression) {
  447. auto syntax_error = create<AST::SyntaxError>("Expected an expression in 'for' loop");
  448. return create<AST::ForLoop>(move(variable_name), move(syntax_error), nullptr, move(in_start_position)); // ForLoop Var Iterated Block
  449. }
  450. }
  451. consume_while(is_any_of(" \t\n"));
  452. {
  453. auto obrace_error_start = push_start();
  454. if (!expect('{')) {
  455. auto syntax_error = create<AST::SyntaxError>("Expected an open brace '{' to start a 'for' loop body");
  456. return create<AST::ForLoop>(move(variable_name), iterated_expression.release_nonnull(), move(syntax_error), move(in_start_position)); // ForLoop Var Iterated Block
  457. }
  458. }
  459. auto body = parse_toplevel();
  460. {
  461. auto cbrace_error_start = push_start();
  462. if (!expect('}')) {
  463. auto error_start = push_start();
  464. auto syntax_error = create<AST::SyntaxError>("Expected a close brace '}' to end a 'for' loop body");
  465. if (body)
  466. body->set_is_syntax_error(*syntax_error);
  467. else
  468. body = syntax_error;
  469. }
  470. }
  471. return create<AST::ForLoop>(move(variable_name), iterated_expression.release_nonnull(), move(body), move(in_start_position)); // ForLoop Var Iterated Block
  472. }
  473. RefPtr<AST::Node> Parser::parse_if_expr()
  474. {
  475. auto rule_start = push_start();
  476. if (!expect("if"))
  477. return nullptr;
  478. if (consume_while(is_any_of(" \t\n")).is_empty()) {
  479. restore_to(*rule_start);
  480. return nullptr;
  481. }
  482. RefPtr<AST::Node> condition;
  483. {
  484. auto cond_error_start = push_start();
  485. condition = parse_or_logical_sequence();
  486. if (!condition)
  487. condition = create<AST::SyntaxError>("Expected a logical sequence after 'if'");
  488. }
  489. auto parse_braced_toplevel = [&]() -> RefPtr<AST::Node> {
  490. RefPtr<AST::Node> body;
  491. {
  492. auto obrace_error_start = push_start();
  493. if (!expect('{')) {
  494. body = create<AST::SyntaxError>("Expected an open brace '{' to start an 'if' true branch");
  495. }
  496. }
  497. if (!body)
  498. body = parse_toplevel();
  499. {
  500. auto cbrace_error_start = push_start();
  501. if (!expect('}')) {
  502. auto error_start = push_start();
  503. RefPtr<AST::SyntaxError> syntax_error = create<AST::SyntaxError>("Expected a close brace '}' to end an 'if' true branch");
  504. if (body)
  505. body->set_is_syntax_error(*syntax_error);
  506. else
  507. body = syntax_error;
  508. }
  509. }
  510. return body;
  511. };
  512. consume_while(is_whitespace);
  513. auto true_branch = parse_braced_toplevel();
  514. consume_while(is_whitespace);
  515. Optional<AST::Position> else_position;
  516. {
  517. auto else_start = push_start();
  518. if (expect("else"))
  519. else_position = AST::Position { else_start->offset, m_offset, else_start->line, line() };
  520. }
  521. if (else_position.has_value()) {
  522. consume_while(is_whitespace);
  523. if (peek() == '{') {
  524. auto false_branch = parse_braced_toplevel();
  525. return create<AST::IfCond>(else_position, condition.release_nonnull(), move(true_branch), move(false_branch)); // If expr true_branch Else false_branch
  526. }
  527. auto else_if_branch = parse_if_expr();
  528. return create<AST::IfCond>(else_position, condition.release_nonnull(), move(true_branch), move(else_if_branch)); // If expr true_branch Else If ...
  529. }
  530. return create<AST::IfCond>(else_position, condition.release_nonnull(), move(true_branch), nullptr); // If expr true_branch
  531. }
  532. RefPtr<AST::Node> Parser::parse_subshell()
  533. {
  534. auto rule_start = push_start();
  535. if (!expect('{'))
  536. return nullptr;
  537. auto body = parse_toplevel();
  538. {
  539. auto cbrace_error_start = push_start();
  540. if (!expect('}')) {
  541. auto error_start = push_start();
  542. RefPtr<AST::SyntaxError> syntax_error = create<AST::SyntaxError>("Expected a close brace '}' to end a subshell");
  543. if (body)
  544. body->set_is_syntax_error(*syntax_error);
  545. else
  546. body = syntax_error;
  547. }
  548. }
  549. return create<AST::Subshell>(move(body));
  550. }
  551. RefPtr<AST::Node> Parser::parse_match_expr()
  552. {
  553. auto rule_start = push_start();
  554. if (!expect("match"))
  555. return nullptr;
  556. if (consume_while(is_whitespace).is_empty()) {
  557. restore_to(*rule_start);
  558. return nullptr;
  559. }
  560. auto match_expression = parse_expression();
  561. if (!match_expression) {
  562. return create<AST::MatchExpr>(
  563. create<AST::SyntaxError>("Expected an expression after 'match'"),
  564. String {}, Optional<AST::Position> {}, Vector<AST::MatchEntry> {});
  565. }
  566. consume_while(is_any_of(" \t\n"));
  567. String match_name;
  568. Optional<AST::Position> as_position;
  569. auto as_start = m_offset;
  570. auto as_line = line();
  571. if (expect("as")) {
  572. as_position = AST::Position { as_start, m_offset, as_line, line() };
  573. if (consume_while(is_any_of(" \t\n")).is_empty()) {
  574. auto node = create<AST::MatchExpr>(
  575. match_expression.release_nonnull(),
  576. String {}, move(as_position), Vector<AST::MatchEntry> {});
  577. node->set_is_syntax_error(create<AST::SyntaxError>("Expected whitespace after 'as' in 'match'"));
  578. return node;
  579. }
  580. match_name = consume_while(is_word_character);
  581. if (match_name.is_empty()) {
  582. auto node = create<AST::MatchExpr>(
  583. match_expression.release_nonnull(),
  584. String {}, move(as_position), Vector<AST::MatchEntry> {});
  585. node->set_is_syntax_error(create<AST::SyntaxError>("Expected an identifier after 'as' in 'match'"));
  586. return node;
  587. }
  588. }
  589. consume_while(is_any_of(" \t\n"));
  590. if (!expect('{')) {
  591. auto node = create<AST::MatchExpr>(
  592. match_expression.release_nonnull(),
  593. move(match_name), move(as_position), Vector<AST::MatchEntry> {});
  594. node->set_is_syntax_error(create<AST::SyntaxError>("Expected an open brace '{' to start a 'match' entry list"));
  595. return node;
  596. }
  597. consume_while(is_any_of(" \t\n"));
  598. Vector<AST::MatchEntry> entries;
  599. for (;;) {
  600. auto entry = parse_match_entry();
  601. consume_while(is_any_of(" \t\n"));
  602. if (entry.options.is_empty())
  603. break;
  604. entries.append(entry);
  605. }
  606. consume_while(is_any_of(" \t\n"));
  607. if (!expect('}')) {
  608. auto node = create<AST::MatchExpr>(
  609. match_expression.release_nonnull(),
  610. move(match_name), move(as_position), move(entries));
  611. node->set_is_syntax_error(create<AST::SyntaxError>("Expected a close brace '}' to end a 'match' entry list"));
  612. return node;
  613. }
  614. return create<AST::MatchExpr>(match_expression.release_nonnull(), move(match_name), move(as_position), move(entries));
  615. }
  616. AST::MatchEntry Parser::parse_match_entry()
  617. {
  618. auto rule_start = push_start();
  619. NonnullRefPtrVector<AST::Node> patterns;
  620. Vector<AST::Position> pipe_positions;
  621. Optional<Vector<String>> match_names;
  622. Optional<AST::Position> match_as_position;
  623. auto pattern = parse_match_pattern();
  624. if (!pattern)
  625. return { {}, {}, {}, {}, create<AST::SyntaxError>("Expected a pattern in 'match' body") };
  626. patterns.append(pattern.release_nonnull());
  627. consume_while(is_any_of(" \t\n"));
  628. auto previous_pipe_start_position = m_offset;
  629. auto previous_pipe_start_line = line();
  630. RefPtr<AST::SyntaxError> error;
  631. while (expect('|')) {
  632. pipe_positions.append({ previous_pipe_start_position, m_offset, previous_pipe_start_line, line() });
  633. consume_while(is_any_of(" \t\n"));
  634. auto pattern = parse_match_pattern();
  635. if (!pattern) {
  636. error = create<AST::SyntaxError>("Expected a pattern to follow '|' in 'match' body");
  637. break;
  638. }
  639. consume_while(is_any_of(" \t\n"));
  640. patterns.append(pattern.release_nonnull());
  641. previous_pipe_start_line = line();
  642. previous_pipe_start_position = m_offset;
  643. }
  644. consume_while(is_any_of(" \t\n"));
  645. auto as_start_position = m_offset;
  646. auto as_start_line = line();
  647. if (expect("as")) {
  648. match_as_position = AST::Position { as_start_position, m_offset, as_start_line, line() };
  649. consume_while(is_any_of(" \t\n"));
  650. if (!expect('(')) {
  651. if (!error)
  652. error = create<AST::SyntaxError>("Expected an explicit list of identifiers after a pattern 'as'");
  653. } else {
  654. match_names = Vector<String>();
  655. for (;;) {
  656. consume_while(is_whitespace);
  657. auto name = consume_while(is_word_character);
  658. if (name.is_empty())
  659. break;
  660. match_names.value().append(move(name));
  661. }
  662. if (!expect(')')) {
  663. if (!error)
  664. error = create<AST::SyntaxError>("Expected a close paren ')' to end the identifier list of pattern 'as'");
  665. }
  666. }
  667. consume_while(is_any_of(" \t\n"));
  668. }
  669. if (!expect('{')) {
  670. if (!error)
  671. error = create<AST::SyntaxError>("Expected an open brace '{' to start a match entry body");
  672. }
  673. auto body = parse_toplevel();
  674. if (!expect('}')) {
  675. if (!error)
  676. error = create<AST::SyntaxError>("Expected a close brace '}' to end a match entry body");
  677. }
  678. if (body && error)
  679. body->set_is_syntax_error(*error);
  680. else if (error)
  681. body = error;
  682. return { move(patterns), move(match_names), move(match_as_position), move(pipe_positions), move(body) };
  683. }
  684. RefPtr<AST::Node> Parser::parse_match_pattern()
  685. {
  686. return parse_expression();
  687. }
  688. RefPtr<AST::Node> Parser::parse_redirection()
  689. {
  690. auto rule_start = push_start();
  691. auto pipe_fd = 0;
  692. auto number = consume_while(is_digit);
  693. if (number.is_empty()) {
  694. pipe_fd = -1;
  695. } else {
  696. auto fd = number.to_int();
  697. pipe_fd = fd.value_or(-1);
  698. }
  699. switch (peek()) {
  700. case '>': {
  701. consume();
  702. if (peek() == '>') {
  703. consume();
  704. consume_while(is_whitespace);
  705. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  706. auto path = parse_expression();
  707. if (!path) {
  708. if (!at_end()) {
  709. // Eat a character and hope the problem goes away
  710. consume();
  711. }
  712. path = create<AST::SyntaxError>("Expected a path after redirection");
  713. }
  714. return create<AST::WriteAppendRedirection>(pipe_fd, path.release_nonnull()); // Redirection WriteAppend
  715. }
  716. if (peek() == '&') {
  717. consume();
  718. // FIXME: 'fd>&-' Syntax not the best. needs discussion.
  719. if (peek() == '-') {
  720. consume();
  721. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  722. return create<AST::CloseFdRedirection>(pipe_fd); // Redirection CloseFd
  723. }
  724. int dest_pipe_fd = 0;
  725. auto number = consume_while(is_digit);
  726. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  727. if (number.is_empty()) {
  728. dest_pipe_fd = -1;
  729. } else {
  730. auto fd = number.to_int();
  731. ASSERT(fd.has_value());
  732. dest_pipe_fd = fd.value();
  733. }
  734. auto redir = create<AST::Fd2FdRedirection>(pipe_fd, dest_pipe_fd); // Redirection Fd2Fd
  735. if (dest_pipe_fd == -1)
  736. redir->set_is_syntax_error(*create<AST::SyntaxError>("Expected a file descriptor"));
  737. return redir;
  738. }
  739. consume_while(is_whitespace);
  740. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  741. auto path = parse_expression();
  742. if (!path) {
  743. if (!at_end()) {
  744. // Eat a character and hope the problem goes away
  745. consume();
  746. }
  747. path = create<AST::SyntaxError>("Expected a path after redirection");
  748. }
  749. return create<AST::WriteRedirection>(pipe_fd, path.release_nonnull()); // Redirection Write
  750. }
  751. case '<': {
  752. consume();
  753. enum {
  754. Read,
  755. ReadWrite,
  756. } mode { Read };
  757. if (peek() == '>') {
  758. mode = ReadWrite;
  759. consume();
  760. }
  761. consume_while(is_whitespace);
  762. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDIN_FILENO;
  763. auto path = parse_expression();
  764. if (!path) {
  765. if (!at_end()) {
  766. // Eat a character and hope the problem goes away
  767. consume();
  768. }
  769. path = create<AST::SyntaxError>("Expected a path after redirection");
  770. }
  771. if (mode == Read)
  772. return create<AST::ReadRedirection>(pipe_fd, path.release_nonnull()); // Redirection Read
  773. return create<AST::ReadWriteRedirection>(pipe_fd, path.release_nonnull()); // Redirection ReadWrite
  774. }
  775. default:
  776. restore_to(*rule_start);
  777. return nullptr;
  778. }
  779. }
  780. RefPtr<AST::Node> Parser::parse_list_expression()
  781. {
  782. consume_while(is_whitespace);
  783. auto rule_start = push_start();
  784. Vector<NonnullRefPtr<AST::Node>> nodes;
  785. do {
  786. auto expr = parse_expression();
  787. if (!expr)
  788. break;
  789. nodes.append(expr.release_nonnull());
  790. } while (!consume_while(is_whitespace).is_empty());
  791. if (nodes.is_empty())
  792. return nullptr;
  793. return create<AST::ListConcatenate>(move(nodes)); // Concatenate List
  794. }
  795. RefPtr<AST::Node> Parser::parse_expression()
  796. {
  797. auto rule_start = push_start();
  798. auto starting_char = peek();
  799. auto read_concat = [&](auto&& expr) -> NonnullRefPtr<AST::Node> {
  800. if (is_whitespace(peek()))
  801. return move(expr);
  802. if (auto next_expr = parse_expression())
  803. return create<AST::Juxtaposition>(move(expr), next_expr.release_nonnull());
  804. return move(expr);
  805. };
  806. if (strchr("&|)} ;<>\n", starting_char) != nullptr)
  807. return nullptr;
  808. if (m_is_in_brace_expansion_spec && starting_char == ',')
  809. return nullptr;
  810. if (m_is_in_brace_expansion_spec && next_is(".."))
  811. return nullptr;
  812. if (isdigit(starting_char)) {
  813. ScopedValueRollback offset_rollback { m_offset };
  814. auto redir = parse_redirection();
  815. if (redir)
  816. return nullptr;
  817. }
  818. if (starting_char == '$') {
  819. if (auto variable = parse_variable())
  820. return read_concat(variable.release_nonnull());
  821. if (auto inline_exec = parse_evaluate())
  822. return read_concat(inline_exec.release_nonnull());
  823. }
  824. if (starting_char == '#')
  825. return parse_comment();
  826. if (starting_char == '(') {
  827. consume();
  828. auto list = parse_list_expression();
  829. if (!expect(')')) {
  830. restore_to(*rule_start);
  831. return nullptr;
  832. }
  833. return read_concat(create<AST::CastToList>(move(list))); // Cast To List
  834. }
  835. if (auto composite = parse_string_composite())
  836. return read_concat(composite.release_nonnull());
  837. return nullptr;
  838. }
  839. RefPtr<AST::Node> Parser::parse_string_composite()
  840. {
  841. auto rule_start = push_start();
  842. if (auto string = parse_string()) {
  843. if (auto next_part = parse_string_composite())
  844. return create<AST::Juxtaposition>(string.release_nonnull(), next_part.release_nonnull()); // Concatenate String StringComposite
  845. return string;
  846. }
  847. if (auto variable = parse_variable()) {
  848. if (auto next_part = parse_string_composite())
  849. return create<AST::Juxtaposition>(variable.release_nonnull(), next_part.release_nonnull()); // Concatenate Variable StringComposite
  850. return variable;
  851. }
  852. if (auto glob = parse_glob()) {
  853. if (auto next_part = parse_string_composite())
  854. return create<AST::Juxtaposition>(glob.release_nonnull(), next_part.release_nonnull()); // Concatenate Glob StringComposite
  855. return glob;
  856. }
  857. if (auto expansion = parse_brace_expansion()) {
  858. if (auto next_part = parse_string_composite())
  859. return create<AST::Juxtaposition>(expansion.release_nonnull(), next_part.release_nonnull()); // Concatenate BraceExpansion StringComposite
  860. return expansion;
  861. }
  862. if (auto bareword = parse_bareword()) {
  863. if (auto next_part = parse_string_composite())
  864. return create<AST::Juxtaposition>(bareword.release_nonnull(), next_part.release_nonnull()); // Concatenate Bareword StringComposite
  865. return bareword;
  866. }
  867. if (auto inline_command = parse_evaluate()) {
  868. if (auto next_part = parse_string_composite())
  869. return create<AST::Juxtaposition>(inline_command.release_nonnull(), next_part.release_nonnull()); // Concatenate Execute StringComposite
  870. return inline_command;
  871. }
  872. return nullptr;
  873. }
  874. RefPtr<AST::Node> Parser::parse_string()
  875. {
  876. auto rule_start = push_start();
  877. if (at_end())
  878. return nullptr;
  879. if (peek() == '"') {
  880. consume();
  881. auto inner = parse_doublequoted_string_inner();
  882. if (!inner)
  883. inner = create<AST::SyntaxError>("Unexpected EOF in string");
  884. if (!expect('"')) {
  885. inner = create<AST::DoubleQuotedString>(move(inner));
  886. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating double quote"));
  887. return inner;
  888. }
  889. return create<AST::DoubleQuotedString>(move(inner)); // Double Quoted String
  890. }
  891. if (peek() == '\'') {
  892. consume();
  893. auto text = consume_while(is_not('\''));
  894. bool is_error = false;
  895. if (!expect('\''))
  896. is_error = true;
  897. auto result = create<AST::StringLiteral>(move(text)); // String Literal
  898. if (is_error)
  899. result->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating single quote"));
  900. return move(result);
  901. }
  902. return nullptr;
  903. }
  904. RefPtr<AST::Node> Parser::parse_doublequoted_string_inner()
  905. {
  906. auto rule_start = push_start();
  907. if (at_end())
  908. return nullptr;
  909. StringBuilder builder;
  910. while (!at_end() && peek() != '"') {
  911. if (peek() == '\\') {
  912. consume();
  913. if (at_end()) {
  914. break;
  915. }
  916. auto ch = consume();
  917. switch (ch) {
  918. case '\\':
  919. default:
  920. builder.append(ch);
  921. break;
  922. case 'x': {
  923. if (m_input.length() <= m_offset + 2)
  924. break;
  925. auto first_nibble = tolower(consume());
  926. auto second_nibble = tolower(consume());
  927. if (!isxdigit(first_nibble) || !isxdigit(second_nibble)) {
  928. builder.append(first_nibble);
  929. builder.append(second_nibble);
  930. break;
  931. }
  932. builder.append(to_byte(first_nibble, second_nibble));
  933. break;
  934. }
  935. case 'a':
  936. builder.append('\a');
  937. break;
  938. case 'b':
  939. builder.append('\b');
  940. break;
  941. case 'e':
  942. builder.append('\x1b');
  943. break;
  944. case 'f':
  945. builder.append('\f');
  946. break;
  947. case 'r':
  948. builder.append('\r');
  949. break;
  950. case 'n':
  951. builder.append('\n');
  952. break;
  953. }
  954. continue;
  955. }
  956. if (peek() == '$') {
  957. auto string_literal = create<AST::StringLiteral>(builder.to_string()); // String Literal
  958. if (auto variable = parse_variable()) {
  959. auto inner = create<AST::StringPartCompose>(
  960. move(string_literal),
  961. variable.release_nonnull()); // Compose String Variable
  962. if (auto string = parse_doublequoted_string_inner()) {
  963. return create<AST::StringPartCompose>(move(inner), string.release_nonnull()); // Compose Composition Composition
  964. }
  965. return inner;
  966. }
  967. if (auto evaluate = parse_evaluate()) {
  968. auto composition = create<AST::StringPartCompose>(
  969. move(string_literal),
  970. evaluate.release_nonnull()); // Compose String Sequence
  971. if (auto string = parse_doublequoted_string_inner()) {
  972. return create<AST::StringPartCompose>(move(composition), string.release_nonnull()); // Compose Composition Composition
  973. }
  974. return composition;
  975. }
  976. }
  977. builder.append(consume());
  978. }
  979. return create<AST::StringLiteral>(builder.to_string()); // String Literal
  980. }
  981. RefPtr<AST::Node> Parser::parse_variable()
  982. {
  983. auto rule_start = push_start();
  984. if (at_end())
  985. return nullptr;
  986. if (peek() != '$')
  987. return nullptr;
  988. consume();
  989. switch (peek()) {
  990. case '$':
  991. case '?':
  992. case '*':
  993. case '#':
  994. return create<AST::SpecialVariable>(consume()); // Variable Special
  995. default:
  996. break;
  997. }
  998. auto name = consume_while(is_word_character);
  999. if (name.length() == 0) {
  1000. restore_to(rule_start->offset, rule_start->line);
  1001. return nullptr;
  1002. }
  1003. return create<AST::SimpleVariable>(move(name)); // Variable Simple
  1004. }
  1005. RefPtr<AST::Node> Parser::parse_evaluate()
  1006. {
  1007. auto rule_start = push_start();
  1008. if (at_end())
  1009. return nullptr;
  1010. if (peek() != '$')
  1011. return nullptr;
  1012. consume();
  1013. if (peek() == '(') {
  1014. consume();
  1015. auto inner = parse_pipe_sequence();
  1016. if (!inner)
  1017. inner = create<AST::SyntaxError>("Unexpected EOF in list");
  1018. if (!expect(')'))
  1019. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating close paren"));
  1020. return create<AST::Execute>(inner.release_nonnull(), true);
  1021. }
  1022. auto inner = parse_expression();
  1023. if (!inner) {
  1024. inner = create<AST::SyntaxError>("Expected a command");
  1025. } else {
  1026. if (inner->is_list()) {
  1027. auto execute_inner = create<AST::Execute>(inner.release_nonnull(), true);
  1028. inner = move(execute_inner);
  1029. } else {
  1030. auto dyn_inner = create<AST::DynamicEvaluate>(inner.release_nonnull());
  1031. inner = move(dyn_inner);
  1032. }
  1033. }
  1034. return inner;
  1035. }
  1036. RefPtr<AST::Node> Parser::parse_comment()
  1037. {
  1038. if (at_end())
  1039. return nullptr;
  1040. if (peek() != '#')
  1041. return nullptr;
  1042. consume();
  1043. auto text = consume_while(is_not('\n'));
  1044. return create<AST::Comment>(move(text)); // Comment
  1045. }
  1046. RefPtr<AST::Node> Parser::parse_bareword()
  1047. {
  1048. auto rule_start = push_start();
  1049. StringBuilder builder;
  1050. auto is_acceptable_bareword_character = [&](char c) {
  1051. return strchr("\\\"'*$&#|(){} ?;<>\n", c) == nullptr
  1052. && ((m_is_in_brace_expansion_spec && c != ',') || !m_is_in_brace_expansion_spec);
  1053. };
  1054. while (!at_end()) {
  1055. char ch = peek();
  1056. if (ch == '\\') {
  1057. consume();
  1058. if (!at_end()) {
  1059. ch = consume();
  1060. if (is_acceptable_bareword_character(ch))
  1061. builder.append('\\');
  1062. }
  1063. builder.append(ch);
  1064. continue;
  1065. }
  1066. if (m_is_in_brace_expansion_spec && next_is("..")) {
  1067. // Don't eat '..' in a brace expansion spec.
  1068. break;
  1069. }
  1070. if (is_acceptable_bareword_character(ch)) {
  1071. builder.append(consume());
  1072. continue;
  1073. }
  1074. break;
  1075. }
  1076. if (builder.is_empty())
  1077. return nullptr;
  1078. auto current_end = m_offset;
  1079. auto current_line = line();
  1080. auto string = builder.to_string();
  1081. if (string.starts_with('~')) {
  1082. String username;
  1083. RefPtr<AST::Node> tilde, text;
  1084. auto first_slash_index = string.index_of("/");
  1085. if (first_slash_index.has_value()) {
  1086. username = string.substring_view(1, first_slash_index.value() - 1);
  1087. string = string.substring_view(first_slash_index.value(), string.length() - first_slash_index.value());
  1088. } else {
  1089. username = string.substring_view(1, string.length() - 1);
  1090. string = "";
  1091. }
  1092. // Synthesize a Tilde Node with the correct positioning information.
  1093. {
  1094. restore_to(rule_start->offset, rule_start->line);
  1095. auto ch = consume();
  1096. ASSERT(ch == '~');
  1097. tilde = create<AST::Tilde>(move(username));
  1098. }
  1099. if (string.is_empty())
  1100. return tilde;
  1101. // Synthesize a BarewordLiteral Node with the correct positioning information.
  1102. {
  1103. auto text_start = push_start();
  1104. restore_to(current_end, current_line);
  1105. text = create<AST::BarewordLiteral>(move(string));
  1106. }
  1107. return create<AST::Juxtaposition>(tilde.release_nonnull(), text.release_nonnull()); // Juxtaposition Variable Bareword
  1108. }
  1109. if (string.starts_with("\\~")) {
  1110. // Un-escape the tilde, but only at the start (where it would be an expansion)
  1111. string = string.substring(1, string.length() - 1);
  1112. }
  1113. return create<AST::BarewordLiteral>(move(string)); // Bareword Literal
  1114. }
  1115. RefPtr<AST::Node> Parser::parse_glob()
  1116. {
  1117. auto rule_start = push_start();
  1118. auto bareword_part = parse_bareword();
  1119. if (at_end())
  1120. return bareword_part;
  1121. char ch = peek();
  1122. if (ch == '*' || ch == '?') {
  1123. auto saved_offset = save_offset();
  1124. consume();
  1125. StringBuilder textbuilder;
  1126. if (bareword_part) {
  1127. StringView text;
  1128. if (bareword_part->is_bareword()) {
  1129. auto bareword = static_cast<AST::BarewordLiteral*>(bareword_part.ptr());
  1130. text = bareword->text();
  1131. } else {
  1132. // FIXME: Allow composition of tilde+bareword with globs: '~/foo/bar/baz*'
  1133. restore_to(saved_offset.offset, saved_offset.line);
  1134. bareword_part->set_is_syntax_error(*create<AST::SyntaxError>(String::format("Unexpected %s inside a glob", bareword_part->class_name().characters())));
  1135. return bareword_part;
  1136. }
  1137. textbuilder.append(text);
  1138. }
  1139. textbuilder.append(ch);
  1140. auto glob_after = parse_glob();
  1141. if (glob_after) {
  1142. if (glob_after->is_glob()) {
  1143. auto glob = static_cast<AST::BarewordLiteral*>(glob_after.ptr());
  1144. textbuilder.append(glob->text());
  1145. } else if (glob_after->is_bareword()) {
  1146. auto bareword = static_cast<AST::BarewordLiteral*>(glob_after.ptr());
  1147. textbuilder.append(bareword->text());
  1148. } else if (glob_after->is_tilde()) {
  1149. auto bareword = static_cast<AST::Tilde*>(glob_after.ptr());
  1150. textbuilder.append("~");
  1151. textbuilder.append(bareword->text());
  1152. } else {
  1153. return create<AST::SyntaxError>(String::formatted("Invalid node '{}' in glob position, escape shell special characters", glob_after->class_name()));
  1154. }
  1155. }
  1156. return create<AST::Glob>(textbuilder.to_string()); // Glob
  1157. }
  1158. return bareword_part;
  1159. }
  1160. RefPtr<AST::Node> Parser::parse_brace_expansion()
  1161. {
  1162. auto rule_start = push_start();
  1163. if (!expect('{'))
  1164. return nullptr;
  1165. if (auto spec = parse_brace_expansion_spec()) {
  1166. if (!expect('}'))
  1167. spec->set_is_syntax_error(create<AST::SyntaxError>("Expected a close brace '}' to end a brace expansion"));
  1168. return spec;
  1169. }
  1170. restore_to(*rule_start);
  1171. return nullptr;
  1172. }
  1173. RefPtr<AST::Node> Parser::parse_brace_expansion_spec()
  1174. {
  1175. TemporaryChange is_in_brace_expansion { m_is_in_brace_expansion_spec, true };
  1176. auto rule_start = push_start();
  1177. auto start_expr = parse_expression();
  1178. if (start_expr) {
  1179. if (expect("..")) {
  1180. if (auto end_expr = parse_expression()) {
  1181. if (end_expr->position().start_offset != start_expr->position().end_offset + 2)
  1182. end_expr->set_is_syntax_error(create<AST::SyntaxError>("Expected no whitespace between '..' and the following expression in brace expansion"));
  1183. return create<AST::Range>(start_expr.release_nonnull(), end_expr.release_nonnull());
  1184. }
  1185. return create<AST::Range>(start_expr.release_nonnull(), create<AST::SyntaxError>("Expected an expression to end range brace expansion with"));
  1186. }
  1187. }
  1188. NonnullRefPtrVector<AST::Node> subexpressions;
  1189. if (start_expr)
  1190. subexpressions.append(start_expr.release_nonnull());
  1191. while (expect(',')) {
  1192. auto expr = parse_expression();
  1193. if (expr) {
  1194. subexpressions.append(expr.release_nonnull());
  1195. } else {
  1196. subexpressions.append(create<AST::StringLiteral>(""));
  1197. }
  1198. }
  1199. if (subexpressions.is_empty())
  1200. return nullptr;
  1201. return create<AST::BraceExpansion>(move(subexpressions));
  1202. }
  1203. StringView Parser::consume_while(Function<bool(char)> condition)
  1204. {
  1205. if (at_end())
  1206. return {};
  1207. auto start_offset = m_offset;
  1208. while (!at_end() && condition(peek()))
  1209. consume();
  1210. return m_input.substring_view(start_offset, m_offset - start_offset);
  1211. }
  1212. bool Parser::next_is(const StringView& next)
  1213. {
  1214. auto start = push_start();
  1215. auto res = expect(next);
  1216. restore_to(*start);
  1217. return res;
  1218. }
  1219. }