Parser.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  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 if (!toplevel->is_syntax_error())
  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", true));
  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", true);
  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", true);
  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 '||'", true);
  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 '&&'", true);
  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", true);
  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", true);
  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", true);
  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", true);
  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'", true);
  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", true);
  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", true);
  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", true);
  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'", true),
  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'", true));
  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'", true));
  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", true));
  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", true));
  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", true) };
  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", true);
  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'", true);
  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", true);
  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", true);
  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", true);
  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. dest_pipe_fd = fd.value_or(-1);
  732. }
  733. auto redir = create<AST::Fd2FdRedirection>(pipe_fd, dest_pipe_fd); // Redirection Fd2Fd
  734. if (dest_pipe_fd == -1)
  735. redir->set_is_syntax_error(*create<AST::SyntaxError>("Expected a file descriptor"));
  736. return redir;
  737. }
  738. consume_while(is_whitespace);
  739. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  740. auto path = parse_expression();
  741. if (!path) {
  742. if (!at_end()) {
  743. // Eat a character and hope the problem goes away
  744. consume();
  745. }
  746. path = create<AST::SyntaxError>("Expected a path after redirection", true);
  747. }
  748. return create<AST::WriteRedirection>(pipe_fd, path.release_nonnull()); // Redirection Write
  749. }
  750. case '<': {
  751. consume();
  752. enum {
  753. Read,
  754. ReadWrite,
  755. } mode { Read };
  756. if (peek() == '>') {
  757. mode = ReadWrite;
  758. consume();
  759. }
  760. consume_while(is_whitespace);
  761. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDIN_FILENO;
  762. auto path = parse_expression();
  763. if (!path) {
  764. if (!at_end()) {
  765. // Eat a character and hope the problem goes away
  766. consume();
  767. }
  768. path = create<AST::SyntaxError>("Expected a path after redirection", true);
  769. }
  770. if (mode == Read)
  771. return create<AST::ReadRedirection>(pipe_fd, path.release_nonnull()); // Redirection Read
  772. return create<AST::ReadWriteRedirection>(pipe_fd, path.release_nonnull()); // Redirection ReadWrite
  773. }
  774. default:
  775. restore_to(*rule_start);
  776. return nullptr;
  777. }
  778. }
  779. RefPtr<AST::Node> Parser::parse_list_expression()
  780. {
  781. consume_while(is_whitespace);
  782. auto rule_start = push_start();
  783. Vector<NonnullRefPtr<AST::Node>> nodes;
  784. do {
  785. auto expr = parse_expression();
  786. if (!expr)
  787. break;
  788. nodes.append(expr.release_nonnull());
  789. } while (!consume_while(is_whitespace).is_empty());
  790. if (nodes.is_empty())
  791. return nullptr;
  792. return create<AST::ListConcatenate>(move(nodes)); // Concatenate List
  793. }
  794. RefPtr<AST::Node> Parser::parse_expression()
  795. {
  796. auto rule_start = push_start();
  797. if (m_rule_start_offsets.size() > max_allowed_nested_rule_depth)
  798. return create<AST::SyntaxError>(String::formatted("Expression nested too deep (max allowed is {})", max_allowed_nested_rule_depth));
  799. auto starting_char = peek();
  800. auto read_concat = [&](auto&& expr) -> NonnullRefPtr<AST::Node> {
  801. if (is_whitespace(peek()))
  802. return move(expr);
  803. if (auto next_expr = parse_expression())
  804. return create<AST::Juxtaposition>(move(expr), next_expr.release_nonnull());
  805. return move(expr);
  806. };
  807. if (strchr("&|)} ;<>\n", starting_char) != nullptr)
  808. return nullptr;
  809. if (m_is_in_brace_expansion_spec && starting_char == ',')
  810. return nullptr;
  811. if (m_is_in_brace_expansion_spec && next_is(".."))
  812. return nullptr;
  813. if (isdigit(starting_char)) {
  814. ScopedValueRollback offset_rollback { m_offset };
  815. auto redir = parse_redirection();
  816. if (redir)
  817. return nullptr;
  818. }
  819. if (starting_char == '$') {
  820. if (auto variable = parse_variable())
  821. return read_concat(variable.release_nonnull());
  822. if (auto inline_exec = parse_evaluate())
  823. return read_concat(inline_exec.release_nonnull());
  824. }
  825. if (starting_char == '#')
  826. return parse_comment();
  827. if (starting_char == '(') {
  828. consume();
  829. auto list = parse_list_expression();
  830. if (!expect(')')) {
  831. restore_to(*rule_start);
  832. return nullptr;
  833. }
  834. return read_concat(create<AST::CastToList>(move(list))); // Cast To List
  835. }
  836. if (auto composite = parse_string_composite())
  837. return read_concat(composite.release_nonnull());
  838. return nullptr;
  839. }
  840. RefPtr<AST::Node> Parser::parse_string_composite()
  841. {
  842. auto rule_start = push_start();
  843. if (auto string = parse_string()) {
  844. if (auto next_part = parse_string_composite())
  845. return create<AST::Juxtaposition>(string.release_nonnull(), next_part.release_nonnull()); // Concatenate String StringComposite
  846. return string;
  847. }
  848. if (auto variable = parse_variable()) {
  849. if (auto next_part = parse_string_composite())
  850. return create<AST::Juxtaposition>(variable.release_nonnull(), next_part.release_nonnull()); // Concatenate Variable StringComposite
  851. return variable;
  852. }
  853. if (auto glob = parse_glob()) {
  854. if (auto next_part = parse_string_composite())
  855. return create<AST::Juxtaposition>(glob.release_nonnull(), next_part.release_nonnull()); // Concatenate Glob StringComposite
  856. return glob;
  857. }
  858. if (auto expansion = parse_brace_expansion()) {
  859. if (auto next_part = parse_string_composite())
  860. return create<AST::Juxtaposition>(expansion.release_nonnull(), next_part.release_nonnull()); // Concatenate BraceExpansion StringComposite
  861. return expansion;
  862. }
  863. if (auto bareword = parse_bareword()) {
  864. if (auto next_part = parse_string_composite())
  865. return create<AST::Juxtaposition>(bareword.release_nonnull(), next_part.release_nonnull()); // Concatenate Bareword StringComposite
  866. return bareword;
  867. }
  868. if (auto inline_command = parse_evaluate()) {
  869. if (auto next_part = parse_string_composite())
  870. return create<AST::Juxtaposition>(inline_command.release_nonnull(), next_part.release_nonnull()); // Concatenate Execute StringComposite
  871. return inline_command;
  872. }
  873. return nullptr;
  874. }
  875. RefPtr<AST::Node> Parser::parse_string()
  876. {
  877. auto rule_start = push_start();
  878. if (at_end())
  879. return nullptr;
  880. if (peek() == '"') {
  881. consume();
  882. auto inner = parse_doublequoted_string_inner();
  883. if (!inner)
  884. inner = create<AST::SyntaxError>("Unexpected EOF in string", true);
  885. if (!expect('"')) {
  886. inner = create<AST::DoubleQuotedString>(move(inner));
  887. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating double quote", true));
  888. return inner;
  889. }
  890. return create<AST::DoubleQuotedString>(move(inner)); // Double Quoted String
  891. }
  892. if (peek() == '\'') {
  893. consume();
  894. auto text = consume_while(is_not('\''));
  895. bool is_error = false;
  896. if (!expect('\''))
  897. is_error = true;
  898. auto result = create<AST::StringLiteral>(move(text)); // String Literal
  899. if (is_error)
  900. result->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating single quote", true));
  901. return move(result);
  902. }
  903. return nullptr;
  904. }
  905. RefPtr<AST::Node> Parser::parse_doublequoted_string_inner()
  906. {
  907. auto rule_start = push_start();
  908. if (at_end())
  909. return nullptr;
  910. StringBuilder builder;
  911. while (!at_end() && peek() != '"') {
  912. if (peek() == '\\') {
  913. consume();
  914. if (at_end()) {
  915. break;
  916. }
  917. auto ch = consume();
  918. switch (ch) {
  919. case '\\':
  920. default:
  921. builder.append(ch);
  922. break;
  923. case 'x': {
  924. if (m_input.length() <= m_offset + 2)
  925. break;
  926. auto first_nibble = tolower(consume());
  927. auto second_nibble = tolower(consume());
  928. if (!isxdigit(first_nibble) || !isxdigit(second_nibble)) {
  929. builder.append(first_nibble);
  930. builder.append(second_nibble);
  931. break;
  932. }
  933. builder.append(to_byte(first_nibble, second_nibble));
  934. break;
  935. }
  936. case 'a':
  937. builder.append('\a');
  938. break;
  939. case 'b':
  940. builder.append('\b');
  941. break;
  942. case 'e':
  943. builder.append('\x1b');
  944. break;
  945. case 'f':
  946. builder.append('\f');
  947. break;
  948. case 'r':
  949. builder.append('\r');
  950. break;
  951. case 'n':
  952. builder.append('\n');
  953. break;
  954. }
  955. continue;
  956. }
  957. if (peek() == '$') {
  958. auto string_literal = create<AST::StringLiteral>(builder.to_string()); // String Literal
  959. if (auto variable = parse_variable()) {
  960. auto inner = create<AST::StringPartCompose>(
  961. move(string_literal),
  962. variable.release_nonnull()); // Compose String Variable
  963. if (auto string = parse_doublequoted_string_inner()) {
  964. return create<AST::StringPartCompose>(move(inner), string.release_nonnull()); // Compose Composition Composition
  965. }
  966. return inner;
  967. }
  968. if (auto evaluate = parse_evaluate()) {
  969. auto composition = create<AST::StringPartCompose>(
  970. move(string_literal),
  971. evaluate.release_nonnull()); // Compose String Sequence
  972. if (auto string = parse_doublequoted_string_inner()) {
  973. return create<AST::StringPartCompose>(move(composition), string.release_nonnull()); // Compose Composition Composition
  974. }
  975. return composition;
  976. }
  977. }
  978. builder.append(consume());
  979. }
  980. return create<AST::StringLiteral>(builder.to_string()); // String Literal
  981. }
  982. RefPtr<AST::Node> Parser::parse_variable()
  983. {
  984. auto rule_start = push_start();
  985. if (at_end())
  986. return nullptr;
  987. if (peek() != '$')
  988. return nullptr;
  989. consume();
  990. switch (peek()) {
  991. case '$':
  992. case '?':
  993. case '*':
  994. case '#':
  995. return create<AST::SpecialVariable>(consume()); // Variable Special
  996. default:
  997. break;
  998. }
  999. auto name = consume_while(is_word_character);
  1000. if (name.length() == 0) {
  1001. restore_to(rule_start->offset, rule_start->line);
  1002. return nullptr;
  1003. }
  1004. return create<AST::SimpleVariable>(move(name)); // Variable Simple
  1005. }
  1006. RefPtr<AST::Node> Parser::parse_evaluate()
  1007. {
  1008. auto rule_start = push_start();
  1009. if (at_end())
  1010. return nullptr;
  1011. if (peek() != '$')
  1012. return nullptr;
  1013. consume();
  1014. if (peek() == '(') {
  1015. consume();
  1016. auto inner = parse_pipe_sequence();
  1017. if (!inner)
  1018. inner = create<AST::SyntaxError>("Unexpected EOF in list", true);
  1019. if (!expect(')'))
  1020. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating close paren", true));
  1021. return create<AST::Execute>(inner.release_nonnull(), true);
  1022. }
  1023. auto inner = parse_expression();
  1024. if (!inner) {
  1025. inner = create<AST::SyntaxError>("Expected a command", true);
  1026. } else {
  1027. if (inner->is_list()) {
  1028. auto execute_inner = create<AST::Execute>(inner.release_nonnull(), true);
  1029. inner = move(execute_inner);
  1030. } else {
  1031. auto dyn_inner = create<AST::DynamicEvaluate>(inner.release_nonnull());
  1032. inner = move(dyn_inner);
  1033. }
  1034. }
  1035. return inner;
  1036. }
  1037. RefPtr<AST::Node> Parser::parse_comment()
  1038. {
  1039. if (at_end())
  1040. return nullptr;
  1041. if (peek() != '#')
  1042. return nullptr;
  1043. consume();
  1044. auto text = consume_while(is_not('\n'));
  1045. return create<AST::Comment>(move(text)); // Comment
  1046. }
  1047. RefPtr<AST::Node> Parser::parse_bareword()
  1048. {
  1049. auto rule_start = push_start();
  1050. StringBuilder builder;
  1051. auto is_acceptable_bareword_character = [&](char c) {
  1052. return strchr("\\\"'*$&#|(){} ?;<>\n", c) == nullptr
  1053. && ((m_is_in_brace_expansion_spec && c != ',') || !m_is_in_brace_expansion_spec);
  1054. };
  1055. while (!at_end()) {
  1056. char ch = peek();
  1057. if (ch == '\\') {
  1058. consume();
  1059. if (!at_end()) {
  1060. ch = consume();
  1061. if (is_acceptable_bareword_character(ch))
  1062. builder.append('\\');
  1063. }
  1064. builder.append(ch);
  1065. continue;
  1066. }
  1067. if (m_is_in_brace_expansion_spec && next_is("..")) {
  1068. // Don't eat '..' in a brace expansion spec.
  1069. break;
  1070. }
  1071. if (is_acceptable_bareword_character(ch)) {
  1072. builder.append(consume());
  1073. continue;
  1074. }
  1075. break;
  1076. }
  1077. if (builder.is_empty())
  1078. return nullptr;
  1079. auto current_end = m_offset;
  1080. auto current_line = line();
  1081. auto string = builder.to_string();
  1082. if (string.starts_with('~')) {
  1083. String username;
  1084. RefPtr<AST::Node> tilde, text;
  1085. auto first_slash_index = string.index_of("/");
  1086. if (first_slash_index.has_value()) {
  1087. username = string.substring_view(1, first_slash_index.value() - 1);
  1088. string = string.substring_view(first_slash_index.value(), string.length() - first_slash_index.value());
  1089. } else {
  1090. username = string.substring_view(1, string.length() - 1);
  1091. string = "";
  1092. }
  1093. // Synthesize a Tilde Node with the correct positioning information.
  1094. {
  1095. restore_to(rule_start->offset, rule_start->line);
  1096. auto ch = consume();
  1097. ASSERT(ch == '~');
  1098. tilde = create<AST::Tilde>(move(username));
  1099. }
  1100. if (string.is_empty())
  1101. return tilde;
  1102. // Synthesize a BarewordLiteral Node with the correct positioning information.
  1103. {
  1104. auto text_start = push_start();
  1105. restore_to(current_end, current_line);
  1106. text = create<AST::BarewordLiteral>(move(string));
  1107. }
  1108. return create<AST::Juxtaposition>(tilde.release_nonnull(), text.release_nonnull()); // Juxtaposition Variable Bareword
  1109. }
  1110. if (string.starts_with("\\~")) {
  1111. // Un-escape the tilde, but only at the start (where it would be an expansion)
  1112. string = string.substring(1, string.length() - 1);
  1113. }
  1114. return create<AST::BarewordLiteral>(move(string)); // Bareword Literal
  1115. }
  1116. RefPtr<AST::Node> Parser::parse_glob()
  1117. {
  1118. auto rule_start = push_start();
  1119. auto bareword_part = parse_bareword();
  1120. if (at_end())
  1121. return bareword_part;
  1122. char ch = peek();
  1123. if (ch == '*' || ch == '?') {
  1124. auto saved_offset = save_offset();
  1125. consume();
  1126. StringBuilder textbuilder;
  1127. if (bareword_part) {
  1128. StringView text;
  1129. if (bareword_part->is_bareword()) {
  1130. auto bareword = static_cast<AST::BarewordLiteral*>(bareword_part.ptr());
  1131. text = bareword->text();
  1132. } else {
  1133. // FIXME: Allow composition of tilde+bareword with globs: '~/foo/bar/baz*'
  1134. restore_to(saved_offset.offset, saved_offset.line);
  1135. bareword_part->set_is_syntax_error(*create<AST::SyntaxError>(String::format("Unexpected %s inside a glob", bareword_part->class_name().characters())));
  1136. return bareword_part;
  1137. }
  1138. textbuilder.append(text);
  1139. }
  1140. textbuilder.append(ch);
  1141. auto glob_after = parse_glob();
  1142. if (glob_after) {
  1143. if (glob_after->is_glob()) {
  1144. auto glob = static_cast<AST::Glob*>(glob_after.ptr());
  1145. textbuilder.append(glob->text());
  1146. } else if (glob_after->is_bareword()) {
  1147. auto bareword = static_cast<AST::BarewordLiteral*>(glob_after.ptr());
  1148. textbuilder.append(bareword->text());
  1149. } else if (glob_after->is_tilde()) {
  1150. auto bareword = static_cast<AST::Tilde*>(glob_after.ptr());
  1151. textbuilder.append("~");
  1152. textbuilder.append(bareword->text());
  1153. } else {
  1154. return create<AST::SyntaxError>(String::formatted("Invalid node '{}' in glob position, escape shell special characters", glob_after->class_name()));
  1155. }
  1156. }
  1157. return create<AST::Glob>(textbuilder.to_string()); // Glob
  1158. }
  1159. return bareword_part;
  1160. }
  1161. RefPtr<AST::Node> Parser::parse_brace_expansion()
  1162. {
  1163. auto rule_start = push_start();
  1164. if (!expect('{'))
  1165. return nullptr;
  1166. if (auto spec = parse_brace_expansion_spec()) {
  1167. if (!expect('}'))
  1168. spec->set_is_syntax_error(create<AST::SyntaxError>("Expected a close brace '}' to end a brace expansion", true));
  1169. return spec;
  1170. }
  1171. restore_to(*rule_start);
  1172. return nullptr;
  1173. }
  1174. RefPtr<AST::Node> Parser::parse_brace_expansion_spec()
  1175. {
  1176. TemporaryChange is_in_brace_expansion { m_is_in_brace_expansion_spec, true };
  1177. auto rule_start = push_start();
  1178. auto start_expr = parse_expression();
  1179. if (start_expr) {
  1180. if (expect("..")) {
  1181. if (auto end_expr = parse_expression()) {
  1182. if (end_expr->position().start_offset != start_expr->position().end_offset + 2)
  1183. end_expr->set_is_syntax_error(create<AST::SyntaxError>("Expected no whitespace between '..' and the following expression in brace expansion"));
  1184. return create<AST::Range>(start_expr.release_nonnull(), end_expr.release_nonnull());
  1185. }
  1186. return create<AST::Range>(start_expr.release_nonnull(), create<AST::SyntaxError>("Expected an expression to end range brace expansion with", true));
  1187. }
  1188. }
  1189. NonnullRefPtrVector<AST::Node> subexpressions;
  1190. if (start_expr)
  1191. subexpressions.append(start_expr.release_nonnull());
  1192. while (expect(',')) {
  1193. auto expr = parse_expression();
  1194. if (expr) {
  1195. subexpressions.append(expr.release_nonnull());
  1196. } else {
  1197. subexpressions.append(create<AST::StringLiteral>(""));
  1198. }
  1199. }
  1200. if (subexpressions.is_empty())
  1201. return nullptr;
  1202. return create<AST::BraceExpansion>(move(subexpressions));
  1203. }
  1204. StringView Parser::consume_while(Function<bool(char)> condition)
  1205. {
  1206. if (at_end())
  1207. return {};
  1208. auto start_offset = m_offset;
  1209. while (!at_end() && condition(peek()))
  1210. consume();
  1211. return m_input.substring_view(start_offset, m_offset - start_offset);
  1212. }
  1213. bool Parser::next_is(const StringView& next)
  1214. {
  1215. auto start = push_start();
  1216. auto res = expect(next);
  1217. restore_to(*start);
  1218. return res;
  1219. }
  1220. }