Parser.cpp 44 KB

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