Parser.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147
  1. /*
  2. * Copyright (c) 2020-2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Parser.h"
  7. #include "Shell.h"
  8. #include <AK/AllOf.h>
  9. #include <AK/GenericLexer.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <AK/ScopedValueRollback.h>
  12. #include <AK/TemporaryChange.h>
  13. #include <ctype.h>
  14. #include <stdio.h>
  15. #include <unistd.h>
  16. namespace Shell {
  17. Parser::SavedOffset Parser::save_offset() const
  18. {
  19. return { m_offset, m_line };
  20. }
  21. char Parser::peek()
  22. {
  23. if (at_end())
  24. return 0;
  25. VERIFY(m_offset < m_input.length());
  26. auto ch = m_input[m_offset];
  27. if (ch == '\\' && m_input.length() > m_offset + 1 && m_input[m_offset + 1] == '\n') {
  28. m_offset += 2;
  29. ++m_line.line_number;
  30. m_line.line_column = 0;
  31. return peek();
  32. }
  33. return ch;
  34. }
  35. char Parser::consume()
  36. {
  37. if (at_end())
  38. return 0;
  39. auto ch = peek();
  40. ++m_offset;
  41. if (ch == '\n') {
  42. ++m_line.line_number;
  43. m_line.line_column = 0;
  44. } else {
  45. ++m_line.line_column;
  46. }
  47. return ch;
  48. }
  49. bool Parser::expect(char ch)
  50. {
  51. return expect(StringView { &ch, 1 });
  52. }
  53. bool Parser::expect(StringView expected)
  54. {
  55. auto offset_at_start = m_offset;
  56. auto line_at_start = line();
  57. if (expected.length() + m_offset > m_input.length())
  58. return false;
  59. for (auto& c : expected) {
  60. if (peek() != c) {
  61. restore_to(offset_at_start, line_at_start);
  62. return false;
  63. }
  64. consume();
  65. }
  66. return true;
  67. }
  68. template<typename A, typename... Args>
  69. NonnullRefPtr<A> Parser::create(Args... args)
  70. {
  71. return adopt_ref(*new A(AST::Position { m_rule_start_offsets.last(), m_offset, m_rule_start_lines.last(), line() }, args...));
  72. }
  73. [[nodiscard]] OwnPtr<Parser::ScopedOffset> Parser::push_start()
  74. {
  75. return make<ScopedOffset>(m_rule_start_offsets, m_rule_start_lines, m_offset, m_line.line_number, m_line.line_column);
  76. }
  77. Parser::Offset Parser::current_position()
  78. {
  79. return Offset { m_offset, { m_line.line_number, m_line.line_column } };
  80. }
  81. static constexpr bool is_whitespace(char c)
  82. {
  83. return c == ' ' || c == '\t';
  84. }
  85. static constexpr bool is_digit(char c)
  86. {
  87. return c <= '9' && c >= '0';
  88. }
  89. static constexpr auto is_not(char c)
  90. {
  91. return [c](char ch) { return ch != c; };
  92. }
  93. static inline char to_byte(char a, char b)
  94. {
  95. char buf[3] { a, b, 0 };
  96. return strtol(buf, nullptr, 16);
  97. }
  98. RefPtr<AST::Node> Parser::parse()
  99. {
  100. m_offset = 0;
  101. m_line = { 0, 0 };
  102. auto toplevel = parse_toplevel();
  103. if (m_offset < m_input.length()) {
  104. // Parsing stopped midway, this is a syntax error.
  105. auto error_start = push_start();
  106. while (!at_end())
  107. consume();
  108. auto syntax_error_node = create<AST::SyntaxError>("Unexpected tokens past the end");
  109. if (!toplevel)
  110. toplevel = move(syntax_error_node);
  111. else if (!toplevel->is_syntax_error())
  112. toplevel->set_is_syntax_error(*syntax_error_node);
  113. }
  114. return toplevel;
  115. }
  116. RefPtr<AST::Node> Parser::parse_as_single_expression()
  117. {
  118. auto input = Shell::escape_token_for_double_quotes(m_input);
  119. Parser parser { input };
  120. return parser.parse_expression();
  121. }
  122. NonnullRefPtrVector<AST::Node> Parser::parse_as_multiple_expressions()
  123. {
  124. NonnullRefPtrVector<AST::Node> nodes;
  125. for (;;) {
  126. consume_while(is_whitespace);
  127. auto node = parse_expression();
  128. if (!node)
  129. node = parse_redirection();
  130. if (!node)
  131. return nodes;
  132. nodes.append(node.release_nonnull());
  133. }
  134. }
  135. RefPtr<AST::Node> Parser::parse_toplevel()
  136. {
  137. auto rule_start = push_start();
  138. SequenceParseResult result;
  139. NonnullRefPtrVector<AST::Node> sequence;
  140. Vector<AST::Position> positions;
  141. do {
  142. result = parse_sequence();
  143. if (result.entries.is_empty())
  144. break;
  145. sequence.extend(move(result.entries));
  146. positions.extend(move(result.separator_positions));
  147. } while (result.decision == ShouldReadMoreSequences::Yes);
  148. if (sequence.is_empty())
  149. return nullptr;
  150. return create<AST::Execute>(
  151. create<AST::Sequence>(move(sequence), move(positions)));
  152. }
  153. Parser::SequenceParseResult Parser::parse_sequence()
  154. {
  155. NonnullRefPtrVector<AST::Node> left;
  156. auto read_terminators = [&](bool consider_tabs_and_spaces) {
  157. if (m_heredoc_initiations.is_empty()) {
  158. discard_terminators:;
  159. consume_while(is_any_of(consider_tabs_and_spaces ? " \t\n;" : "\n;"));
  160. } else {
  161. for (;;) {
  162. if (consider_tabs_and_spaces && (peek() == '\t' || peek() == ' ')) {
  163. consume();
  164. continue;
  165. }
  166. if (peek() == ';') {
  167. consume();
  168. continue;
  169. }
  170. if (peek() == '\n') {
  171. auto rule_start = push_start();
  172. consume();
  173. if (!parse_heredoc_entries()) {
  174. StringBuilder error_builder;
  175. error_builder.append("Expected to find heredoc entries for ");
  176. bool first = true;
  177. for (auto& entry : m_heredoc_initiations) {
  178. if (first)
  179. error_builder.appendff("{} (at {}:{})", entry.end, entry.node->position().start_line.line_column, entry.node->position().start_line.line_number);
  180. else
  181. error_builder.appendff(", {} (at {}:{})", entry.end, entry.node->position().start_line.line_column, entry.node->position().start_line.line_number);
  182. first = false;
  183. }
  184. left.append(create<AST::SyntaxError>(error_builder.build(), true));
  185. // Just read the rest of the newlines
  186. goto discard_terminators;
  187. }
  188. continue;
  189. }
  190. break;
  191. }
  192. }
  193. };
  194. read_terminators(true);
  195. auto rule_start = push_start();
  196. {
  197. auto var_decls = parse_variable_decls();
  198. if (var_decls)
  199. left.append(var_decls.release_nonnull());
  200. }
  201. auto pos_before_seps = save_offset();
  202. switch (peek()) {
  203. case '}':
  204. return { move(left), {}, ShouldReadMoreSequences::No };
  205. case '\n':
  206. read_terminators(false);
  207. [[fallthrough]];
  208. case ';': {
  209. if (left.is_empty())
  210. break;
  211. consume_while(is_any_of("\n;"));
  212. auto pos_after_seps = save_offset();
  213. AST::Position separator_position { pos_before_seps.offset, pos_after_seps.offset, pos_before_seps.line, pos_after_seps.line };
  214. return { move(left), { move(separator_position) }, ShouldReadMoreSequences::Yes };
  215. }
  216. default:
  217. break;
  218. }
  219. auto first_entry = parse_function_decl();
  220. Vector<AST::Position> separator_positions;
  221. if (!first_entry)
  222. first_entry = parse_or_logical_sequence();
  223. if (!first_entry)
  224. return { move(left), {}, ShouldReadMoreSequences::No };
  225. left.append(first_entry.release_nonnull());
  226. separator_positions.empend(pos_before_seps.offset, pos_before_seps.offset, pos_before_seps.line, pos_before_seps.line);
  227. consume_while(is_whitespace);
  228. pos_before_seps = save_offset();
  229. switch (peek()) {
  230. case '\n':
  231. read_terminators(false);
  232. [[fallthrough]];
  233. case ';': {
  234. consume_while(is_any_of("\n;"));
  235. auto pos_after_seps = save_offset();
  236. separator_positions.empend(pos_before_seps.offset, pos_after_seps.offset, pos_before_seps.line, pos_after_seps.line);
  237. return { move(left), move(separator_positions), ShouldReadMoreSequences::Yes };
  238. }
  239. case '&': {
  240. consume();
  241. auto pos_after_seps = save_offset();
  242. auto bg = create<AST::Background>(left.take_last()); // Execute Background
  243. left.append(move(bg));
  244. separator_positions.empend(pos_before_seps.offset, pos_after_seps.offset, pos_before_seps.line, pos_after_seps.line);
  245. return { move(left), move(separator_positions), ShouldReadMoreSequences::Yes };
  246. }
  247. default:
  248. return { move(left), move(separator_positions), ShouldReadMoreSequences::No };
  249. }
  250. }
  251. RefPtr<AST::Node> Parser::parse_variable_decls()
  252. {
  253. auto rule_start = push_start();
  254. consume_while(is_whitespace);
  255. auto pos_before_name = save_offset();
  256. auto var_name = consume_while(is_word_character);
  257. if (var_name.is_empty())
  258. return nullptr;
  259. if (!expect('=')) {
  260. restore_to(pos_before_name.offset, pos_before_name.line);
  261. return nullptr;
  262. }
  263. auto name_expr = create<AST::BarewordLiteral>(move(var_name));
  264. auto start = push_start();
  265. auto expression = parse_expression();
  266. if (!expression || expression->is_syntax_error()) {
  267. restore_to(*start);
  268. if (peek() == '(') {
  269. consume();
  270. auto command = parse_pipe_sequence();
  271. if (!command)
  272. restore_to(*start);
  273. else if (!expect(')'))
  274. command->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating close paren", true));
  275. expression = command;
  276. }
  277. }
  278. if (!expression) {
  279. if (is_whitespace(peek())) {
  280. auto string_start = push_start();
  281. expression = create<AST::StringLiteral>("");
  282. } else {
  283. restore_to(pos_before_name.offset, pos_before_name.line);
  284. return nullptr;
  285. }
  286. }
  287. Vector<AST::VariableDeclarations::Variable> variables;
  288. variables.append({ move(name_expr), expression.release_nonnull() });
  289. if (consume_while(is_whitespace).is_empty())
  290. return create<AST::VariableDeclarations>(move(variables));
  291. auto rest = parse_variable_decls();
  292. if (!rest)
  293. return create<AST::VariableDeclarations>(move(variables));
  294. VERIFY(rest->is_variable_decls());
  295. auto* rest_decl = static_cast<AST::VariableDeclarations*>(rest.ptr());
  296. variables.extend(rest_decl->variables());
  297. return create<AST::VariableDeclarations>(move(variables));
  298. }
  299. RefPtr<AST::Node> Parser::parse_function_decl()
  300. {
  301. auto rule_start = push_start();
  302. auto restore = [&] {
  303. restore_to(*rule_start);
  304. return nullptr;
  305. };
  306. consume_while(is_whitespace);
  307. auto pos_before_name = save_offset();
  308. auto function_name = consume_while(is_word_character);
  309. auto pos_after_name = save_offset();
  310. if (function_name.is_empty())
  311. return restore();
  312. if (!expect('('))
  313. return restore();
  314. Vector<AST::NameWithPosition> arguments;
  315. for (;;) {
  316. consume_while(is_whitespace);
  317. if (expect(')'))
  318. break;
  319. auto name_offset = m_offset;
  320. auto start_line = line();
  321. auto arg_name = consume_while(is_word_character);
  322. if (arg_name.is_empty()) {
  323. // FIXME: Should this be a syntax error, or just return?
  324. return restore();
  325. }
  326. arguments.append({ arg_name, { name_offset, m_offset, start_line, line() } });
  327. }
  328. consume_while(is_any_of("\n\t "));
  329. {
  330. RefPtr<AST::Node> syntax_error;
  331. {
  332. auto obrace_error_start = push_start();
  333. syntax_error = create<AST::SyntaxError>("Expected an open brace '{' to start a function body", true);
  334. }
  335. if (!expect('{')) {
  336. return create<AST::FunctionDeclaration>(
  337. AST::NameWithPosition {
  338. move(function_name),
  339. { pos_before_name.offset, pos_after_name.offset, pos_before_name.line, pos_after_name.line } },
  340. move(arguments),
  341. move(syntax_error));
  342. }
  343. }
  344. TemporaryChange controls { m_continuation_controls_allowed, false };
  345. auto body = parse_toplevel();
  346. {
  347. RefPtr<AST::SyntaxError> syntax_error;
  348. {
  349. auto cbrace_error_start = push_start();
  350. syntax_error = create<AST::SyntaxError>("Expected a close brace '}' to end a function body", true);
  351. }
  352. if (!expect('}')) {
  353. if (body)
  354. body->set_is_syntax_error(*syntax_error);
  355. else
  356. body = move(syntax_error);
  357. return create<AST::FunctionDeclaration>(
  358. AST::NameWithPosition {
  359. move(function_name),
  360. { pos_before_name.offset, pos_after_name.offset, pos_before_name.line, pos_after_name.line } },
  361. move(arguments),
  362. move(body));
  363. }
  364. }
  365. return create<AST::FunctionDeclaration>(
  366. AST::NameWithPosition {
  367. move(function_name),
  368. { pos_before_name.offset, pos_after_name.offset, pos_before_name.line, pos_after_name.line } },
  369. move(arguments),
  370. move(body));
  371. }
  372. RefPtr<AST::Node> Parser::parse_or_logical_sequence()
  373. {
  374. consume_while(is_whitespace);
  375. auto rule_start = push_start();
  376. auto and_sequence = parse_and_logical_sequence();
  377. if (!and_sequence)
  378. return nullptr;
  379. consume_while(is_whitespace);
  380. auto pos_before_or = save_offset();
  381. if (!expect("||"))
  382. return and_sequence;
  383. auto pos_after_or = save_offset();
  384. auto right_and_sequence = parse_and_logical_sequence();
  385. if (!right_and_sequence)
  386. right_and_sequence = create<AST::SyntaxError>("Expected an expression after '||'", true);
  387. return create<AST::Or>(
  388. and_sequence.release_nonnull(),
  389. right_and_sequence.release_nonnull(),
  390. AST::Position { pos_before_or.offset, pos_after_or.offset, pos_before_or.line, pos_after_or.line });
  391. }
  392. RefPtr<AST::Node> Parser::parse_and_logical_sequence()
  393. {
  394. consume_while(is_whitespace);
  395. auto rule_start = push_start();
  396. auto pipe_sequence = parse_pipe_sequence();
  397. if (!pipe_sequence)
  398. return nullptr;
  399. consume_while(is_whitespace);
  400. auto pos_before_and = save_offset();
  401. if (!expect("&&"))
  402. return pipe_sequence;
  403. auto pos_after_end = save_offset();
  404. auto right_and_sequence = parse_and_logical_sequence();
  405. if (!right_and_sequence)
  406. right_and_sequence = create<AST::SyntaxError>("Expected an expression after '&&'", true);
  407. return create<AST::And>(
  408. pipe_sequence.release_nonnull(),
  409. right_and_sequence.release_nonnull(),
  410. AST::Position { pos_before_and.offset, pos_after_end.offset, pos_before_and.line, pos_after_end.line });
  411. }
  412. RefPtr<AST::Node> Parser::parse_pipe_sequence()
  413. {
  414. auto rule_start = push_start();
  415. auto left = parse_control_structure();
  416. if (!left) {
  417. if (auto cmd = parse_command())
  418. left = cmd;
  419. else
  420. return nullptr;
  421. }
  422. consume_while(is_whitespace);
  423. if (peek() != '|')
  424. return left;
  425. auto before_pipe = save_offset();
  426. consume();
  427. if (auto pipe_seq = parse_pipe_sequence()) {
  428. return create<AST::Pipe>(left.release_nonnull(), pipe_seq.release_nonnull()); // Pipe
  429. }
  430. restore_to(before_pipe.offset, before_pipe.line);
  431. return left;
  432. }
  433. RefPtr<AST::Node> Parser::parse_command()
  434. {
  435. auto rule_start = push_start();
  436. consume_while(is_whitespace);
  437. auto redir = parse_redirection();
  438. if (!redir) {
  439. auto list_expr = parse_list_expression();
  440. if (!list_expr)
  441. return nullptr;
  442. auto cast = create<AST::CastToCommand>(list_expr.release_nonnull()); // Cast List Command
  443. auto next_command = parse_command();
  444. if (!next_command)
  445. return cast;
  446. return create<AST::Join>(move(cast), next_command.release_nonnull()); // Join List Command
  447. }
  448. auto command = parse_command();
  449. if (!command)
  450. return redir;
  451. return create<AST::Join>(redir.release_nonnull(), command.release_nonnull()); // Join Command Command
  452. }
  453. RefPtr<AST::Node> Parser::parse_control_structure()
  454. {
  455. auto rule_start = push_start();
  456. consume_while(is_whitespace);
  457. if (auto control = parse_continuation_control())
  458. return control;
  459. if (auto for_loop = parse_for_loop())
  460. return for_loop;
  461. if (auto loop = parse_loop_loop())
  462. return loop;
  463. if (auto if_expr = parse_if_expr())
  464. return if_expr;
  465. if (auto subshell = parse_subshell())
  466. return subshell;
  467. if (auto match = parse_match_expr())
  468. return match;
  469. return nullptr;
  470. }
  471. RefPtr<AST::Node> Parser::parse_continuation_control()
  472. {
  473. if (!m_continuation_controls_allowed)
  474. return nullptr;
  475. auto rule_start = push_start();
  476. if (expect("break")) {
  477. {
  478. auto break_end = push_start();
  479. if (consume_while(is_any_of(" \t\n;")).is_empty()) {
  480. restore_to(*rule_start);
  481. return nullptr;
  482. }
  483. restore_to(*break_end);
  484. }
  485. return create<AST::ContinuationControl>(AST::ContinuationControl::Break);
  486. }
  487. if (expect("continue")) {
  488. {
  489. auto continue_end = push_start();
  490. if (consume_while(is_any_of(" \t\n;")).is_empty()) {
  491. restore_to(*rule_start);
  492. return nullptr;
  493. }
  494. restore_to(*continue_end);
  495. }
  496. return create<AST::ContinuationControl>(AST::ContinuationControl::Continue);
  497. }
  498. return nullptr;
  499. }
  500. RefPtr<AST::Node> Parser::parse_for_loop()
  501. {
  502. auto rule_start = push_start();
  503. if (!expect("for"))
  504. return nullptr;
  505. if (consume_while(is_any_of(" \t\n")).is_empty()) {
  506. restore_to(*rule_start);
  507. return nullptr;
  508. }
  509. Optional<AST::NameWithPosition> index_variable_name, variable_name;
  510. Optional<AST::Position> in_start_position, index_start_position;
  511. auto offset_before_index = current_position();
  512. if (expect("index")) {
  513. auto offset = current_position();
  514. if (!consume_while(is_whitespace).is_empty()) {
  515. auto offset_before_variable = current_position();
  516. auto variable = consume_while(is_word_character);
  517. if (!variable.is_empty()) {
  518. index_start_position = AST::Position { offset_before_index.offset, offset.offset, offset_before_index.line, offset.line };
  519. auto offset_after_variable = current_position();
  520. index_variable_name = AST::NameWithPosition {
  521. variable,
  522. { offset_before_variable.offset, offset_after_variable.offset, offset_before_variable.line, offset_after_variable.line },
  523. };
  524. consume_while(is_whitespace);
  525. } else {
  526. restore_to(offset_before_index.offset, offset_before_index.line);
  527. }
  528. } else {
  529. restore_to(offset_before_index.offset, offset_before_index.line);
  530. }
  531. }
  532. auto variable_name_start_offset = current_position();
  533. auto name = consume_while(is_word_character);
  534. auto variable_name_end_offset = current_position();
  535. if (!name.is_empty()) {
  536. variable_name = AST::NameWithPosition {
  537. name,
  538. { variable_name_start_offset.offset, variable_name_end_offset.offset, variable_name_start_offset.line, variable_name_end_offset.line }
  539. };
  540. consume_while(is_whitespace);
  541. auto in_error_start = push_start();
  542. if (!expect("in")) {
  543. auto syntax_error = create<AST::SyntaxError>("Expected 'in' after a variable name in a 'for' loop", true);
  544. return create<AST::ForLoop>(move(variable_name), move(index_variable_name), move(syntax_error), nullptr); // ForLoop Var Iterated Block
  545. }
  546. in_start_position = AST::Position { in_error_start->offset, m_offset, in_error_start->line, line() };
  547. }
  548. consume_while(is_whitespace);
  549. RefPtr<AST::Node> iterated_expression;
  550. {
  551. auto iter_error_start = push_start();
  552. iterated_expression = parse_expression();
  553. if (!iterated_expression)
  554. iterated_expression = create<AST::SyntaxError>("Expected an expression in 'for' loop", true);
  555. }
  556. consume_while(is_any_of(" \t\n"));
  557. {
  558. auto obrace_error_start = push_start();
  559. if (!expect('{')) {
  560. auto syntax_error = create<AST::SyntaxError>("Expected an open brace '{' to start a 'for' loop body", true);
  561. return create<AST::ForLoop>(move(variable_name), move(index_variable_name), move(iterated_expression), move(syntax_error), move(in_start_position), move(index_start_position)); // ForLoop Var Iterated Block
  562. }
  563. }
  564. TemporaryChange controls { m_continuation_controls_allowed, true };
  565. auto body = parse_toplevel();
  566. {
  567. auto cbrace_error_start = push_start();
  568. if (!expect('}')) {
  569. auto error_start = push_start();
  570. auto syntax_error = create<AST::SyntaxError>("Expected a close brace '}' to end a 'for' loop body", true);
  571. if (body)
  572. body->set_is_syntax_error(*syntax_error);
  573. else
  574. body = syntax_error;
  575. }
  576. }
  577. return create<AST::ForLoop>(move(variable_name), move(index_variable_name), move(iterated_expression), move(body), move(in_start_position), move(index_start_position)); // ForLoop Var Iterated Block
  578. }
  579. RefPtr<AST::Node> Parser::parse_loop_loop()
  580. {
  581. auto rule_start = push_start();
  582. if (!expect("loop"))
  583. return nullptr;
  584. if (consume_while(is_any_of(" \t\n")).is_empty()) {
  585. restore_to(*rule_start);
  586. return nullptr;
  587. }
  588. {
  589. auto obrace_error_start = push_start();
  590. if (!expect('{')) {
  591. auto syntax_error = create<AST::SyntaxError>("Expected an open brace '{' to start a 'loop' loop body", true);
  592. return create<AST::ForLoop>(AST::NameWithPosition {}, AST::NameWithPosition {}, nullptr, move(syntax_error)); // ForLoop null null Block
  593. }
  594. }
  595. TemporaryChange controls { m_continuation_controls_allowed, true };
  596. auto body = parse_toplevel();
  597. {
  598. auto cbrace_error_start = push_start();
  599. if (!expect('}')) {
  600. auto error_start = push_start();
  601. auto syntax_error = create<AST::SyntaxError>("Expected a close brace '}' to end a 'loop' loop body", true);
  602. if (body)
  603. body->set_is_syntax_error(*syntax_error);
  604. else
  605. body = syntax_error;
  606. }
  607. }
  608. return create<AST::ForLoop>(AST::NameWithPosition {}, AST::NameWithPosition {}, nullptr, move(body)); // ForLoop null null Block
  609. }
  610. RefPtr<AST::Node> Parser::parse_if_expr()
  611. {
  612. auto rule_start = push_start();
  613. if (!expect("if"))
  614. return nullptr;
  615. if (consume_while(is_any_of(" \t\n")).is_empty()) {
  616. restore_to(*rule_start);
  617. return nullptr;
  618. }
  619. RefPtr<AST::Node> condition;
  620. {
  621. auto cond_error_start = push_start();
  622. condition = parse_or_logical_sequence();
  623. if (!condition)
  624. condition = create<AST::SyntaxError>("Expected a logical sequence after 'if'", true);
  625. }
  626. auto parse_braced_toplevel = [&]() -> RefPtr<AST::Node> {
  627. RefPtr<AST::Node> body;
  628. {
  629. auto obrace_error_start = push_start();
  630. if (!expect('{')) {
  631. body = create<AST::SyntaxError>("Expected an open brace '{' to start an 'if' true branch", true);
  632. }
  633. }
  634. if (!body)
  635. body = parse_toplevel();
  636. {
  637. auto cbrace_error_start = push_start();
  638. if (!expect('}')) {
  639. auto error_start = push_start();
  640. RefPtr<AST::SyntaxError> syntax_error = create<AST::SyntaxError>("Expected a close brace '}' to end an 'if' true branch", true);
  641. if (body)
  642. body->set_is_syntax_error(*syntax_error);
  643. else
  644. body = syntax_error;
  645. }
  646. }
  647. return body;
  648. };
  649. consume_while(is_any_of(" \t\n"));
  650. auto true_branch = parse_braced_toplevel();
  651. auto end_before_else = m_offset;
  652. auto line_before_else = line();
  653. consume_while(is_any_of(" \t\n"));
  654. Optional<AST::Position> else_position;
  655. {
  656. auto else_start = push_start();
  657. if (expect("else"))
  658. else_position = AST::Position { else_start->offset, m_offset, else_start->line, line() };
  659. else
  660. restore_to(end_before_else, line_before_else);
  661. }
  662. if (else_position.has_value()) {
  663. consume_while(is_any_of(" \t\n"));
  664. if (peek() == '{') {
  665. auto false_branch = parse_braced_toplevel();
  666. return create<AST::IfCond>(else_position, condition.release_nonnull(), move(true_branch), move(false_branch)); // If expr true_branch Else false_branch
  667. }
  668. auto else_if_branch = parse_if_expr();
  669. return create<AST::IfCond>(else_position, condition.release_nonnull(), move(true_branch), move(else_if_branch)); // If expr true_branch Else If ...
  670. }
  671. return create<AST::IfCond>(else_position, condition.release_nonnull(), move(true_branch), nullptr); // If expr true_branch
  672. }
  673. RefPtr<AST::Node> Parser::parse_subshell()
  674. {
  675. auto rule_start = push_start();
  676. if (!expect('{'))
  677. return nullptr;
  678. auto body = parse_toplevel();
  679. {
  680. auto cbrace_error_start = push_start();
  681. if (!expect('}')) {
  682. auto error_start = push_start();
  683. RefPtr<AST::SyntaxError> syntax_error = create<AST::SyntaxError>("Expected a close brace '}' to end a subshell", true);
  684. if (body)
  685. body->set_is_syntax_error(*syntax_error);
  686. else
  687. body = syntax_error;
  688. }
  689. }
  690. return create<AST::Subshell>(move(body));
  691. }
  692. RefPtr<AST::Node> Parser::parse_match_expr()
  693. {
  694. auto rule_start = push_start();
  695. if (!expect("match"))
  696. return nullptr;
  697. if (consume_while(is_whitespace).is_empty()) {
  698. restore_to(*rule_start);
  699. return nullptr;
  700. }
  701. auto match_expression = parse_expression();
  702. if (!match_expression) {
  703. return create<AST::MatchExpr>(
  704. create<AST::SyntaxError>("Expected an expression after 'match'", true),
  705. String {}, Optional<AST::Position> {}, Vector<AST::MatchEntry> {});
  706. }
  707. consume_while(is_any_of(" \t\n"));
  708. String match_name;
  709. Optional<AST::Position> as_position;
  710. auto as_start = m_offset;
  711. auto as_line = line();
  712. if (expect("as")) {
  713. as_position = AST::Position { as_start, m_offset, as_line, line() };
  714. if (consume_while(is_any_of(" \t\n")).is_empty()) {
  715. auto node = create<AST::MatchExpr>(
  716. match_expression.release_nonnull(),
  717. String {}, move(as_position), Vector<AST::MatchEntry> {});
  718. node->set_is_syntax_error(create<AST::SyntaxError>("Expected whitespace after 'as' in 'match'", true));
  719. return node;
  720. }
  721. match_name = consume_while(is_word_character);
  722. if (match_name.is_empty()) {
  723. auto node = create<AST::MatchExpr>(
  724. match_expression.release_nonnull(),
  725. String {}, move(as_position), Vector<AST::MatchEntry> {});
  726. node->set_is_syntax_error(create<AST::SyntaxError>("Expected an identifier after 'as' in 'match'", true));
  727. return node;
  728. }
  729. }
  730. consume_while(is_any_of(" \t\n"));
  731. if (!expect('{')) {
  732. auto node = create<AST::MatchExpr>(
  733. match_expression.release_nonnull(),
  734. move(match_name), move(as_position), Vector<AST::MatchEntry> {});
  735. node->set_is_syntax_error(create<AST::SyntaxError>("Expected an open brace '{' to start a 'match' entry list", true));
  736. return node;
  737. }
  738. consume_while(is_any_of(" \t\n"));
  739. Vector<AST::MatchEntry> entries;
  740. for (;;) {
  741. auto entry = parse_match_entry();
  742. consume_while(is_any_of(" \t\n"));
  743. if (entry.options.is_empty())
  744. break;
  745. entries.append(entry);
  746. }
  747. consume_while(is_any_of(" \t\n"));
  748. if (!expect('}')) {
  749. auto node = create<AST::MatchExpr>(
  750. match_expression.release_nonnull(),
  751. move(match_name), move(as_position), move(entries));
  752. node->set_is_syntax_error(create<AST::SyntaxError>("Expected a close brace '}' to end a 'match' entry list", true));
  753. return node;
  754. }
  755. return create<AST::MatchExpr>(match_expression.release_nonnull(), move(match_name), move(as_position), move(entries));
  756. }
  757. AST::MatchEntry Parser::parse_match_entry()
  758. {
  759. auto rule_start = push_start();
  760. NonnullRefPtrVector<AST::Node> patterns;
  761. Vector<AST::Position> pipe_positions;
  762. Optional<Vector<String>> match_names;
  763. Optional<AST::Position> match_as_position;
  764. auto pattern = parse_match_pattern();
  765. if (!pattern)
  766. return { {}, {}, {}, {}, create<AST::SyntaxError>("Expected a pattern in 'match' body", true) };
  767. patterns.append(pattern.release_nonnull());
  768. consume_while(is_any_of(" \t\n"));
  769. auto previous_pipe_start_position = m_offset;
  770. auto previous_pipe_start_line = line();
  771. RefPtr<AST::SyntaxError> error;
  772. while (expect('|')) {
  773. pipe_positions.append({ previous_pipe_start_position, m_offset, previous_pipe_start_line, line() });
  774. consume_while(is_any_of(" \t\n"));
  775. auto pattern = parse_match_pattern();
  776. if (!pattern) {
  777. error = create<AST::SyntaxError>("Expected a pattern to follow '|' in 'match' body", true);
  778. break;
  779. }
  780. consume_while(is_any_of(" \t\n"));
  781. patterns.append(pattern.release_nonnull());
  782. previous_pipe_start_line = line();
  783. previous_pipe_start_position = m_offset;
  784. }
  785. consume_while(is_any_of(" \t\n"));
  786. auto as_start_position = m_offset;
  787. auto as_start_line = line();
  788. if (expect("as")) {
  789. match_as_position = AST::Position { as_start_position, m_offset, as_start_line, line() };
  790. consume_while(is_any_of(" \t\n"));
  791. if (!expect('(')) {
  792. if (!error)
  793. error = create<AST::SyntaxError>("Expected an explicit list of identifiers after a pattern 'as'");
  794. } else {
  795. match_names = Vector<String>();
  796. for (;;) {
  797. consume_while(is_whitespace);
  798. auto name = consume_while(is_word_character);
  799. if (name.is_empty())
  800. break;
  801. match_names.value().append(move(name));
  802. }
  803. if (!expect(')')) {
  804. if (!error)
  805. error = create<AST::SyntaxError>("Expected a close paren ')' to end the identifier list of pattern 'as'", true);
  806. }
  807. }
  808. consume_while(is_any_of(" \t\n"));
  809. }
  810. if (!expect('{')) {
  811. if (!error)
  812. error = create<AST::SyntaxError>("Expected an open brace '{' to start a match entry body", true);
  813. }
  814. auto body = parse_toplevel();
  815. if (!expect('}')) {
  816. if (!error)
  817. error = create<AST::SyntaxError>("Expected a close brace '}' to end a match entry body", true);
  818. }
  819. if (body && error)
  820. body->set_is_syntax_error(*error);
  821. else if (error)
  822. body = error;
  823. return { move(patterns), move(match_names), move(match_as_position), move(pipe_positions), move(body) };
  824. }
  825. RefPtr<AST::Node> Parser::parse_match_pattern()
  826. {
  827. return parse_expression();
  828. }
  829. RefPtr<AST::Node> Parser::parse_redirection()
  830. {
  831. auto rule_start = push_start();
  832. // heredoc entry
  833. if (next_is("<<-") || next_is("<<~"))
  834. return nullptr;
  835. auto pipe_fd = 0;
  836. auto number = consume_while(is_digit);
  837. if (number.is_empty()) {
  838. pipe_fd = -1;
  839. } else {
  840. auto fd = number.to_int();
  841. pipe_fd = fd.value_or(-1);
  842. }
  843. switch (peek()) {
  844. case '>': {
  845. consume();
  846. if (peek() == '>') {
  847. consume();
  848. consume_while(is_whitespace);
  849. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  850. auto path = parse_expression();
  851. if (!path) {
  852. if (!at_end()) {
  853. // Eat a character and hope the problem goes away
  854. consume();
  855. }
  856. path = create<AST::SyntaxError>("Expected a path after redirection", true);
  857. }
  858. return create<AST::WriteAppendRedirection>(pipe_fd, path.release_nonnull()); // Redirection WriteAppend
  859. }
  860. if (peek() == '&') {
  861. consume();
  862. // FIXME: 'fd>&-' Syntax not the best. needs discussion.
  863. if (peek() == '-') {
  864. consume();
  865. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  866. return create<AST::CloseFdRedirection>(pipe_fd); // Redirection CloseFd
  867. }
  868. int dest_pipe_fd = 0;
  869. auto number = consume_while(is_digit);
  870. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  871. if (number.is_empty()) {
  872. dest_pipe_fd = -1;
  873. } else {
  874. auto fd = number.to_int();
  875. dest_pipe_fd = fd.value_or(-1);
  876. }
  877. auto redir = create<AST::Fd2FdRedirection>(pipe_fd, dest_pipe_fd); // Redirection Fd2Fd
  878. if (dest_pipe_fd == -1)
  879. redir->set_is_syntax_error(*create<AST::SyntaxError>("Expected a file descriptor"));
  880. return redir;
  881. }
  882. consume_while(is_whitespace);
  883. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  884. auto path = parse_expression();
  885. if (!path) {
  886. if (!at_end()) {
  887. // Eat a character and hope the problem goes away
  888. consume();
  889. }
  890. path = create<AST::SyntaxError>("Expected a path after redirection", true);
  891. }
  892. return create<AST::WriteRedirection>(pipe_fd, path.release_nonnull()); // Redirection Write
  893. }
  894. case '<': {
  895. consume();
  896. enum {
  897. Read,
  898. ReadWrite,
  899. } mode { Read };
  900. if (peek() == '>') {
  901. mode = ReadWrite;
  902. consume();
  903. }
  904. consume_while(is_whitespace);
  905. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDIN_FILENO;
  906. auto path = parse_expression();
  907. if (!path) {
  908. if (!at_end()) {
  909. // Eat a character and hope the problem goes away
  910. consume();
  911. }
  912. path = create<AST::SyntaxError>("Expected a path after redirection", true);
  913. }
  914. if (mode == Read)
  915. return create<AST::ReadRedirection>(pipe_fd, path.release_nonnull()); // Redirection Read
  916. return create<AST::ReadWriteRedirection>(pipe_fd, path.release_nonnull()); // Redirection ReadWrite
  917. }
  918. default:
  919. restore_to(*rule_start);
  920. return nullptr;
  921. }
  922. }
  923. RefPtr<AST::Node> Parser::parse_list_expression()
  924. {
  925. consume_while(is_whitespace);
  926. auto rule_start = push_start();
  927. Vector<NonnullRefPtr<AST::Node>> nodes;
  928. do {
  929. auto expr = parse_expression();
  930. if (!expr)
  931. break;
  932. nodes.append(expr.release_nonnull());
  933. } while (!consume_while(is_whitespace).is_empty());
  934. if (nodes.is_empty())
  935. return nullptr;
  936. return create<AST::ListConcatenate>(move(nodes)); // Concatenate List
  937. }
  938. RefPtr<AST::Node> Parser::parse_expression()
  939. {
  940. auto rule_start = push_start();
  941. if (m_rule_start_offsets.size() > max_allowed_nested_rule_depth)
  942. return create<AST::SyntaxError>(String::formatted("Expression nested too deep (max allowed is {})", max_allowed_nested_rule_depth));
  943. auto starting_char = peek();
  944. auto read_concat = [&](auto&& expr) -> NonnullRefPtr<AST::Node> {
  945. if (is_whitespace(peek()))
  946. return move(expr);
  947. if (auto next_expr = parse_expression())
  948. return create<AST::Juxtaposition>(move(expr), next_expr.release_nonnull());
  949. return move(expr);
  950. };
  951. // Heredocs are expressions, so allow them
  952. if (!(next_is("<<-") || next_is("<<~"))) {
  953. if (strchr("&|)} ;<>\n", starting_char) != nullptr)
  954. return nullptr;
  955. }
  956. if (m_extra_chars_not_allowed_in_barewords.contains_slow(starting_char))
  957. return nullptr;
  958. if (m_is_in_brace_expansion_spec && next_is(".."))
  959. return nullptr;
  960. if (isdigit(starting_char)) {
  961. ScopedValueRollback offset_rollback { m_offset };
  962. auto redir = parse_redirection();
  963. if (redir)
  964. return nullptr;
  965. }
  966. if (starting_char == '$') {
  967. if (auto variable = parse_variable())
  968. return read_concat(variable.release_nonnull());
  969. if (auto immediate = parse_immediate_expression())
  970. return read_concat(immediate.release_nonnull());
  971. auto inline_exec = parse_evaluate();
  972. if (inline_exec && !inline_exec->is_syntax_error())
  973. return read_concat(inline_exec.release_nonnull());
  974. return inline_exec;
  975. }
  976. if (starting_char == '#')
  977. return parse_comment();
  978. if (starting_char == '(') {
  979. consume();
  980. auto list = parse_list_expression();
  981. if (!expect(')')) {
  982. restore_to(*rule_start);
  983. return nullptr;
  984. }
  985. return read_concat(create<AST::CastToList>(move(list))); // Cast To List
  986. }
  987. if (starting_char == '!' && m_in_interactive_mode) {
  988. if (auto designator = parse_history_designator())
  989. return designator;
  990. }
  991. if (auto composite = parse_string_composite())
  992. return read_concat(composite.release_nonnull());
  993. return nullptr;
  994. }
  995. RefPtr<AST::Node> Parser::parse_string_composite()
  996. {
  997. auto rule_start = push_start();
  998. if (auto string = parse_string()) {
  999. if (auto next_part = parse_string_composite())
  1000. return create<AST::Juxtaposition>(string.release_nonnull(), next_part.release_nonnull()); // Concatenate String StringComposite
  1001. return string;
  1002. }
  1003. if (auto variable = parse_variable()) {
  1004. if (auto next_part = parse_string_composite())
  1005. return create<AST::Juxtaposition>(variable.release_nonnull(), next_part.release_nonnull()); // Concatenate Variable StringComposite
  1006. return variable;
  1007. }
  1008. if (auto glob = parse_glob()) {
  1009. if (auto next_part = parse_string_composite())
  1010. return create<AST::Juxtaposition>(glob.release_nonnull(), next_part.release_nonnull()); // Concatenate Glob StringComposite
  1011. return glob;
  1012. }
  1013. if (auto expansion = parse_brace_expansion()) {
  1014. if (auto next_part = parse_string_composite())
  1015. return create<AST::Juxtaposition>(expansion.release_nonnull(), next_part.release_nonnull()); // Concatenate BraceExpansion StringComposite
  1016. return expansion;
  1017. }
  1018. if (auto bareword = parse_bareword()) {
  1019. if (auto next_part = parse_string_composite())
  1020. return create<AST::Juxtaposition>(bareword.release_nonnull(), next_part.release_nonnull()); // Concatenate Bareword StringComposite
  1021. return bareword;
  1022. }
  1023. if (auto inline_command = parse_evaluate()) {
  1024. if (auto next_part = parse_string_composite())
  1025. return create<AST::Juxtaposition>(inline_command.release_nonnull(), next_part.release_nonnull()); // Concatenate Execute StringComposite
  1026. return inline_command;
  1027. }
  1028. if (auto heredoc = parse_heredoc_initiation_record()) {
  1029. if (auto next_part = parse_string_composite())
  1030. return create<AST::Juxtaposition>(heredoc.release_nonnull(), next_part.release_nonnull()); // Concatenate Heredoc StringComposite
  1031. return heredoc;
  1032. }
  1033. return nullptr;
  1034. }
  1035. RefPtr<AST::Node> Parser::parse_string()
  1036. {
  1037. auto rule_start = push_start();
  1038. if (at_end())
  1039. return nullptr;
  1040. if (peek() == '"') {
  1041. consume();
  1042. auto inner = parse_string_inner(StringEndCondition::DoubleQuote);
  1043. if (!inner)
  1044. inner = create<AST::SyntaxError>("Unexpected EOF in string", true);
  1045. if (!expect('"')) {
  1046. inner = create<AST::DoubleQuotedString>(move(inner));
  1047. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating double quote", true));
  1048. return inner;
  1049. }
  1050. return create<AST::DoubleQuotedString>(move(inner)); // Double Quoted String
  1051. }
  1052. if (peek() == '\'') {
  1053. consume();
  1054. auto text = consume_while(is_not('\''));
  1055. bool is_error = false;
  1056. if (!expect('\''))
  1057. is_error = true;
  1058. auto result = create<AST::StringLiteral>(move(text)); // String Literal
  1059. if (is_error)
  1060. result->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating single quote", true));
  1061. return result;
  1062. }
  1063. return nullptr;
  1064. }
  1065. RefPtr<AST::Node> Parser::parse_string_inner(StringEndCondition condition)
  1066. {
  1067. auto rule_start = push_start();
  1068. if (at_end())
  1069. return nullptr;
  1070. StringBuilder builder;
  1071. while (!at_end()) {
  1072. if (condition == StringEndCondition::DoubleQuote && peek() == '"') {
  1073. break;
  1074. }
  1075. if (peek() == '\\') {
  1076. consume();
  1077. if (at_end()) {
  1078. break;
  1079. }
  1080. auto ch = consume();
  1081. switch (ch) {
  1082. case '\\':
  1083. default:
  1084. builder.append(ch);
  1085. break;
  1086. case 'x': {
  1087. if (m_input.length() <= m_offset + 2)
  1088. break;
  1089. auto first_nibble = tolower(consume());
  1090. auto second_nibble = tolower(consume());
  1091. if (!isxdigit(first_nibble) || !isxdigit(second_nibble)) {
  1092. builder.append(first_nibble);
  1093. builder.append(second_nibble);
  1094. break;
  1095. }
  1096. builder.append(to_byte(first_nibble, second_nibble));
  1097. break;
  1098. }
  1099. case 'u': {
  1100. if (m_input.length() <= m_offset + 8)
  1101. break;
  1102. size_t counter = 8;
  1103. auto chars = consume_while([&](auto) { return counter-- > 0; });
  1104. if (auto number = AK::StringUtils::convert_to_uint_from_hex(chars); number.has_value())
  1105. builder.append(Utf32View { &number.value(), 1 });
  1106. else
  1107. builder.append(chars);
  1108. break;
  1109. }
  1110. case 'a':
  1111. builder.append('\a');
  1112. break;
  1113. case 'b':
  1114. builder.append('\b');
  1115. break;
  1116. case 'e':
  1117. builder.append('\x1b');
  1118. break;
  1119. case 'f':
  1120. builder.append('\f');
  1121. break;
  1122. case 'r':
  1123. builder.append('\r');
  1124. break;
  1125. case 'n':
  1126. builder.append('\n');
  1127. break;
  1128. case 't':
  1129. builder.append('\t');
  1130. break;
  1131. }
  1132. continue;
  1133. }
  1134. if (peek() == '$') {
  1135. auto string_literal = create<AST::StringLiteral>(builder.to_string()); // String Literal
  1136. auto read_concat = [&](auto&& node) {
  1137. auto inner = create<AST::StringPartCompose>(
  1138. move(string_literal),
  1139. move(node)); // Compose String Node
  1140. if (auto string = parse_string_inner(condition)) {
  1141. return create<AST::StringPartCompose>(move(inner), string.release_nonnull()); // Compose Composition Composition
  1142. }
  1143. return inner;
  1144. };
  1145. if (auto variable = parse_variable())
  1146. return read_concat(variable.release_nonnull());
  1147. if (auto immediate = parse_immediate_expression())
  1148. return read_concat(immediate.release_nonnull());
  1149. if (auto evaluate = parse_evaluate())
  1150. return read_concat(evaluate.release_nonnull());
  1151. }
  1152. builder.append(consume());
  1153. }
  1154. return create<AST::StringLiteral>(builder.to_string()); // String Literal
  1155. }
  1156. RefPtr<AST::Node> Parser::parse_variable()
  1157. {
  1158. auto rule_start = push_start();
  1159. auto ref = parse_variable_ref();
  1160. if (!ref)
  1161. return nullptr;
  1162. auto variable = static_ptr_cast<AST::VariableNode>(ref);
  1163. if (auto slice = parse_slice())
  1164. variable->set_slice(slice.release_nonnull());
  1165. return variable;
  1166. }
  1167. RefPtr<AST::Node> Parser::parse_variable_ref()
  1168. {
  1169. auto rule_start = push_start();
  1170. if (at_end())
  1171. return nullptr;
  1172. if (peek() != '$')
  1173. return nullptr;
  1174. consume();
  1175. switch (peek()) {
  1176. case '$':
  1177. case '?':
  1178. case '*':
  1179. case '#':
  1180. return create<AST::SpecialVariable>(consume()); // Variable Special
  1181. default:
  1182. break;
  1183. }
  1184. auto name = consume_while(is_word_character);
  1185. if (name.length() == 0) {
  1186. restore_to(rule_start->offset, rule_start->line);
  1187. return nullptr;
  1188. }
  1189. return create<AST::SimpleVariable>(move(name)); // Variable Simple
  1190. }
  1191. RefPtr<AST::Slice> Parser::parse_slice()
  1192. {
  1193. auto rule_start = push_start();
  1194. if (!next_is("["))
  1195. return nullptr;
  1196. consume(); // [
  1197. ScopedValueRollback chars_change { m_extra_chars_not_allowed_in_barewords };
  1198. m_extra_chars_not_allowed_in_barewords.append(']');
  1199. auto spec = parse_brace_expansion_spec();
  1200. RefPtr<AST::SyntaxError> error;
  1201. if (peek() != ']')
  1202. error = create<AST::SyntaxError>("Expected a close bracket ']' to end a variable slice");
  1203. else
  1204. consume();
  1205. if (!spec) {
  1206. if (error)
  1207. spec = move(error);
  1208. else
  1209. spec = create<AST::SyntaxError>("Expected either a range, or a comma-seprated list of selectors");
  1210. }
  1211. auto node = create<AST::Slice>(spec.release_nonnull());
  1212. if (error)
  1213. node->set_is_syntax_error(*error);
  1214. return node;
  1215. }
  1216. RefPtr<AST::Node> Parser::parse_evaluate()
  1217. {
  1218. auto rule_start = push_start();
  1219. if (at_end())
  1220. return nullptr;
  1221. if (peek() != '$')
  1222. return nullptr;
  1223. consume();
  1224. if (peek() == '(') {
  1225. consume();
  1226. auto inner = parse_pipe_sequence();
  1227. if (!inner)
  1228. inner = create<AST::SyntaxError>("Unexpected EOF in list", true);
  1229. if (!expect(')'))
  1230. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating close paren", true));
  1231. return create<AST::Execute>(inner.release_nonnull(), true);
  1232. }
  1233. auto inner = parse_expression();
  1234. if (!inner) {
  1235. inner = create<AST::SyntaxError>("Expected a command", true);
  1236. } else {
  1237. if (inner->is_list()) {
  1238. auto execute_inner = create<AST::Execute>(inner.release_nonnull(), true);
  1239. inner = move(execute_inner);
  1240. } else {
  1241. auto dyn_inner = create<AST::DynamicEvaluate>(inner.release_nonnull());
  1242. inner = move(dyn_inner);
  1243. }
  1244. }
  1245. return inner;
  1246. }
  1247. RefPtr<AST::Node> Parser::parse_immediate_expression()
  1248. {
  1249. auto rule_start = push_start();
  1250. if (at_end())
  1251. return nullptr;
  1252. if (peek() != '$')
  1253. return nullptr;
  1254. consume();
  1255. if (peek() != '{') {
  1256. restore_to(*rule_start);
  1257. return nullptr;
  1258. }
  1259. consume();
  1260. consume_while(is_whitespace);
  1261. auto function_name_start_offset = current_position();
  1262. auto function_name = consume_while(is_word_character);
  1263. auto function_name_end_offset = current_position();
  1264. AST::Position function_position {
  1265. function_name_start_offset.offset,
  1266. function_name_end_offset.offset,
  1267. function_name_start_offset.line,
  1268. function_name_end_offset.line,
  1269. };
  1270. consume_while(is_whitespace);
  1271. NonnullRefPtrVector<AST::Node> arguments;
  1272. do {
  1273. auto expr = parse_expression();
  1274. if (!expr)
  1275. break;
  1276. arguments.append(expr.release_nonnull());
  1277. } while (!consume_while(is_whitespace).is_empty());
  1278. auto ending_brace_start_offset = current_position();
  1279. if (peek() == '}')
  1280. consume();
  1281. auto ending_brace_end_offset = current_position();
  1282. auto ending_brace_position = ending_brace_start_offset.offset == ending_brace_end_offset.offset
  1283. ? Optional<AST::Position> {}
  1284. : Optional<AST::Position> {
  1285. AST::Position {
  1286. ending_brace_start_offset.offset,
  1287. ending_brace_end_offset.offset,
  1288. ending_brace_start_offset.line,
  1289. ending_brace_end_offset.line,
  1290. }
  1291. };
  1292. auto node = create<AST::ImmediateExpression>(
  1293. AST::NameWithPosition { function_name, move(function_position) },
  1294. move(arguments),
  1295. ending_brace_position);
  1296. if (!ending_brace_position.has_value())
  1297. node->set_is_syntax_error(create<AST::SyntaxError>("Expected a closing brace '}' to end an immediate expression", true));
  1298. else if (node->function_name().is_empty())
  1299. node->set_is_syntax_error(create<AST::SyntaxError>("Expected an immediate function name"));
  1300. return node;
  1301. }
  1302. RefPtr<AST::Node> Parser::parse_history_designator()
  1303. {
  1304. auto rule_start = push_start();
  1305. VERIFY(peek() == '!');
  1306. consume();
  1307. // Event selector
  1308. AST::HistorySelector selector;
  1309. RefPtr<AST::SyntaxError> syntax_error;
  1310. selector.event.kind = AST::HistorySelector::EventKind::StartingStringLookup;
  1311. selector.event.text_position = { m_offset, m_offset, m_line, m_line };
  1312. selector.word_selector_range = {
  1313. AST::HistorySelector::WordSelector {
  1314. AST::HistorySelector::WordSelectorKind::Index,
  1315. 0,
  1316. { m_offset, m_offset, m_line, m_line },
  1317. nullptr },
  1318. AST::HistorySelector::WordSelector {
  1319. AST::HistorySelector::WordSelectorKind::Last,
  1320. 0,
  1321. { m_offset, m_offset, m_line, m_line },
  1322. nullptr }
  1323. };
  1324. bool is_word_selector = false;
  1325. switch (peek()) {
  1326. case ':':
  1327. consume();
  1328. [[fallthrough]];
  1329. case '^':
  1330. case '$':
  1331. case '*':
  1332. is_word_selector = true;
  1333. break;
  1334. case '!':
  1335. consume();
  1336. selector.event.kind = AST::HistorySelector::EventKind::IndexFromEnd;
  1337. selector.event.index = 0;
  1338. selector.event.text = "!";
  1339. break;
  1340. case '?':
  1341. consume();
  1342. selector.event.kind = AST::HistorySelector::EventKind::ContainingStringLookup;
  1343. [[fallthrough]];
  1344. default: {
  1345. TemporaryChange chars_change { m_extra_chars_not_allowed_in_barewords, { ':', '^', '$', '*' } };
  1346. auto bareword = parse_bareword();
  1347. if (!bareword || !bareword->is_bareword()) {
  1348. restore_to(*rule_start);
  1349. return nullptr;
  1350. }
  1351. selector.event.text = static_ptr_cast<AST::BarewordLiteral>(bareword)->text();
  1352. selector.event.text_position = bareword->position();
  1353. auto it = selector.event.text.begin();
  1354. bool is_negative = false;
  1355. if (*it == '-') {
  1356. ++it;
  1357. is_negative = true;
  1358. }
  1359. if (it != selector.event.text.end() && all_of(it, selector.event.text.end(), is_digit)) {
  1360. if (is_negative)
  1361. selector.event.kind = AST::HistorySelector::EventKind::IndexFromEnd;
  1362. else
  1363. selector.event.kind = AST::HistorySelector::EventKind::IndexFromStart;
  1364. auto number = abs(selector.event.text.to_int().value_or(0));
  1365. if (number != 0)
  1366. selector.event.index = number - 1;
  1367. else
  1368. syntax_error = create<AST::SyntaxError>("History entry index value invalid or out of range");
  1369. }
  1370. if (":^$*"sv.contains(peek())) {
  1371. is_word_selector = true;
  1372. if (peek() == ':')
  1373. consume();
  1374. }
  1375. }
  1376. }
  1377. if (!is_word_selector) {
  1378. auto node = create<AST::HistoryEvent>(move(selector));
  1379. if (syntax_error)
  1380. node->set_is_syntax_error(*syntax_error);
  1381. return node;
  1382. }
  1383. // Word selectors
  1384. auto parse_word_selector = [&]() -> Optional<AST::HistorySelector::WordSelector> {
  1385. auto c = peek();
  1386. AST::HistorySelector::WordSelectorKind word_selector_kind;
  1387. ssize_t offset = -1;
  1388. if (isdigit(c)) {
  1389. auto num = consume_while(is_digit);
  1390. auto value = num.to_uint();
  1391. if (!value.has_value())
  1392. return {};
  1393. word_selector_kind = AST::HistorySelector::WordSelectorKind::Index;
  1394. offset = value.value();
  1395. } else if (c == '^') {
  1396. consume();
  1397. word_selector_kind = AST::HistorySelector::WordSelectorKind::Index;
  1398. offset = 1;
  1399. } else if (c == '$') {
  1400. consume();
  1401. word_selector_kind = AST::HistorySelector::WordSelectorKind::Last;
  1402. offset = 0;
  1403. }
  1404. if (offset == -1)
  1405. return {};
  1406. return AST::HistorySelector::WordSelector {
  1407. word_selector_kind,
  1408. static_cast<size_t>(offset),
  1409. { m_rule_start_offsets.last(), m_offset, m_rule_start_lines.last(), line() },
  1410. syntax_error
  1411. };
  1412. };
  1413. auto make_word_selector = [&](AST::HistorySelector::WordSelectorKind word_selector_kind, size_t offset) {
  1414. return AST::HistorySelector::WordSelector {
  1415. word_selector_kind,
  1416. offset,
  1417. { m_rule_start_offsets.last(), m_offset, m_rule_start_lines.last(), line() },
  1418. syntax_error
  1419. };
  1420. };
  1421. auto first_char = peek();
  1422. if (!(is_digit(first_char) || "^$-*"sv.contains(first_char))) {
  1423. if (!syntax_error)
  1424. syntax_error = create<AST::SyntaxError>("Expected a word selector after ':' in a history event designator", true);
  1425. } else if (first_char == '*') {
  1426. consume();
  1427. selector.word_selector_range.start = make_word_selector(AST::HistorySelector::WordSelectorKind::Index, 1);
  1428. selector.word_selector_range.end = make_word_selector(AST::HistorySelector::WordSelectorKind::Last, 0);
  1429. } else if (first_char == '-') {
  1430. consume();
  1431. selector.word_selector_range.start = make_word_selector(AST::HistorySelector::WordSelectorKind::Index, 0);
  1432. auto last_selector = parse_word_selector();
  1433. if (!last_selector.has_value())
  1434. selector.word_selector_range.end = make_word_selector(AST::HistorySelector::WordSelectorKind::Last, 1);
  1435. else
  1436. selector.word_selector_range.end = last_selector.release_value();
  1437. } else {
  1438. auto first_selector = parse_word_selector();
  1439. // peek() should be a digit, ^, or $ here, so this should always have value.
  1440. VERIFY(first_selector.has_value());
  1441. selector.word_selector_range.start = first_selector.release_value();
  1442. if (peek() == '-') {
  1443. consume();
  1444. auto last_selector = parse_word_selector();
  1445. if (last_selector.has_value()) {
  1446. selector.word_selector_range.end = last_selector.release_value();
  1447. } else {
  1448. selector.word_selector_range.end = make_word_selector(AST::HistorySelector::WordSelectorKind::Last, 1);
  1449. }
  1450. } else if (peek() == '*') {
  1451. consume();
  1452. selector.word_selector_range.end = make_word_selector(AST::HistorySelector::WordSelectorKind::Last, 0);
  1453. } else {
  1454. selector.word_selector_range.end.clear();
  1455. }
  1456. }
  1457. auto node = create<AST::HistoryEvent>(move(selector));
  1458. if (syntax_error)
  1459. node->set_is_syntax_error(*syntax_error);
  1460. return node;
  1461. }
  1462. RefPtr<AST::Node> Parser::parse_comment()
  1463. {
  1464. if (at_end())
  1465. return nullptr;
  1466. if (peek() != '#')
  1467. return nullptr;
  1468. consume();
  1469. auto text = consume_while(is_not('\n'));
  1470. return create<AST::Comment>(move(text)); // Comment
  1471. }
  1472. RefPtr<AST::Node> Parser::parse_bareword()
  1473. {
  1474. auto rule_start = push_start();
  1475. StringBuilder builder;
  1476. auto is_acceptable_bareword_character = [&](char c) {
  1477. return strchr("\\\"'*$&#|(){} ?;<>\n", c) == nullptr
  1478. && !m_extra_chars_not_allowed_in_barewords.contains_slow(c);
  1479. };
  1480. while (!at_end()) {
  1481. char ch = peek();
  1482. if (ch == '\\') {
  1483. consume();
  1484. if (!at_end()) {
  1485. ch = consume();
  1486. if (is_acceptable_bareword_character(ch))
  1487. builder.append('\\');
  1488. }
  1489. builder.append(ch);
  1490. continue;
  1491. }
  1492. if (m_is_in_brace_expansion_spec && next_is("..")) {
  1493. // Don't eat '..' in a brace expansion spec.
  1494. break;
  1495. }
  1496. if (is_acceptable_bareword_character(ch)) {
  1497. builder.append(consume());
  1498. continue;
  1499. }
  1500. break;
  1501. }
  1502. if (builder.is_empty())
  1503. return nullptr;
  1504. auto current_end = m_offset;
  1505. auto current_line = line();
  1506. auto string = builder.to_string();
  1507. if (string.starts_with('~')) {
  1508. String username;
  1509. RefPtr<AST::Node> tilde, text;
  1510. auto first_slash_index = string.find('/');
  1511. if (first_slash_index.has_value()) {
  1512. username = string.substring_view(1, first_slash_index.value() - 1);
  1513. string = string.substring_view(first_slash_index.value(), string.length() - first_slash_index.value());
  1514. } else {
  1515. username = string.substring_view(1, string.length() - 1);
  1516. string = "";
  1517. }
  1518. // Synthesize a Tilde Node with the correct positioning information.
  1519. {
  1520. restore_to(rule_start->offset, rule_start->line);
  1521. auto ch = consume();
  1522. VERIFY(ch == '~');
  1523. auto username_length = username.length();
  1524. tilde = create<AST::Tilde>(move(username));
  1525. // Consume the username (if any)
  1526. for (size_t i = 0; i < username_length; ++i)
  1527. consume();
  1528. }
  1529. if (string.is_empty())
  1530. return tilde;
  1531. // Synthesize a BarewordLiteral Node with the correct positioning information.
  1532. {
  1533. auto text_start = push_start();
  1534. restore_to(current_end, current_line);
  1535. text = create<AST::BarewordLiteral>(move(string));
  1536. }
  1537. return create<AST::Juxtaposition>(tilde.release_nonnull(), text.release_nonnull()); // Juxtaposition Variable Bareword
  1538. }
  1539. if (string.starts_with("\\~")) {
  1540. // Un-escape the tilde, but only at the start (where it would be an expansion)
  1541. string = string.substring(1, string.length() - 1);
  1542. }
  1543. return create<AST::BarewordLiteral>(move(string)); // Bareword Literal
  1544. }
  1545. RefPtr<AST::Node> Parser::parse_glob()
  1546. {
  1547. auto rule_start = push_start();
  1548. auto bareword_part = parse_bareword();
  1549. if (at_end())
  1550. return bareword_part;
  1551. char ch = peek();
  1552. if (ch == '*' || ch == '?') {
  1553. auto saved_offset = save_offset();
  1554. consume();
  1555. StringBuilder textbuilder;
  1556. if (bareword_part) {
  1557. StringView text;
  1558. if (bareword_part->is_bareword()) {
  1559. auto bareword = static_cast<AST::BarewordLiteral*>(bareword_part.ptr());
  1560. text = bareword->text();
  1561. } else {
  1562. // FIXME: Allow composition of tilde+bareword with globs: '~/foo/bar/baz*'
  1563. restore_to(saved_offset.offset, saved_offset.line);
  1564. bareword_part->set_is_syntax_error(*create<AST::SyntaxError>(String::formatted("Unexpected {} inside a glob", bareword_part->class_name())));
  1565. return bareword_part;
  1566. }
  1567. textbuilder.append(text);
  1568. }
  1569. textbuilder.append(ch);
  1570. auto glob_after = parse_glob();
  1571. if (glob_after) {
  1572. if (glob_after->is_glob()) {
  1573. auto glob = static_cast<AST::Glob*>(glob_after.ptr());
  1574. textbuilder.append(glob->text());
  1575. } else if (glob_after->is_bareword()) {
  1576. auto bareword = static_cast<AST::BarewordLiteral*>(glob_after.ptr());
  1577. textbuilder.append(bareword->text());
  1578. } else if (glob_after->is_tilde()) {
  1579. auto bareword = static_cast<AST::Tilde*>(glob_after.ptr());
  1580. textbuilder.append("~");
  1581. textbuilder.append(bareword->text());
  1582. } else {
  1583. return create<AST::SyntaxError>(String::formatted("Invalid node '{}' in glob position, escape shell special characters", glob_after->class_name()));
  1584. }
  1585. }
  1586. return create<AST::Glob>(textbuilder.to_string()); // Glob
  1587. }
  1588. return bareword_part;
  1589. }
  1590. RefPtr<AST::Node> Parser::parse_brace_expansion()
  1591. {
  1592. auto rule_start = push_start();
  1593. if (!expect('{'))
  1594. return nullptr;
  1595. if (auto spec = parse_brace_expansion_spec()) {
  1596. if (!expect('}'))
  1597. spec->set_is_syntax_error(create<AST::SyntaxError>("Expected a close brace '}' to end a brace expansion", true));
  1598. return spec;
  1599. }
  1600. restore_to(*rule_start);
  1601. return nullptr;
  1602. }
  1603. RefPtr<AST::Node> Parser::parse_brace_expansion_spec()
  1604. {
  1605. TemporaryChange is_in_brace_expansion { m_is_in_brace_expansion_spec, true };
  1606. ScopedValueRollback chars_change { m_extra_chars_not_allowed_in_barewords };
  1607. m_extra_chars_not_allowed_in_barewords.append(',');
  1608. auto rule_start = push_start();
  1609. NonnullRefPtrVector<AST::Node> subexpressions;
  1610. if (next_is(",")) {
  1611. // Note that we don't consume the ',' here.
  1612. subexpressions.append(create<AST::StringLiteral>(""));
  1613. } else {
  1614. auto start_expr = parse_expression();
  1615. if (start_expr) {
  1616. if (expect("..")) {
  1617. if (auto end_expr = parse_expression()) {
  1618. if (end_expr->position().start_offset != start_expr->position().end_offset + 2)
  1619. end_expr->set_is_syntax_error(create<AST::SyntaxError>("Expected no whitespace between '..' and the following expression in brace expansion"));
  1620. return create<AST::Range>(start_expr.release_nonnull(), end_expr.release_nonnull());
  1621. }
  1622. return create<AST::Range>(start_expr.release_nonnull(), create<AST::SyntaxError>("Expected an expression to end range brace expansion with", true));
  1623. }
  1624. }
  1625. if (start_expr)
  1626. subexpressions.append(start_expr.release_nonnull());
  1627. }
  1628. while (expect(',')) {
  1629. auto expr = parse_expression();
  1630. if (expr) {
  1631. subexpressions.append(expr.release_nonnull());
  1632. } else {
  1633. subexpressions.append(create<AST::StringLiteral>(""));
  1634. }
  1635. }
  1636. if (subexpressions.is_empty())
  1637. return nullptr;
  1638. return create<AST::BraceExpansion>(move(subexpressions));
  1639. }
  1640. RefPtr<AST::Node> Parser::parse_heredoc_initiation_record()
  1641. {
  1642. if (!next_is("<<"))
  1643. return nullptr;
  1644. auto rule_start = push_start();
  1645. // '<' '<'
  1646. consume();
  1647. consume();
  1648. HeredocInitiationRecord record;
  1649. record.end = "<error>";
  1650. RefPtr<AST::SyntaxError> syntax_error_node;
  1651. // '-' | '~'
  1652. switch (peek()) {
  1653. case '-':
  1654. record.deindent = false;
  1655. consume();
  1656. break;
  1657. case '~':
  1658. record.deindent = true;
  1659. consume();
  1660. break;
  1661. default:
  1662. restore_to(*rule_start);
  1663. return nullptr;
  1664. }
  1665. // StringLiteral | bareword
  1666. if (auto bareword = parse_bareword()) {
  1667. if (!bareword->is_bareword()) {
  1668. syntax_error_node = create<AST::SyntaxError>(String::formatted("Expected a bareword or a quoted string, not {}", bareword->class_name()));
  1669. } else {
  1670. if (bareword->is_syntax_error())
  1671. syntax_error_node = bareword->syntax_error_node();
  1672. else
  1673. record.end = static_cast<AST::BarewordLiteral*>(bareword.ptr())->text();
  1674. }
  1675. record.interpolate = true;
  1676. } else if (peek() == '\'') {
  1677. consume();
  1678. auto text = consume_while(is_not('\''));
  1679. bool is_error = false;
  1680. if (!expect('\''))
  1681. is_error = true;
  1682. if (is_error)
  1683. syntax_error_node = create<AST::SyntaxError>("Expected a terminating single quote", true);
  1684. record.end = text;
  1685. record.interpolate = false;
  1686. } else {
  1687. syntax_error_node = create<AST::SyntaxError>("Expected a bareword or a single-quoted string literal for heredoc end key", true);
  1688. }
  1689. auto node = create<AST::Heredoc>(record.end, record.interpolate, record.deindent);
  1690. if (syntax_error_node)
  1691. node->set_is_syntax_error(*syntax_error_node);
  1692. else
  1693. node->set_is_syntax_error(*create<AST::SyntaxError>(String::formatted("Expected heredoc contents for heredoc with end key '{}'", node->end()), true));
  1694. record.node = node;
  1695. m_heredoc_initiations.append(move(record));
  1696. return node;
  1697. }
  1698. bool Parser::parse_heredoc_entries()
  1699. {
  1700. auto heredocs = move(m_heredoc_initiations);
  1701. m_heredoc_initiations.clear();
  1702. // Try to parse heredoc entries, as reverse recorded in the initiation records
  1703. for (auto& record : heredocs) {
  1704. auto rule_start = push_start();
  1705. if (m_rule_start_offsets.size() > max_allowed_nested_rule_depth) {
  1706. record.node->set_is_syntax_error(*create<AST::SyntaxError>(String::formatted("Expression nested too deep (max allowed is {})", max_allowed_nested_rule_depth)));
  1707. continue;
  1708. }
  1709. bool found_key = false;
  1710. if (!record.interpolate) {
  1711. // Since no interpolation is allowed, just read lines until we hit the key
  1712. Optional<Offset> last_line_offset;
  1713. for (;;) {
  1714. if (at_end())
  1715. break;
  1716. if (peek() == '\n')
  1717. consume();
  1718. last_line_offset = current_position();
  1719. auto line = consume_while(is_not('\n'));
  1720. if (peek() == '\n')
  1721. consume();
  1722. if (line.trim_whitespace() == record.end) {
  1723. found_key = true;
  1724. break;
  1725. }
  1726. }
  1727. if (!last_line_offset.has_value())
  1728. last_line_offset = current_position();
  1729. // Now just wrap it in a StringLiteral and set it as the node's contents
  1730. auto node = create<AST::StringLiteral>(m_input.substring_view(rule_start->offset, last_line_offset->offset - rule_start->offset));
  1731. if (!found_key)
  1732. node->set_is_syntax_error(*create<AST::SyntaxError>(String::formatted("Expected to find the heredoc key '{}', but found Eof", record.end), true));
  1733. record.node->set_contents(move(node));
  1734. } else {
  1735. // Interpolation is allowed, so we're going to read doublequoted string innards
  1736. // until we find a line that contains the key
  1737. auto end_condition = move(m_end_condition);
  1738. found_key = false;
  1739. set_end_condition(make<Function<bool()>>([this, end = record.end, &found_key] {
  1740. if (found_key)
  1741. return true;
  1742. auto offset = current_position();
  1743. auto cond = move(m_end_condition);
  1744. ScopeGuard guard {
  1745. [&] {
  1746. m_end_condition = move(cond);
  1747. }
  1748. };
  1749. if (peek() == '\n') {
  1750. consume();
  1751. auto line = consume_while(is_not('\n'));
  1752. if (peek() == '\n')
  1753. consume();
  1754. if (line.trim_whitespace() == end) {
  1755. restore_to(offset.offset, offset.line);
  1756. found_key = true;
  1757. return true;
  1758. }
  1759. }
  1760. restore_to(offset.offset, offset.line);
  1761. return false;
  1762. }));
  1763. auto expr = parse_string_inner(StringEndCondition::Heredoc);
  1764. set_end_condition(move(end_condition));
  1765. if (found_key) {
  1766. auto offset = current_position();
  1767. if (peek() == '\n')
  1768. consume();
  1769. auto line = consume_while(is_not('\n'));
  1770. if (peek() == '\n')
  1771. consume();
  1772. if (line.trim_whitespace() != record.end)
  1773. restore_to(offset.offset, offset.line);
  1774. }
  1775. if (!expr && found_key) {
  1776. expr = create<AST::StringLiteral>("");
  1777. } else if (!expr) {
  1778. expr = create<AST::SyntaxError>(String::formatted("Expected to find a valid string inside a heredoc (with end key '{}')", record.end), true);
  1779. } else if (!found_key) {
  1780. expr->set_is_syntax_error(*create<AST::SyntaxError>(String::formatted("Expected to find the heredoc key '{}'", record.end), true));
  1781. }
  1782. record.node->set_contents(create<AST::DoubleQuotedString>(move(expr)));
  1783. }
  1784. }
  1785. return true;
  1786. }
  1787. StringView Parser::consume_while(Function<bool(char)> condition)
  1788. {
  1789. if (at_end())
  1790. return {};
  1791. auto start_offset = m_offset;
  1792. while (!at_end() && condition(peek()))
  1793. consume();
  1794. return m_input.substring_view(start_offset, m_offset - start_offset);
  1795. }
  1796. bool Parser::next_is(StringView next)
  1797. {
  1798. auto start = current_position();
  1799. auto res = expect(next);
  1800. restore_to(start.offset, start.line);
  1801. return res;
  1802. }
  1803. }