Parser.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  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() }, forward<Args>(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;"sv : "\n;"sv));
  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 "sv);
  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;"sv));
  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;"sv));
  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>("", AST::StringLiteral::EnclosureType::None);
  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 "sv));
  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("||"sv))
  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("&&"sv))
  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"sv)) {
  477. {
  478. auto break_end = push_start();
  479. if (consume_while(is_any_of(" \t\n;"sv)).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"sv)) {
  488. {
  489. auto continue_end = push_start();
  490. if (consume_while(is_any_of(" \t\n;"sv)).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"sv))
  504. return nullptr;
  505. if (consume_while(is_any_of(" \t\n"sv)).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"sv)) {
  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"sv)) {
  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"sv));
  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"sv))
  583. return nullptr;
  584. if (consume_while(is_any_of(" \t\n"sv)).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"sv))
  614. return nullptr;
  615. if (consume_while(is_any_of(" \t\n"sv)).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"sv));
  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"sv));
  654. Optional<AST::Position> else_position;
  655. {
  656. auto else_start = push_start();
  657. if (expect("else"sv))
  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"sv));
  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"sv))
  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"sv));
  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"sv)) {
  713. as_position = AST::Position { as_start, m_offset, as_line, line() };
  714. if (consume_while(is_any_of(" \t\n"sv)).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"sv));
  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"sv));
  739. Vector<AST::MatchEntry> entries;
  740. for (;;) {
  741. auto entry = parse_match_entry();
  742. consume_while(is_any_of(" \t\n"sv));
  743. if (entry.options.visit([](auto& x) { return x.is_empty(); }))
  744. break;
  745. entries.append(move(entry));
  746. }
  747. consume_while(is_any_of(" \t\n"sv));
  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<Regex<ECMA262>> regexps;
  762. Vector<AST::Position> pipe_positions;
  763. Optional<Vector<String>> match_names;
  764. Optional<AST::Position> match_as_position;
  765. enum {
  766. Regex,
  767. Glob,
  768. } pattern_kind;
  769. consume_while(is_any_of(" \t\n"sv));
  770. auto regex_pattern = parse_regex_pattern();
  771. if (regex_pattern.has_value()) {
  772. if (auto error = regex_pattern.value().parser_result.error; error != regex::Error::NoError)
  773. return { NonnullRefPtrVector<AST::Node> {}, {}, {}, {}, create<AST::SyntaxError>(regex::get_error_string(error), false) };
  774. pattern_kind = Regex;
  775. regexps.append(regex_pattern.release_value());
  776. } else {
  777. auto glob_pattern = parse_match_pattern();
  778. if (!glob_pattern)
  779. return { NonnullRefPtrVector<AST::Node> {}, {}, {}, {}, create<AST::SyntaxError>("Expected a pattern in 'match' body", true) };
  780. pattern_kind = Glob;
  781. patterns.append(glob_pattern.release_nonnull());
  782. }
  783. consume_while(is_any_of(" \t\n"sv));
  784. auto previous_pipe_start_position = m_offset;
  785. auto previous_pipe_start_line = line();
  786. RefPtr<AST::SyntaxError> error;
  787. while (expect('|')) {
  788. pipe_positions.append({ previous_pipe_start_position, m_offset, previous_pipe_start_line, line() });
  789. consume_while(is_any_of(" \t\n"sv));
  790. switch (pattern_kind) {
  791. case Regex: {
  792. auto pattern = parse_regex_pattern();
  793. if (!pattern.has_value()) {
  794. error = create<AST::SyntaxError>("Expected a regex pattern to follow '|' in 'match' body", true);
  795. break;
  796. }
  797. regexps.append(pattern.release_value());
  798. break;
  799. }
  800. case Glob: {
  801. auto pattern = parse_match_pattern();
  802. if (!pattern) {
  803. error = create<AST::SyntaxError>("Expected a pattern to follow '|' in 'match' body", true);
  804. break;
  805. }
  806. patterns.append(pattern.release_nonnull());
  807. break;
  808. }
  809. }
  810. consume_while(is_any_of(" \t\n"sv));
  811. previous_pipe_start_line = line();
  812. previous_pipe_start_position = m_offset;
  813. }
  814. consume_while(is_any_of(" \t\n"sv));
  815. auto as_start_position = m_offset;
  816. auto as_start_line = line();
  817. if (pattern_kind == Glob && expect("as"sv)) {
  818. match_as_position = AST::Position { as_start_position, m_offset, as_start_line, line() };
  819. consume_while(is_any_of(" \t\n"sv));
  820. if (!expect('(')) {
  821. if (!error)
  822. error = create<AST::SyntaxError>("Expected an explicit list of identifiers after a pattern 'as'");
  823. } else {
  824. match_names = Vector<String>();
  825. for (;;) {
  826. consume_while(is_whitespace);
  827. auto name = consume_while(is_word_character);
  828. if (name.is_empty())
  829. break;
  830. match_names.value().append(move(name));
  831. }
  832. if (!expect(')')) {
  833. if (!error)
  834. error = create<AST::SyntaxError>("Expected a close paren ')' to end the identifier list of pattern 'as'", true);
  835. }
  836. }
  837. consume_while(is_any_of(" \t\n"sv));
  838. }
  839. if (pattern_kind == Regex) {
  840. Vector<String> names;
  841. for (auto& regex : regexps) {
  842. if (names.is_empty()) {
  843. for (auto& name : regex.parser_result.capture_groups)
  844. names.append(name);
  845. } else {
  846. size_t index = 0;
  847. for (auto& name : regex.parser_result.capture_groups) {
  848. if (names.size() <= index) {
  849. names.append(name);
  850. continue;
  851. }
  852. if (names[index] != name) {
  853. if (!error)
  854. error = create<AST::SyntaxError>("Alternative regex patterns must have the same capture groups", false);
  855. break;
  856. }
  857. }
  858. }
  859. }
  860. match_names = move(names);
  861. }
  862. if (!expect('{')) {
  863. if (!error)
  864. error = create<AST::SyntaxError>("Expected an open brace '{' to start a match entry body", true);
  865. }
  866. auto body = parse_toplevel();
  867. if (!expect('}')) {
  868. if (!error)
  869. error = create<AST::SyntaxError>("Expected a close brace '}' to end a match entry body", true);
  870. }
  871. if (body && error)
  872. body->set_is_syntax_error(*error);
  873. else if (error)
  874. body = error;
  875. if (pattern_kind == Glob)
  876. return { move(patterns), move(match_names), move(match_as_position), move(pipe_positions), move(body) };
  877. return { move(regexps), move(match_names), move(match_as_position), move(pipe_positions), move(body) };
  878. }
  879. RefPtr<AST::Node> Parser::parse_match_pattern()
  880. {
  881. return parse_expression();
  882. }
  883. Optional<Regex<ECMA262>> Parser::parse_regex_pattern()
  884. {
  885. auto rule_start = push_start();
  886. auto start = m_offset;
  887. if (!expect("(?:"sv) && !expect("(?<"sv))
  888. return {};
  889. size_t open_parens = 1;
  890. while (open_parens > 0) {
  891. if (at_end())
  892. break;
  893. if (next_is("("sv))
  894. ++open_parens;
  895. else if (next_is(")"sv))
  896. --open_parens;
  897. consume();
  898. }
  899. if (open_parens != 0) {
  900. restore_to(*rule_start);
  901. return {};
  902. }
  903. auto end = m_offset;
  904. auto pattern = m_input.substring_view(start, end - start);
  905. return Regex<ECMA262>(pattern);
  906. }
  907. RefPtr<AST::Node> Parser::parse_redirection()
  908. {
  909. auto rule_start = push_start();
  910. // heredoc entry
  911. if (next_is("<<-"sv) || next_is("<<~"sv))
  912. return nullptr;
  913. auto pipe_fd = 0;
  914. auto number = consume_while(is_digit);
  915. if (number.is_empty()) {
  916. pipe_fd = -1;
  917. } else {
  918. auto fd = number.to_int();
  919. pipe_fd = fd.value_or(-1);
  920. }
  921. switch (peek()) {
  922. case '>': {
  923. consume();
  924. if (peek() == '>') {
  925. consume();
  926. consume_while(is_whitespace);
  927. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  928. auto path = parse_expression();
  929. if (!path) {
  930. if (!at_end()) {
  931. // Eat a character and hope the problem goes away
  932. consume();
  933. }
  934. path = create<AST::SyntaxError>("Expected a path after redirection", true);
  935. }
  936. return create<AST::WriteAppendRedirection>(pipe_fd, path.release_nonnull()); // Redirection WriteAppend
  937. }
  938. if (peek() == '&') {
  939. consume();
  940. // FIXME: 'fd>&-' Syntax not the best. needs discussion.
  941. if (peek() == '-') {
  942. consume();
  943. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  944. return create<AST::CloseFdRedirection>(pipe_fd); // Redirection CloseFd
  945. }
  946. int dest_pipe_fd = 0;
  947. auto number = consume_while(is_digit);
  948. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  949. if (number.is_empty()) {
  950. dest_pipe_fd = -1;
  951. } else {
  952. auto fd = number.to_int();
  953. dest_pipe_fd = fd.value_or(-1);
  954. }
  955. auto redir = create<AST::Fd2FdRedirection>(pipe_fd, dest_pipe_fd); // Redirection Fd2Fd
  956. if (dest_pipe_fd == -1)
  957. redir->set_is_syntax_error(*create<AST::SyntaxError>("Expected a file descriptor"));
  958. return redir;
  959. }
  960. consume_while(is_whitespace);
  961. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDOUT_FILENO;
  962. auto path = parse_expression();
  963. if (!path) {
  964. if (!at_end()) {
  965. // Eat a character and hope the problem goes away
  966. consume();
  967. }
  968. path = create<AST::SyntaxError>("Expected a path after redirection", true);
  969. }
  970. return create<AST::WriteRedirection>(pipe_fd, path.release_nonnull()); // Redirection Write
  971. }
  972. case '<': {
  973. consume();
  974. enum {
  975. Read,
  976. ReadWrite,
  977. } mode { Read };
  978. if (peek() == '>') {
  979. mode = ReadWrite;
  980. consume();
  981. }
  982. consume_while(is_whitespace);
  983. pipe_fd = pipe_fd >= 0 ? pipe_fd : STDIN_FILENO;
  984. auto path = parse_expression();
  985. if (!path) {
  986. if (!at_end()) {
  987. // Eat a character and hope the problem goes away
  988. consume();
  989. }
  990. path = create<AST::SyntaxError>("Expected a path after redirection", true);
  991. }
  992. if (mode == Read)
  993. return create<AST::ReadRedirection>(pipe_fd, path.release_nonnull()); // Redirection Read
  994. return create<AST::ReadWriteRedirection>(pipe_fd, path.release_nonnull()); // Redirection ReadWrite
  995. }
  996. default:
  997. restore_to(*rule_start);
  998. return nullptr;
  999. }
  1000. }
  1001. RefPtr<AST::Node> Parser::parse_list_expression()
  1002. {
  1003. consume_while(is_whitespace);
  1004. auto rule_start = push_start();
  1005. Vector<NonnullRefPtr<AST::Node>> nodes;
  1006. do {
  1007. auto expr = parse_expression();
  1008. if (!expr)
  1009. break;
  1010. nodes.append(expr.release_nonnull());
  1011. } while (!consume_while(is_whitespace).is_empty());
  1012. if (nodes.is_empty())
  1013. return nullptr;
  1014. return create<AST::ListConcatenate>(move(nodes)); // Concatenate List
  1015. }
  1016. RefPtr<AST::Node> Parser::parse_expression()
  1017. {
  1018. auto rule_start = push_start();
  1019. if (m_rule_start_offsets.size() > max_allowed_nested_rule_depth)
  1020. return create<AST::SyntaxError>(String::formatted("Expression nested too deep (max allowed is {})", max_allowed_nested_rule_depth));
  1021. auto starting_char = peek();
  1022. auto read_concat = [&](auto&& expr) -> NonnullRefPtr<AST::Node> {
  1023. if (is_whitespace(peek()))
  1024. return move(expr);
  1025. if (auto next_expr = parse_expression())
  1026. return create<AST::Juxtaposition>(move(expr), next_expr.release_nonnull());
  1027. return move(expr);
  1028. };
  1029. // Heredocs are expressions, so allow them
  1030. if (!(next_is("<<-"sv) || next_is("<<~"sv))) {
  1031. if (strchr("&|)} ;<>\n", starting_char) != nullptr)
  1032. return nullptr;
  1033. }
  1034. if (m_extra_chars_not_allowed_in_barewords.contains_slow(starting_char))
  1035. return nullptr;
  1036. if (m_is_in_brace_expansion_spec && next_is(".."sv))
  1037. return nullptr;
  1038. if (isdigit(starting_char)) {
  1039. ScopedValueRollback offset_rollback { m_offset };
  1040. auto redir = parse_redirection();
  1041. if (redir)
  1042. return nullptr;
  1043. }
  1044. if (starting_char == '$') {
  1045. if (auto variable = parse_variable())
  1046. return read_concat(variable.release_nonnull());
  1047. if (auto immediate = parse_immediate_expression())
  1048. return read_concat(immediate.release_nonnull());
  1049. auto inline_exec = parse_evaluate();
  1050. if (inline_exec && !inline_exec->is_syntax_error())
  1051. return read_concat(inline_exec.release_nonnull());
  1052. return inline_exec;
  1053. }
  1054. if (starting_char == '#')
  1055. return parse_comment();
  1056. if (starting_char == '(') {
  1057. consume();
  1058. auto list = parse_list_expression();
  1059. if (!expect(')')) {
  1060. restore_to(*rule_start);
  1061. return nullptr;
  1062. }
  1063. return read_concat(create<AST::CastToList>(move(list))); // Cast To List
  1064. }
  1065. if (starting_char == '!' && m_in_interactive_mode) {
  1066. if (auto designator = parse_history_designator())
  1067. return designator;
  1068. }
  1069. if (auto composite = parse_string_composite())
  1070. return read_concat(composite.release_nonnull());
  1071. return nullptr;
  1072. }
  1073. RefPtr<AST::Node> Parser::parse_string_composite()
  1074. {
  1075. auto rule_start = push_start();
  1076. if (auto string = parse_string()) {
  1077. if (auto next_part = parse_string_composite())
  1078. return create<AST::Juxtaposition>(string.release_nonnull(), next_part.release_nonnull()); // Concatenate String StringComposite
  1079. return string;
  1080. }
  1081. if (auto variable = parse_variable()) {
  1082. if (auto next_part = parse_string_composite())
  1083. return create<AST::Juxtaposition>(variable.release_nonnull(), next_part.release_nonnull()); // Concatenate Variable StringComposite
  1084. return variable;
  1085. }
  1086. if (auto glob = parse_glob()) {
  1087. if (auto next_part = parse_string_composite())
  1088. return create<AST::Juxtaposition>(glob.release_nonnull(), next_part.release_nonnull()); // Concatenate Glob StringComposite
  1089. return glob;
  1090. }
  1091. if (auto expansion = parse_brace_expansion()) {
  1092. if (auto next_part = parse_string_composite())
  1093. return create<AST::Juxtaposition>(expansion.release_nonnull(), next_part.release_nonnull()); // Concatenate BraceExpansion StringComposite
  1094. return expansion;
  1095. }
  1096. if (auto bareword = parse_bareword()) {
  1097. if (auto next_part = parse_string_composite())
  1098. return create<AST::Juxtaposition>(bareword.release_nonnull(), next_part.release_nonnull()); // Concatenate Bareword StringComposite
  1099. return bareword;
  1100. }
  1101. if (auto inline_command = parse_evaluate()) {
  1102. if (auto next_part = parse_string_composite())
  1103. return create<AST::Juxtaposition>(inline_command.release_nonnull(), next_part.release_nonnull()); // Concatenate Execute StringComposite
  1104. return inline_command;
  1105. }
  1106. if (auto heredoc = parse_heredoc_initiation_record()) {
  1107. if (auto next_part = parse_string_composite())
  1108. return create<AST::Juxtaposition>(heredoc.release_nonnull(), next_part.release_nonnull()); // Concatenate Heredoc StringComposite
  1109. return heredoc;
  1110. }
  1111. return nullptr;
  1112. }
  1113. RefPtr<AST::Node> Parser::parse_string()
  1114. {
  1115. auto rule_start = push_start();
  1116. if (at_end())
  1117. return nullptr;
  1118. if (peek() == '"') {
  1119. consume();
  1120. auto inner = parse_string_inner(StringEndCondition::DoubleQuote);
  1121. if (!inner)
  1122. inner = create<AST::SyntaxError>("Unexpected EOF in string", true);
  1123. if (!expect('"')) {
  1124. inner = create<AST::DoubleQuotedString>(move(inner));
  1125. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating double quote", true));
  1126. return inner;
  1127. }
  1128. return create<AST::DoubleQuotedString>(move(inner)); // Double Quoted String
  1129. }
  1130. if (peek() == '\'') {
  1131. consume();
  1132. auto text = consume_while(is_not('\''));
  1133. bool is_error = false;
  1134. if (!expect('\''))
  1135. is_error = true;
  1136. auto result = create<AST::StringLiteral>(move(text), AST::StringLiteral::EnclosureType::SingleQuotes); // String Literal
  1137. if (is_error)
  1138. result->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating single quote", true));
  1139. return result;
  1140. }
  1141. return nullptr;
  1142. }
  1143. RefPtr<AST::Node> Parser::parse_string_inner(StringEndCondition condition)
  1144. {
  1145. auto rule_start = push_start();
  1146. if (at_end())
  1147. return nullptr;
  1148. StringBuilder builder;
  1149. while (!at_end()) {
  1150. if (condition == StringEndCondition::DoubleQuote && peek() == '"') {
  1151. break;
  1152. }
  1153. if (peek() == '\\') {
  1154. consume();
  1155. if (at_end()) {
  1156. break;
  1157. }
  1158. auto ch = consume();
  1159. switch (ch) {
  1160. case '\\':
  1161. default:
  1162. builder.append(ch);
  1163. break;
  1164. case 'x': {
  1165. if (m_input.length() <= m_offset + 2)
  1166. break;
  1167. auto first_nibble = tolower(consume());
  1168. auto second_nibble = tolower(consume());
  1169. if (!isxdigit(first_nibble) || !isxdigit(second_nibble)) {
  1170. builder.append(first_nibble);
  1171. builder.append(second_nibble);
  1172. break;
  1173. }
  1174. builder.append(to_byte(first_nibble, second_nibble));
  1175. break;
  1176. }
  1177. case 'u': {
  1178. if (m_input.length() <= m_offset + 8)
  1179. break;
  1180. size_t counter = 8;
  1181. auto chars = consume_while([&](auto) { return counter-- > 0; });
  1182. if (auto number = AK::StringUtils::convert_to_uint_from_hex(chars); number.has_value())
  1183. builder.append(Utf32View { &number.value(), 1 });
  1184. else
  1185. builder.append(chars);
  1186. break;
  1187. }
  1188. case 'a':
  1189. builder.append('\a');
  1190. break;
  1191. case 'b':
  1192. builder.append('\b');
  1193. break;
  1194. case 'e':
  1195. builder.append('\x1b');
  1196. break;
  1197. case 'f':
  1198. builder.append('\f');
  1199. break;
  1200. case 'r':
  1201. builder.append('\r');
  1202. break;
  1203. case 'n':
  1204. builder.append('\n');
  1205. break;
  1206. case 't':
  1207. builder.append('\t');
  1208. break;
  1209. }
  1210. continue;
  1211. }
  1212. if (peek() == '$') {
  1213. auto string_literal = create<AST::StringLiteral>(builder.to_string(), AST::StringLiteral::EnclosureType::DoubleQuotes); // String Literal
  1214. auto read_concat = [&](auto&& node) {
  1215. auto inner = create<AST::StringPartCompose>(
  1216. move(string_literal),
  1217. move(node)); // Compose String Node
  1218. if (auto string = parse_string_inner(condition)) {
  1219. return create<AST::StringPartCompose>(move(inner), string.release_nonnull()); // Compose Composition Composition
  1220. }
  1221. return inner;
  1222. };
  1223. if (auto variable = parse_variable())
  1224. return read_concat(variable.release_nonnull());
  1225. if (auto immediate = parse_immediate_expression())
  1226. return read_concat(immediate.release_nonnull());
  1227. if (auto evaluate = parse_evaluate())
  1228. return read_concat(evaluate.release_nonnull());
  1229. }
  1230. builder.append(consume());
  1231. }
  1232. return create<AST::StringLiteral>(builder.to_string(), AST::StringLiteral::EnclosureType::DoubleQuotes); // String Literal
  1233. }
  1234. RefPtr<AST::Node> Parser::parse_variable()
  1235. {
  1236. auto rule_start = push_start();
  1237. auto ref = parse_variable_ref();
  1238. if (!ref)
  1239. return nullptr;
  1240. auto variable = static_ptr_cast<AST::VariableNode>(ref);
  1241. if (auto slice = parse_slice())
  1242. variable->set_slice(slice.release_nonnull());
  1243. return variable;
  1244. }
  1245. RefPtr<AST::Node> Parser::parse_variable_ref()
  1246. {
  1247. auto rule_start = push_start();
  1248. if (at_end())
  1249. return nullptr;
  1250. if (peek() != '$')
  1251. return nullptr;
  1252. consume();
  1253. switch (peek()) {
  1254. case '$':
  1255. case '?':
  1256. case '*':
  1257. case '#':
  1258. return create<AST::SpecialVariable>(consume()); // Variable Special
  1259. default:
  1260. break;
  1261. }
  1262. auto name = consume_while(is_word_character);
  1263. if (name.length() == 0) {
  1264. restore_to(rule_start->offset, rule_start->line);
  1265. return nullptr;
  1266. }
  1267. return create<AST::SimpleVariable>(move(name)); // Variable Simple
  1268. }
  1269. RefPtr<AST::Slice> Parser::parse_slice()
  1270. {
  1271. auto rule_start = push_start();
  1272. if (!next_is("["sv))
  1273. return nullptr;
  1274. consume(); // [
  1275. ScopedValueRollback chars_change { m_extra_chars_not_allowed_in_barewords };
  1276. m_extra_chars_not_allowed_in_barewords.append(']');
  1277. auto spec = parse_brace_expansion_spec();
  1278. RefPtr<AST::SyntaxError> error;
  1279. if (peek() != ']')
  1280. error = create<AST::SyntaxError>("Expected a close bracket ']' to end a variable slice");
  1281. else
  1282. consume();
  1283. if (!spec) {
  1284. if (error)
  1285. spec = move(error);
  1286. else
  1287. spec = create<AST::SyntaxError>("Expected either a range, or a comma-seprated list of selectors");
  1288. }
  1289. auto node = create<AST::Slice>(spec.release_nonnull());
  1290. if (error)
  1291. node->set_is_syntax_error(*error);
  1292. return node;
  1293. }
  1294. RefPtr<AST::Node> Parser::parse_evaluate()
  1295. {
  1296. auto rule_start = push_start();
  1297. if (at_end())
  1298. return nullptr;
  1299. if (peek() != '$')
  1300. return nullptr;
  1301. consume();
  1302. if (peek() == '(') {
  1303. consume();
  1304. auto inner = parse_pipe_sequence();
  1305. if (!inner)
  1306. inner = create<AST::SyntaxError>("Unexpected EOF in list", true);
  1307. if (!expect(')'))
  1308. inner->set_is_syntax_error(*create<AST::SyntaxError>("Expected a terminating close paren", true));
  1309. return create<AST::Execute>(inner.release_nonnull(), true);
  1310. }
  1311. auto inner = parse_expression();
  1312. if (!inner) {
  1313. inner = create<AST::SyntaxError>("Expected a command", true);
  1314. } else {
  1315. if (inner->is_list()) {
  1316. auto execute_inner = create<AST::Execute>(inner.release_nonnull(), true);
  1317. inner = move(execute_inner);
  1318. } else {
  1319. auto dyn_inner = create<AST::DynamicEvaluate>(inner.release_nonnull());
  1320. inner = move(dyn_inner);
  1321. }
  1322. }
  1323. return inner;
  1324. }
  1325. RefPtr<AST::Node> Parser::parse_immediate_expression()
  1326. {
  1327. auto rule_start = push_start();
  1328. if (at_end())
  1329. return nullptr;
  1330. if (peek() != '$')
  1331. return nullptr;
  1332. consume();
  1333. if (peek() != '{') {
  1334. restore_to(*rule_start);
  1335. return nullptr;
  1336. }
  1337. consume();
  1338. consume_while(is_whitespace);
  1339. auto function_name_start_offset = current_position();
  1340. auto function_name = consume_while(is_word_character);
  1341. auto function_name_end_offset = current_position();
  1342. AST::Position function_position {
  1343. function_name_start_offset.offset,
  1344. function_name_end_offset.offset,
  1345. function_name_start_offset.line,
  1346. function_name_end_offset.line,
  1347. };
  1348. consume_while(is_whitespace);
  1349. NonnullRefPtrVector<AST::Node> arguments;
  1350. do {
  1351. auto expr = parse_expression();
  1352. if (!expr)
  1353. break;
  1354. arguments.append(expr.release_nonnull());
  1355. } while (!consume_while(is_whitespace).is_empty());
  1356. auto ending_brace_start_offset = current_position();
  1357. if (peek() == '}')
  1358. consume();
  1359. auto ending_brace_end_offset = current_position();
  1360. auto ending_brace_position = ending_brace_start_offset.offset == ending_brace_end_offset.offset
  1361. ? Optional<AST::Position> {}
  1362. : Optional<AST::Position> {
  1363. AST::Position {
  1364. ending_brace_start_offset.offset,
  1365. ending_brace_end_offset.offset,
  1366. ending_brace_start_offset.line,
  1367. ending_brace_end_offset.line,
  1368. }
  1369. };
  1370. auto node = create<AST::ImmediateExpression>(
  1371. AST::NameWithPosition { function_name, move(function_position) },
  1372. move(arguments),
  1373. ending_brace_position);
  1374. if (!ending_brace_position.has_value())
  1375. node->set_is_syntax_error(create<AST::SyntaxError>("Expected a closing brace '}' to end an immediate expression", true));
  1376. else if (node->function_name().is_empty())
  1377. node->set_is_syntax_error(create<AST::SyntaxError>("Expected an immediate function name"));
  1378. return node;
  1379. }
  1380. RefPtr<AST::Node> Parser::parse_history_designator()
  1381. {
  1382. auto rule_start = push_start();
  1383. VERIFY(peek() == '!');
  1384. consume();
  1385. // Event selector
  1386. AST::HistorySelector selector;
  1387. RefPtr<AST::SyntaxError> syntax_error;
  1388. selector.event.kind = AST::HistorySelector::EventKind::StartingStringLookup;
  1389. selector.event.text_position = { m_offset, m_offset, m_line, m_line };
  1390. selector.word_selector_range = {
  1391. AST::HistorySelector::WordSelector {
  1392. AST::HistorySelector::WordSelectorKind::Index,
  1393. 0,
  1394. { m_offset, m_offset, m_line, m_line },
  1395. nullptr },
  1396. AST::HistorySelector::WordSelector {
  1397. AST::HistorySelector::WordSelectorKind::Last,
  1398. 0,
  1399. { m_offset, m_offset, m_line, m_line },
  1400. nullptr }
  1401. };
  1402. bool is_word_selector = false;
  1403. switch (peek()) {
  1404. case ':':
  1405. consume();
  1406. [[fallthrough]];
  1407. case '^':
  1408. case '$':
  1409. case '*':
  1410. is_word_selector = true;
  1411. break;
  1412. case '!':
  1413. consume();
  1414. selector.event.kind = AST::HistorySelector::EventKind::IndexFromEnd;
  1415. selector.event.index = 0;
  1416. selector.event.text = "!";
  1417. break;
  1418. case '?':
  1419. consume();
  1420. selector.event.kind = AST::HistorySelector::EventKind::ContainingStringLookup;
  1421. [[fallthrough]];
  1422. default: {
  1423. TemporaryChange chars_change { m_extra_chars_not_allowed_in_barewords, { ':', '^', '$', '*' } };
  1424. auto bareword = parse_bareword();
  1425. if (!bareword || !bareword->is_bareword()) {
  1426. restore_to(*rule_start);
  1427. return nullptr;
  1428. }
  1429. selector.event.text = static_ptr_cast<AST::BarewordLiteral>(bareword)->text();
  1430. selector.event.text_position = bareword->position();
  1431. auto it = selector.event.text.begin();
  1432. bool is_negative = false;
  1433. if (*it == '-') {
  1434. ++it;
  1435. is_negative = true;
  1436. }
  1437. if (it != selector.event.text.end() && all_of(it, selector.event.text.end(), is_digit)) {
  1438. if (is_negative)
  1439. selector.event.kind = AST::HistorySelector::EventKind::IndexFromEnd;
  1440. else
  1441. selector.event.kind = AST::HistorySelector::EventKind::IndexFromStart;
  1442. auto number = abs(selector.event.text.to_int().value_or(0));
  1443. if (number != 0)
  1444. selector.event.index = number - 1;
  1445. else
  1446. syntax_error = create<AST::SyntaxError>("History entry index value invalid or out of range");
  1447. }
  1448. if (":^$*"sv.contains(peek())) {
  1449. is_word_selector = true;
  1450. if (peek() == ':')
  1451. consume();
  1452. }
  1453. }
  1454. }
  1455. if (!is_word_selector) {
  1456. auto node = create<AST::HistoryEvent>(move(selector));
  1457. if (syntax_error)
  1458. node->set_is_syntax_error(*syntax_error);
  1459. return node;
  1460. }
  1461. // Word selectors
  1462. auto parse_word_selector = [&]() -> Optional<AST::HistorySelector::WordSelector> {
  1463. auto c = peek();
  1464. AST::HistorySelector::WordSelectorKind word_selector_kind;
  1465. ssize_t offset = -1;
  1466. if (isdigit(c)) {
  1467. auto num = consume_while(is_digit);
  1468. auto value = num.to_uint();
  1469. if (!value.has_value())
  1470. return {};
  1471. word_selector_kind = AST::HistorySelector::WordSelectorKind::Index;
  1472. offset = value.value();
  1473. } else if (c == '^') {
  1474. consume();
  1475. word_selector_kind = AST::HistorySelector::WordSelectorKind::Index;
  1476. offset = 1;
  1477. } else if (c == '$') {
  1478. consume();
  1479. word_selector_kind = AST::HistorySelector::WordSelectorKind::Last;
  1480. offset = 0;
  1481. }
  1482. if (offset == -1)
  1483. return {};
  1484. return AST::HistorySelector::WordSelector {
  1485. word_selector_kind,
  1486. static_cast<size_t>(offset),
  1487. { m_rule_start_offsets.last(), m_offset, m_rule_start_lines.last(), line() },
  1488. syntax_error
  1489. };
  1490. };
  1491. auto make_word_selector = [&](AST::HistorySelector::WordSelectorKind word_selector_kind, size_t offset) {
  1492. return AST::HistorySelector::WordSelector {
  1493. word_selector_kind,
  1494. offset,
  1495. { m_rule_start_offsets.last(), m_offset, m_rule_start_lines.last(), line() },
  1496. syntax_error
  1497. };
  1498. };
  1499. auto first_char = peek();
  1500. if (!(is_digit(first_char) || "^$-*"sv.contains(first_char))) {
  1501. if (!syntax_error)
  1502. syntax_error = create<AST::SyntaxError>("Expected a word selector after ':' in a history event designator", true);
  1503. } else if (first_char == '*') {
  1504. consume();
  1505. selector.word_selector_range.start = make_word_selector(AST::HistorySelector::WordSelectorKind::Index, 1);
  1506. selector.word_selector_range.end = make_word_selector(AST::HistorySelector::WordSelectorKind::Last, 0);
  1507. } else if (first_char == '-') {
  1508. consume();
  1509. selector.word_selector_range.start = make_word_selector(AST::HistorySelector::WordSelectorKind::Index, 0);
  1510. auto last_selector = parse_word_selector();
  1511. if (!last_selector.has_value())
  1512. selector.word_selector_range.end = make_word_selector(AST::HistorySelector::WordSelectorKind::Last, 1);
  1513. else
  1514. selector.word_selector_range.end = last_selector.release_value();
  1515. } else {
  1516. auto first_selector = parse_word_selector();
  1517. // peek() should be a digit, ^, or $ here, so this should always have value.
  1518. VERIFY(first_selector.has_value());
  1519. selector.word_selector_range.start = first_selector.release_value();
  1520. if (peek() == '-') {
  1521. consume();
  1522. auto last_selector = parse_word_selector();
  1523. if (last_selector.has_value()) {
  1524. selector.word_selector_range.end = last_selector.release_value();
  1525. } else {
  1526. selector.word_selector_range.end = make_word_selector(AST::HistorySelector::WordSelectorKind::Last, 1);
  1527. }
  1528. } else if (peek() == '*') {
  1529. consume();
  1530. selector.word_selector_range.end = make_word_selector(AST::HistorySelector::WordSelectorKind::Last, 0);
  1531. } else {
  1532. selector.word_selector_range.end.clear();
  1533. }
  1534. }
  1535. auto node = create<AST::HistoryEvent>(move(selector));
  1536. if (syntax_error)
  1537. node->set_is_syntax_error(*syntax_error);
  1538. return node;
  1539. }
  1540. RefPtr<AST::Node> Parser::parse_comment()
  1541. {
  1542. if (at_end())
  1543. return nullptr;
  1544. if (peek() != '#')
  1545. return nullptr;
  1546. consume();
  1547. auto text = consume_while(is_not('\n'));
  1548. return create<AST::Comment>(move(text)); // Comment
  1549. }
  1550. RefPtr<AST::Node> Parser::parse_bareword()
  1551. {
  1552. auto rule_start = push_start();
  1553. StringBuilder builder;
  1554. auto is_acceptable_bareword_character = [&](char c) {
  1555. return strchr("\\\"'*$&#|(){} ?;<>\n", c) == nullptr
  1556. && !m_extra_chars_not_allowed_in_barewords.contains_slow(c);
  1557. };
  1558. while (!at_end()) {
  1559. char ch = peek();
  1560. if (ch == '\\') {
  1561. consume();
  1562. if (!at_end()) {
  1563. ch = consume();
  1564. if (is_acceptable_bareword_character(ch))
  1565. builder.append('\\');
  1566. }
  1567. builder.append(ch);
  1568. continue;
  1569. }
  1570. if (m_is_in_brace_expansion_spec && next_is(".."sv)) {
  1571. // Don't eat '..' in a brace expansion spec.
  1572. break;
  1573. }
  1574. if (is_acceptable_bareword_character(ch)) {
  1575. builder.append(consume());
  1576. continue;
  1577. }
  1578. break;
  1579. }
  1580. if (builder.is_empty())
  1581. return nullptr;
  1582. auto current_end = m_offset;
  1583. auto current_line = line();
  1584. auto string = builder.to_string();
  1585. if (string.starts_with('~')) {
  1586. String username;
  1587. RefPtr<AST::Node> tilde, text;
  1588. auto first_slash_index = string.find('/');
  1589. if (first_slash_index.has_value()) {
  1590. username = string.substring_view(1, first_slash_index.value() - 1);
  1591. string = string.substring_view(first_slash_index.value(), string.length() - first_slash_index.value());
  1592. } else {
  1593. username = string.substring_view(1, string.length() - 1);
  1594. string = "";
  1595. }
  1596. // Synthesize a Tilde Node with the correct positioning information.
  1597. {
  1598. restore_to(rule_start->offset, rule_start->line);
  1599. auto ch = consume();
  1600. VERIFY(ch == '~');
  1601. auto username_length = username.length();
  1602. tilde = create<AST::Tilde>(move(username));
  1603. // Consume the username (if any)
  1604. for (size_t i = 0; i < username_length; ++i)
  1605. consume();
  1606. }
  1607. if (string.is_empty())
  1608. return tilde;
  1609. // Synthesize a BarewordLiteral Node with the correct positioning information.
  1610. {
  1611. auto text_start = push_start();
  1612. restore_to(current_end, current_line);
  1613. text = create<AST::BarewordLiteral>(move(string));
  1614. }
  1615. return create<AST::Juxtaposition>(tilde.release_nonnull(), text.release_nonnull()); // Juxtaposition Variable Bareword
  1616. }
  1617. if (string.starts_with("\\~"sv)) {
  1618. // Un-escape the tilde, but only at the start (where it would be an expansion)
  1619. string = string.substring(1, string.length() - 1);
  1620. }
  1621. return create<AST::BarewordLiteral>(move(string)); // Bareword Literal
  1622. }
  1623. RefPtr<AST::Node> Parser::parse_glob()
  1624. {
  1625. auto rule_start = push_start();
  1626. auto bareword_part = parse_bareword();
  1627. if (at_end())
  1628. return bareword_part;
  1629. char ch = peek();
  1630. if (ch == '*' || ch == '?') {
  1631. auto saved_offset = save_offset();
  1632. consume();
  1633. StringBuilder textbuilder;
  1634. if (bareword_part) {
  1635. StringView text;
  1636. if (bareword_part->is_bareword()) {
  1637. auto bareword = static_cast<AST::BarewordLiteral*>(bareword_part.ptr());
  1638. text = bareword->text();
  1639. } else {
  1640. // FIXME: Allow composition of tilde+bareword with globs: '~/foo/bar/baz*'
  1641. restore_to(saved_offset.offset, saved_offset.line);
  1642. bareword_part->set_is_syntax_error(*create<AST::SyntaxError>(String::formatted("Unexpected {} inside a glob", bareword_part->class_name())));
  1643. return bareword_part;
  1644. }
  1645. textbuilder.append(text);
  1646. }
  1647. textbuilder.append(ch);
  1648. auto glob_after = parse_glob();
  1649. if (glob_after) {
  1650. if (glob_after->is_glob()) {
  1651. auto glob = static_cast<AST::Glob*>(glob_after.ptr());
  1652. textbuilder.append(glob->text());
  1653. } else if (glob_after->is_bareword()) {
  1654. auto bareword = static_cast<AST::BarewordLiteral*>(glob_after.ptr());
  1655. textbuilder.append(bareword->text());
  1656. } else if (glob_after->is_tilde()) {
  1657. auto bareword = static_cast<AST::Tilde*>(glob_after.ptr());
  1658. textbuilder.append('~');
  1659. textbuilder.append(bareword->text());
  1660. } else {
  1661. return create<AST::SyntaxError>(String::formatted("Invalid node '{}' in glob position, escape shell special characters", glob_after->class_name()));
  1662. }
  1663. }
  1664. return create<AST::Glob>(textbuilder.to_string()); // Glob
  1665. }
  1666. return bareword_part;
  1667. }
  1668. RefPtr<AST::Node> Parser::parse_brace_expansion()
  1669. {
  1670. auto rule_start = push_start();
  1671. if (!expect('{'))
  1672. return nullptr;
  1673. if (auto spec = parse_brace_expansion_spec()) {
  1674. if (!expect('}'))
  1675. spec->set_is_syntax_error(create<AST::SyntaxError>("Expected a close brace '}' to end a brace expansion", true));
  1676. return spec;
  1677. }
  1678. restore_to(*rule_start);
  1679. return nullptr;
  1680. }
  1681. RefPtr<AST::Node> Parser::parse_brace_expansion_spec()
  1682. {
  1683. TemporaryChange is_in_brace_expansion { m_is_in_brace_expansion_spec, true };
  1684. ScopedValueRollback chars_change { m_extra_chars_not_allowed_in_barewords };
  1685. m_extra_chars_not_allowed_in_barewords.append(',');
  1686. auto rule_start = push_start();
  1687. NonnullRefPtrVector<AST::Node> subexpressions;
  1688. if (next_is(","sv)) {
  1689. // Note that we don't consume the ',' here.
  1690. subexpressions.append(create<AST::StringLiteral>("", AST::StringLiteral::EnclosureType::None));
  1691. } else {
  1692. auto start_expr = parse_expression();
  1693. if (start_expr) {
  1694. if (expect(".."sv)) {
  1695. if (auto end_expr = parse_expression()) {
  1696. if (end_expr->position().start_offset != start_expr->position().end_offset + 2)
  1697. end_expr->set_is_syntax_error(create<AST::SyntaxError>("Expected no whitespace between '..' and the following expression in brace expansion"));
  1698. return create<AST::Range>(start_expr.release_nonnull(), end_expr.release_nonnull());
  1699. }
  1700. return create<AST::Range>(start_expr.release_nonnull(), create<AST::SyntaxError>("Expected an expression to end range brace expansion with", true));
  1701. }
  1702. }
  1703. if (start_expr)
  1704. subexpressions.append(start_expr.release_nonnull());
  1705. }
  1706. while (expect(',')) {
  1707. auto expr = parse_expression();
  1708. if (expr) {
  1709. subexpressions.append(expr.release_nonnull());
  1710. } else {
  1711. subexpressions.append(create<AST::StringLiteral>("", AST::StringLiteral::EnclosureType::None));
  1712. }
  1713. }
  1714. if (subexpressions.is_empty())
  1715. return nullptr;
  1716. return create<AST::BraceExpansion>(move(subexpressions));
  1717. }
  1718. RefPtr<AST::Node> Parser::parse_heredoc_initiation_record()
  1719. {
  1720. if (!next_is("<<"sv))
  1721. return nullptr;
  1722. auto rule_start = push_start();
  1723. // '<' '<'
  1724. consume();
  1725. consume();
  1726. HeredocInitiationRecord record;
  1727. record.end = "<error>";
  1728. RefPtr<AST::SyntaxError> syntax_error_node;
  1729. // '-' | '~'
  1730. switch (peek()) {
  1731. case '-':
  1732. record.deindent = false;
  1733. consume();
  1734. break;
  1735. case '~':
  1736. record.deindent = true;
  1737. consume();
  1738. break;
  1739. default:
  1740. restore_to(*rule_start);
  1741. return nullptr;
  1742. }
  1743. // StringLiteral | bareword
  1744. if (auto bareword = parse_bareword()) {
  1745. if (!bareword->is_bareword()) {
  1746. syntax_error_node = create<AST::SyntaxError>(String::formatted("Expected a bareword or a quoted string, not {}", bareword->class_name()));
  1747. } else {
  1748. if (bareword->is_syntax_error())
  1749. syntax_error_node = bareword->syntax_error_node();
  1750. else
  1751. record.end = static_cast<AST::BarewordLiteral*>(bareword.ptr())->text();
  1752. }
  1753. record.interpolate = true;
  1754. } else if (peek() == '\'') {
  1755. consume();
  1756. auto text = consume_while(is_not('\''));
  1757. bool is_error = false;
  1758. if (!expect('\''))
  1759. is_error = true;
  1760. if (is_error)
  1761. syntax_error_node = create<AST::SyntaxError>("Expected a terminating single quote", true);
  1762. record.end = text;
  1763. record.interpolate = false;
  1764. } else {
  1765. syntax_error_node = create<AST::SyntaxError>("Expected a bareword or a single-quoted string literal for heredoc end key", true);
  1766. }
  1767. auto node = create<AST::Heredoc>(record.end, record.interpolate, record.deindent);
  1768. if (syntax_error_node)
  1769. node->set_is_syntax_error(*syntax_error_node);
  1770. else
  1771. node->set_is_syntax_error(*create<AST::SyntaxError>(String::formatted("Expected heredoc contents for heredoc with end key '{}'", node->end()), true));
  1772. record.node = node;
  1773. m_heredoc_initiations.append(move(record));
  1774. return node;
  1775. }
  1776. bool Parser::parse_heredoc_entries()
  1777. {
  1778. auto heredocs = move(m_heredoc_initiations);
  1779. m_heredoc_initiations.clear();
  1780. // Try to parse heredoc entries, as reverse recorded in the initiation records
  1781. for (auto& record : heredocs) {
  1782. auto rule_start = push_start();
  1783. if (m_rule_start_offsets.size() > max_allowed_nested_rule_depth) {
  1784. record.node->set_is_syntax_error(*create<AST::SyntaxError>(String::formatted("Expression nested too deep (max allowed is {})", max_allowed_nested_rule_depth)));
  1785. continue;
  1786. }
  1787. bool found_key = false;
  1788. if (!record.interpolate) {
  1789. // Since no interpolation is allowed, just read lines until we hit the key
  1790. Optional<Offset> last_line_offset;
  1791. for (;;) {
  1792. if (at_end())
  1793. break;
  1794. if (peek() == '\n')
  1795. consume();
  1796. last_line_offset = current_position();
  1797. auto line = consume_while(is_not('\n'));
  1798. if (peek() == '\n')
  1799. consume();
  1800. if (line.trim_whitespace() == record.end) {
  1801. found_key = true;
  1802. break;
  1803. }
  1804. }
  1805. if (!last_line_offset.has_value())
  1806. last_line_offset = current_position();
  1807. // Now just wrap it in a StringLiteral and set it as the node's contents
  1808. auto node = create<AST::StringLiteral>(m_input.substring_view(rule_start->offset, last_line_offset->offset - rule_start->offset), AST::StringLiteral::EnclosureType::None);
  1809. if (!found_key)
  1810. node->set_is_syntax_error(*create<AST::SyntaxError>(String::formatted("Expected to find the heredoc key '{}', but found Eof", record.end), true));
  1811. record.node->set_contents(move(node));
  1812. } else {
  1813. // Interpolation is allowed, so we're going to read doublequoted string innards
  1814. // until we find a line that contains the key
  1815. auto end_condition = move(m_end_condition);
  1816. found_key = false;
  1817. set_end_condition(make<Function<bool()>>([this, end = record.end, &found_key] {
  1818. if (found_key)
  1819. return true;
  1820. auto offset = current_position();
  1821. auto cond = move(m_end_condition);
  1822. ScopeGuard guard {
  1823. [&] {
  1824. m_end_condition = move(cond);
  1825. }
  1826. };
  1827. if (peek() == '\n') {
  1828. consume();
  1829. auto line = consume_while(is_not('\n'));
  1830. if (peek() == '\n')
  1831. consume();
  1832. if (line.trim_whitespace() == end) {
  1833. restore_to(offset.offset, offset.line);
  1834. found_key = true;
  1835. return true;
  1836. }
  1837. }
  1838. restore_to(offset.offset, offset.line);
  1839. return false;
  1840. }));
  1841. auto expr = parse_string_inner(StringEndCondition::Heredoc);
  1842. set_end_condition(move(end_condition));
  1843. if (found_key) {
  1844. auto offset = current_position();
  1845. if (peek() == '\n')
  1846. consume();
  1847. auto line = consume_while(is_not('\n'));
  1848. if (peek() == '\n')
  1849. consume();
  1850. if (line.trim_whitespace() != record.end)
  1851. restore_to(offset.offset, offset.line);
  1852. }
  1853. if (!expr && found_key) {
  1854. expr = create<AST::StringLiteral>("", AST::StringLiteral::EnclosureType::None);
  1855. } else if (!expr) {
  1856. expr = create<AST::SyntaxError>(String::formatted("Expected to find a valid string inside a heredoc (with end key '{}')", record.end), true);
  1857. } else if (!found_key) {
  1858. expr->set_is_syntax_error(*create<AST::SyntaxError>(String::formatted("Expected to find the heredoc key '{}'", record.end), true));
  1859. }
  1860. record.node->set_contents(create<AST::DoubleQuotedString>(move(expr)));
  1861. }
  1862. }
  1863. return true;
  1864. }
  1865. StringView Parser::consume_while(Function<bool(char)> condition)
  1866. {
  1867. if (at_end())
  1868. return {};
  1869. auto start_offset = m_offset;
  1870. while (!at_end() && condition(peek()))
  1871. consume();
  1872. return m_input.substring_view(start_offset, m_offset - start_offset);
  1873. }
  1874. bool Parser::next_is(StringView next)
  1875. {
  1876. auto start = current_position();
  1877. auto res = expect(next);
  1878. restore_to(start.offset, start.line);
  1879. return res;
  1880. }
  1881. }