AST.cpp 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "AST.h"
  27. #include "Shell.h"
  28. #include <AK/MemoryStream.h>
  29. #include <AK/ScopeGuard.h>
  30. #include <AK/String.h>
  31. #include <AK/StringBuilder.h>
  32. #include <AK/URL.h>
  33. #include <LibCore/EventLoop.h>
  34. #include <LibCore/File.h>
  35. #include <signal.h>
  36. //#define EXECUTE_DEBUG
  37. void AK::Formatter<Shell::AST::Command>::format(FormatBuilder& builder, const Shell::AST::Command& value)
  38. {
  39. if (m_sign_mode != FormatBuilder::SignMode::Default)
  40. ASSERT_NOT_REACHED();
  41. if (m_alternative_form)
  42. ASSERT_NOT_REACHED();
  43. if (m_zero_pad)
  44. ASSERT_NOT_REACHED();
  45. if (m_mode != Mode::Default && m_mode != Mode::String)
  46. ASSERT_NOT_REACHED();
  47. if (m_width.has_value())
  48. ASSERT_NOT_REACHED();
  49. if (m_precision.has_value())
  50. ASSERT_NOT_REACHED();
  51. if (value.argv.is_empty()) {
  52. builder.put_literal("(ShellInternal)");
  53. } else {
  54. bool first = true;
  55. for (auto& arg : value.argv) {
  56. if (!first)
  57. builder.put_literal(" ");
  58. first = false;
  59. builder.put_literal(arg);
  60. }
  61. }
  62. for (auto& redir : value.redirections) {
  63. builder.put_padding(' ', 1);
  64. if (redir.is_path_redirection()) {
  65. auto path_redir = (const Shell::AST::PathRedirection*)&redir;
  66. builder.put_i64(path_redir->fd);
  67. switch (path_redir->direction) {
  68. case Shell::AST::PathRedirection::Read:
  69. builder.put_literal("<");
  70. break;
  71. case Shell::AST::PathRedirection::Write:
  72. builder.put_literal(">");
  73. break;
  74. case Shell::AST::PathRedirection::WriteAppend:
  75. builder.put_literal(">>");
  76. break;
  77. case Shell::AST::PathRedirection::ReadWrite:
  78. builder.put_literal("<>");
  79. break;
  80. }
  81. builder.put_literal(path_redir->path);
  82. } else if (redir.is_fd_redirection()) {
  83. auto* fdredir = (const Shell::AST::FdRedirection*)&redir;
  84. builder.put_i64(fdredir->new_fd);
  85. builder.put_literal(">");
  86. builder.put_i64(fdredir->old_fd);
  87. } else if (redir.is_close_redirection()) {
  88. auto close_redir = (const Shell::AST::CloseRedirection*)&redir;
  89. builder.put_i64(close_redir->fd);
  90. builder.put_literal(">&-");
  91. } else {
  92. ASSERT_NOT_REACHED();
  93. }
  94. }
  95. if (!value.next_chain.is_empty()) {
  96. for (auto& command : value.next_chain) {
  97. switch (command.action) {
  98. case Shell::AST::NodeWithAction::And:
  99. builder.put_literal(" && ");
  100. break;
  101. case Shell::AST::NodeWithAction::Or:
  102. builder.put_literal(" || ");
  103. break;
  104. case Shell::AST::NodeWithAction::Sequence:
  105. builder.put_literal("; ");
  106. break;
  107. }
  108. builder.put_literal("(");
  109. builder.put_literal(command.node->class_name());
  110. builder.put_literal("...)");
  111. }
  112. }
  113. if (!value.should_wait)
  114. builder.put_literal("&");
  115. }
  116. namespace Shell::AST {
  117. static inline void print_indented(const String& str, int indent)
  118. {
  119. for (auto i = 0; i < indent; ++i)
  120. dbgprintf(" ");
  121. dbgprintf("%s\n", str.characters());
  122. }
  123. static inline Optional<Position> merge_positions(const Optional<Position>& left, const Optional<Position>& right)
  124. {
  125. if (!left.has_value())
  126. return right;
  127. if (!right.has_value())
  128. return left;
  129. return Position {
  130. .start_offset = left->start_offset,
  131. .end_offset = right->end_offset,
  132. .start_line = left->start_line,
  133. .end_line = right->end_line,
  134. };
  135. }
  136. static inline Vector<Command> join_commands(Vector<Command> left, Vector<Command> right)
  137. {
  138. Command command;
  139. auto last_in_left = left.take_last();
  140. auto first_in_right = right.take_first();
  141. command.argv.append(last_in_left.argv);
  142. command.argv.append(first_in_right.argv);
  143. command.redirections.append(last_in_left.redirections);
  144. command.redirections.append(first_in_right.redirections);
  145. command.should_wait = first_in_right.should_wait && last_in_left.should_wait;
  146. command.is_pipe_source = first_in_right.is_pipe_source;
  147. command.should_notify_if_in_background = first_in_right.should_notify_if_in_background || last_in_left.should_notify_if_in_background;
  148. command.position = merge_positions(last_in_left.position, first_in_right.position);
  149. Vector<Command> commands;
  150. commands.append(left);
  151. commands.append(command);
  152. commands.append(right);
  153. return commands;
  154. }
  155. void Node::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(NonnullRefPtr<Value>)> callback)
  156. {
  157. auto value = run(shell)->resolve_without_cast(shell);
  158. if (value->is_job()) {
  159. callback(value);
  160. return;
  161. }
  162. if (value->is_list_without_resolution()) {
  163. auto list = value->resolve_without_cast(shell);
  164. for (auto& element : static_cast<ListValue*>(list.ptr())->values()) {
  165. if (callback(element) == IterationDecision::Break)
  166. break;
  167. }
  168. return;
  169. }
  170. auto list = value->resolve_as_list(shell);
  171. for (auto& element : list) {
  172. if (callback(create<StringValue>(move(element))) == IterationDecision::Break)
  173. break;
  174. }
  175. }
  176. Vector<Command> Node::to_lazy_evaluated_commands(RefPtr<Shell> shell)
  177. {
  178. if (would_execute()) {
  179. // Wrap the node in a "should immediately execute next" command.
  180. return {
  181. Command { {}, {}, true, false, true, true, {}, { NodeWithAction(*this, NodeWithAction::Sequence) }, position() }
  182. };
  183. }
  184. return run(shell)->resolve_as_commands(shell);
  185. }
  186. void Node::dump(int level) const
  187. {
  188. print_indented(String::formatted("{} at {}:{} (from {}.{} to {}.{})",
  189. class_name().characters(),
  190. m_position.start_offset,
  191. m_position.end_offset,
  192. m_position.start_line.line_number,
  193. m_position.start_line.line_column,
  194. m_position.end_line.line_number,
  195. m_position.end_line.line_column),
  196. level);
  197. }
  198. Node::Node(Position position)
  199. : m_position(position)
  200. {
  201. }
  202. Vector<Line::CompletionSuggestion> Node::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  203. {
  204. auto matching_node = hit_test_result.matching_node;
  205. if (matching_node) {
  206. if (matching_node->is_bareword()) {
  207. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  208. auto corrected_offset = find_offset_into_node(node->text(), offset - matching_node->position().start_offset);
  209. if (corrected_offset > node->text().length())
  210. return {};
  211. auto& text = node->text();
  212. // If the literal isn't an option, treat it as a path.
  213. if (!(text.starts_with("-") || text == "--" || text == "-"))
  214. return shell.complete_path("", text, corrected_offset);
  215. // If the literal is an option, we have to know the program name
  216. // should we have no way to get that, bail early.
  217. if (!hit_test_result.closest_command_node)
  218. return {};
  219. auto program_name_node = hit_test_result.closest_command_node->leftmost_trivial_literal();
  220. if (!program_name_node)
  221. return {};
  222. String program_name;
  223. if (program_name_node->is_bareword())
  224. program_name = static_cast<BarewordLiteral*>(program_name_node.ptr())->text();
  225. else
  226. program_name = static_cast<StringLiteral*>(program_name_node.ptr())->text();
  227. return shell.complete_option(program_name, text, corrected_offset);
  228. }
  229. return {};
  230. }
  231. auto result = hit_test_position(offset);
  232. if (!result.matching_node)
  233. return {};
  234. auto node = result.matching_node;
  235. if (node->is_bareword() || node != result.closest_node_with_semantic_meaning)
  236. node = result.closest_node_with_semantic_meaning;
  237. if (!node)
  238. return {};
  239. return node->complete_for_editor(shell, offset, result);
  240. }
  241. Vector<Line::CompletionSuggestion> Node::complete_for_editor(Shell& shell, size_t offset)
  242. {
  243. return Node::complete_for_editor(shell, offset, { nullptr, nullptr, nullptr });
  244. }
  245. Node::~Node()
  246. {
  247. }
  248. void And::dump(int level) const
  249. {
  250. Node::dump(level);
  251. m_left->dump(level + 1);
  252. m_right->dump(level + 1);
  253. }
  254. RefPtr<Value> And::run(RefPtr<Shell> shell)
  255. {
  256. auto commands = m_left->to_lazy_evaluated_commands(shell);
  257. commands.last().next_chain.append(NodeWithAction { *m_right, NodeWithAction::And });
  258. return create<CommandSequenceValue>(move(commands));
  259. }
  260. void And::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  261. {
  262. metadata.is_first_in_list = true;
  263. m_left->highlight_in_editor(editor, shell, metadata);
  264. m_right->highlight_in_editor(editor, shell, metadata);
  265. }
  266. HitTestResult And::hit_test_position(size_t offset)
  267. {
  268. if (!position().contains(offset))
  269. return {};
  270. auto result = m_left->hit_test_position(offset);
  271. if (result.matching_node) {
  272. if (!result.closest_command_node)
  273. result.closest_command_node = m_right;
  274. return result;
  275. }
  276. result = m_right->hit_test_position(offset);
  277. if (!result.closest_command_node)
  278. result.closest_command_node = m_right;
  279. return result;
  280. }
  281. And::And(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position and_position)
  282. : Node(move(position))
  283. , m_left(move(left))
  284. , m_right(move(right))
  285. , m_and_position(and_position)
  286. {
  287. if (m_left->is_syntax_error())
  288. set_is_syntax_error(m_left->syntax_error_node());
  289. else if (m_right->is_syntax_error())
  290. set_is_syntax_error(m_right->syntax_error_node());
  291. }
  292. And::~And()
  293. {
  294. }
  295. void ListConcatenate::dump(int level) const
  296. {
  297. Node::dump(level);
  298. for (auto& element : m_list)
  299. element->dump(level + 1);
  300. }
  301. RefPtr<Value> ListConcatenate::run(RefPtr<Shell> shell)
  302. {
  303. RefPtr<Value> result = nullptr;
  304. for (auto& element : m_list) {
  305. if (!result) {
  306. result = create<ListValue>({ element->run(shell)->resolve_without_cast(shell) });
  307. continue;
  308. }
  309. auto element_value = element->run(shell)->resolve_without_cast(shell);
  310. if (result->is_command() || element_value->is_command()) {
  311. auto joined_commands = join_commands(result->resolve_as_commands(shell), element_value->resolve_as_commands(shell));
  312. if (joined_commands.size() == 1) {
  313. auto& command = joined_commands[0];
  314. command.position = position();
  315. result = create<CommandValue>(command);
  316. } else {
  317. result = create<CommandSequenceValue>(move(joined_commands));
  318. }
  319. } else {
  320. NonnullRefPtrVector<Value> values;
  321. if (result->is_list_without_resolution()) {
  322. values.append(static_cast<ListValue*>(result.ptr())->values());
  323. } else {
  324. for (auto& result : result->resolve_as_list(shell))
  325. values.append(create<StringValue>(result));
  326. }
  327. values.append(element_value);
  328. result = create<ListValue>(move(values));
  329. }
  330. }
  331. if (!result)
  332. return create<ListValue>({});
  333. return result;
  334. }
  335. void ListConcatenate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  336. {
  337. auto first = metadata.is_first_in_list;
  338. metadata.is_first_in_list = false;
  339. metadata.is_first_in_list = first;
  340. for (auto& element : m_list) {
  341. element->highlight_in_editor(editor, shell, metadata);
  342. metadata.is_first_in_list = false;
  343. }
  344. }
  345. HitTestResult ListConcatenate::hit_test_position(size_t offset)
  346. {
  347. if (!position().contains(offset))
  348. return {};
  349. bool first = true;
  350. for (auto& element : m_list) {
  351. auto result = element->hit_test_position(offset);
  352. if (!result.closest_node_with_semantic_meaning && !first)
  353. result.closest_node_with_semantic_meaning = this;
  354. if (result.matching_node)
  355. return result;
  356. first = false;
  357. }
  358. return {};
  359. }
  360. RefPtr<Node> ListConcatenate::leftmost_trivial_literal() const
  361. {
  362. if (m_list.is_empty())
  363. return nullptr;
  364. return m_list.first()->leftmost_trivial_literal();
  365. }
  366. ListConcatenate::ListConcatenate(Position position, Vector<NonnullRefPtr<Node>> list)
  367. : Node(move(position))
  368. , m_list(move(list))
  369. {
  370. for (auto& element : m_list) {
  371. if (element->is_syntax_error()) {
  372. set_is_syntax_error(element->syntax_error_node());
  373. break;
  374. }
  375. }
  376. }
  377. ListConcatenate::~ListConcatenate()
  378. {
  379. }
  380. void Background::dump(int level) const
  381. {
  382. Node::dump(level);
  383. m_command->dump(level + 1);
  384. }
  385. RefPtr<Value> Background::run(RefPtr<Shell> shell)
  386. {
  387. auto commands = m_command->to_lazy_evaluated_commands(shell);
  388. for (auto& command : commands)
  389. command.should_wait = false;
  390. return create<CommandSequenceValue>(move(commands));
  391. }
  392. void Background::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  393. {
  394. m_command->highlight_in_editor(editor, shell, metadata);
  395. }
  396. HitTestResult Background::hit_test_position(size_t offset)
  397. {
  398. if (!position().contains(offset))
  399. return {};
  400. return m_command->hit_test_position(offset);
  401. }
  402. Background::Background(Position position, NonnullRefPtr<Node> command)
  403. : Node(move(position))
  404. , m_command(move(command))
  405. {
  406. if (m_command->is_syntax_error())
  407. set_is_syntax_error(m_command->syntax_error_node());
  408. }
  409. Background::~Background()
  410. {
  411. }
  412. void BarewordLiteral::dump(int level) const
  413. {
  414. Node::dump(level);
  415. print_indented(m_text, level + 1);
  416. }
  417. RefPtr<Value> BarewordLiteral::run(RefPtr<Shell>)
  418. {
  419. return create<StringValue>(m_text);
  420. }
  421. void BarewordLiteral::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  422. {
  423. if (metadata.is_first_in_list) {
  424. if (shell.is_runnable(m_text)) {
  425. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Bold });
  426. } else {
  427. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red) });
  428. }
  429. return;
  430. }
  431. if (m_text.starts_with('-')) {
  432. if (m_text == "--") {
  433. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  434. return;
  435. }
  436. if (m_text == "-")
  437. return;
  438. if (m_text.starts_with("--")) {
  439. auto index = m_text.index_of("=").value_or(m_text.length() - 1) + 1;
  440. editor.stylize({ m_position.start_offset, m_position.start_offset + index }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  441. } else {
  442. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  443. }
  444. }
  445. if (Core::File::exists(m_text)) {
  446. auto realpath = shell.resolve_path(m_text);
  447. auto url = URL::create_with_file_protocol(realpath);
  448. url.set_host(shell.hostname);
  449. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  450. }
  451. }
  452. BarewordLiteral::BarewordLiteral(Position position, String text)
  453. : Node(move(position))
  454. , m_text(move(text))
  455. {
  456. }
  457. BarewordLiteral::~BarewordLiteral()
  458. {
  459. }
  460. void BraceExpansion::dump(int level) const
  461. {
  462. Node::dump(level);
  463. for (auto& entry : m_entries)
  464. entry.dump(level + 1);
  465. }
  466. RefPtr<Value> BraceExpansion::run(RefPtr<Shell> shell)
  467. {
  468. NonnullRefPtrVector<Value> values;
  469. for (auto& entry : m_entries) {
  470. auto value = entry.run(shell);
  471. if (value)
  472. values.append(value.release_nonnull());
  473. }
  474. return create<ListValue>(move(values));
  475. }
  476. HitTestResult BraceExpansion::hit_test_position(size_t offset)
  477. {
  478. if (!position().contains(offset))
  479. return {};
  480. for (auto& entry : m_entries) {
  481. auto result = entry.hit_test_position(offset);
  482. if (result.matching_node) {
  483. if (!result.closest_command_node)
  484. result.closest_command_node = &entry;
  485. return result;
  486. }
  487. }
  488. return {};
  489. }
  490. void BraceExpansion::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  491. {
  492. for (auto& entry : m_entries) {
  493. entry.highlight_in_editor(editor, shell, metadata);
  494. metadata.is_first_in_list = false;
  495. }
  496. }
  497. BraceExpansion::BraceExpansion(Position position, NonnullRefPtrVector<Node> entries)
  498. : Node(move(position))
  499. , m_entries(move(entries))
  500. {
  501. for (auto& entry : m_entries) {
  502. if (entry.is_syntax_error()) {
  503. set_is_syntax_error(entry.syntax_error_node());
  504. break;
  505. }
  506. }
  507. }
  508. BraceExpansion::~BraceExpansion()
  509. {
  510. }
  511. void CastToCommand::dump(int level) const
  512. {
  513. Node::dump(level);
  514. m_inner->dump(level + 1);
  515. }
  516. RefPtr<Value> CastToCommand::run(RefPtr<Shell> shell)
  517. {
  518. if (m_inner->is_command())
  519. return m_inner->run(shell);
  520. auto value = m_inner->run(shell)->resolve_without_cast(shell);
  521. if (value->is_command())
  522. return value;
  523. auto argv = value->resolve_as_list(shell);
  524. return create<CommandValue>(move(argv), position());
  525. }
  526. void CastToCommand::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  527. {
  528. m_inner->highlight_in_editor(editor, shell, metadata);
  529. }
  530. HitTestResult CastToCommand::hit_test_position(size_t offset)
  531. {
  532. if (!position().contains(offset))
  533. return {};
  534. auto result = m_inner->hit_test_position(offset);
  535. if (!result.closest_node_with_semantic_meaning)
  536. result.closest_node_with_semantic_meaning = this;
  537. return result;
  538. }
  539. Vector<Line::CompletionSuggestion> CastToCommand::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  540. {
  541. auto matching_node = hit_test_result.matching_node;
  542. if (!matching_node || !matching_node->is_bareword())
  543. return {};
  544. auto corrected_offset = offset - matching_node->position().start_offset;
  545. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  546. if (corrected_offset > node->text().length())
  547. return {};
  548. return shell.complete_program_name(node->text(), corrected_offset);
  549. }
  550. RefPtr<Node> CastToCommand::leftmost_trivial_literal() const
  551. {
  552. return m_inner->leftmost_trivial_literal();
  553. }
  554. CastToCommand::CastToCommand(Position position, NonnullRefPtr<Node> inner)
  555. : Node(move(position))
  556. , m_inner(move(inner))
  557. {
  558. if (m_inner->is_syntax_error())
  559. set_is_syntax_error(m_inner->syntax_error_node());
  560. }
  561. CastToCommand::~CastToCommand()
  562. {
  563. }
  564. void CastToList::dump(int level) const
  565. {
  566. Node::dump(level);
  567. if (m_inner)
  568. m_inner->dump(level + 1);
  569. else
  570. print_indented("(empty)", level + 1);
  571. }
  572. RefPtr<Value> CastToList::run(RefPtr<Shell> shell)
  573. {
  574. if (!m_inner)
  575. return create<ListValue>({});
  576. auto inner_value = m_inner->run(shell)->resolve_without_cast(shell);
  577. if (inner_value->is_command() || inner_value->is_list())
  578. return inner_value;
  579. auto values = inner_value->resolve_as_list(shell);
  580. NonnullRefPtrVector<Value> cast_values;
  581. for (auto& value : values)
  582. cast_values.append(create<StringValue>(value));
  583. return create<ListValue>(cast_values);
  584. }
  585. void CastToList::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  586. {
  587. if (m_inner)
  588. m_inner->highlight_in_editor(editor, shell, metadata);
  589. }
  590. HitTestResult CastToList::hit_test_position(size_t offset)
  591. {
  592. if (!position().contains(offset))
  593. return {};
  594. if (!m_inner)
  595. return {};
  596. return m_inner->hit_test_position(offset);
  597. }
  598. RefPtr<Node> CastToList::leftmost_trivial_literal() const
  599. {
  600. return m_inner->leftmost_trivial_literal();
  601. }
  602. CastToList::CastToList(Position position, RefPtr<Node> inner)
  603. : Node(move(position))
  604. , m_inner(move(inner))
  605. {
  606. if (m_inner && m_inner->is_syntax_error())
  607. set_is_syntax_error(m_inner->syntax_error_node());
  608. }
  609. CastToList::~CastToList()
  610. {
  611. }
  612. void CloseFdRedirection::dump(int level) const
  613. {
  614. Node::dump(level);
  615. print_indented(String::format("%d -> Close", m_fd), level);
  616. }
  617. RefPtr<Value> CloseFdRedirection::run(RefPtr<Shell>)
  618. {
  619. Command command;
  620. command.position = position();
  621. command.redirections.append(adopt(*new CloseRedirection(m_fd)));
  622. return create<CommandValue>(move(command));
  623. }
  624. void CloseFdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  625. {
  626. editor.stylize({ m_position.start_offset, m_position.end_offset - 1 }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  627. editor.stylize({ m_position.end_offset - 1, m_position.end_offset }, { Line::Style::Foreground(0xff, 0x7e, 0x00) }); // Amber
  628. }
  629. CloseFdRedirection::CloseFdRedirection(Position position, int fd)
  630. : Node(move(position))
  631. , m_fd(fd)
  632. {
  633. }
  634. CloseFdRedirection::~CloseFdRedirection()
  635. {
  636. }
  637. void CommandLiteral::dump(int level) const
  638. {
  639. Node::dump(level);
  640. print_indented("(Generated command literal)", level + 1);
  641. }
  642. RefPtr<Value> CommandLiteral::run(RefPtr<Shell>)
  643. {
  644. return create<CommandValue>(m_command);
  645. }
  646. CommandLiteral::CommandLiteral(Position position, Command command)
  647. : Node(move(position))
  648. , m_command(move(command))
  649. {
  650. }
  651. CommandLiteral::~CommandLiteral()
  652. {
  653. }
  654. void Comment::dump(int level) const
  655. {
  656. Node::dump(level);
  657. print_indented(m_text, level + 1);
  658. }
  659. RefPtr<Value> Comment::run(RefPtr<Shell>)
  660. {
  661. return create<ListValue>({});
  662. }
  663. void Comment::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  664. {
  665. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(150, 150, 150) }); // Light gray
  666. }
  667. Comment::Comment(Position position, String text)
  668. : Node(move(position))
  669. , m_text(move(text))
  670. {
  671. }
  672. Comment::~Comment()
  673. {
  674. }
  675. void ContinuationControl::dump(int level) const
  676. {
  677. Node::dump(level);
  678. print_indented(m_kind == Continue ? "(Continue)" : "(Break)", level + 1);
  679. }
  680. RefPtr<Value> ContinuationControl::run(RefPtr<Shell> shell)
  681. {
  682. if (m_kind == Break)
  683. shell->raise_error(Shell::ShellError::InternalControlFlowBreak, {}, position());
  684. else if (m_kind == Continue)
  685. shell->raise_error(Shell::ShellError::InternalControlFlowContinue, {}, position());
  686. else
  687. ASSERT_NOT_REACHED();
  688. return create<ListValue>({});
  689. }
  690. void ContinuationControl::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  691. {
  692. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  693. }
  694. void DoubleQuotedString::dump(int level) const
  695. {
  696. Node::dump(level);
  697. m_inner->dump(level + 1);
  698. }
  699. RefPtr<Value> DoubleQuotedString::run(RefPtr<Shell> shell)
  700. {
  701. StringBuilder builder;
  702. auto values = m_inner->run(shell)->resolve_as_list(shell);
  703. builder.join("", values);
  704. return create<StringValue>(builder.to_string());
  705. }
  706. void DoubleQuotedString::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  707. {
  708. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  709. if (metadata.is_first_in_list)
  710. style.unify_with({ Line::Style::Bold });
  711. editor.stylize({ m_position.start_offset, m_position.end_offset }, style);
  712. metadata.is_first_in_list = false;
  713. m_inner->highlight_in_editor(editor, shell, metadata);
  714. }
  715. HitTestResult DoubleQuotedString::hit_test_position(size_t offset)
  716. {
  717. if (!position().contains(offset))
  718. return {};
  719. return m_inner->hit_test_position(offset);
  720. }
  721. DoubleQuotedString::DoubleQuotedString(Position position, RefPtr<Node> inner)
  722. : Node(move(position))
  723. , m_inner(move(inner))
  724. {
  725. if (m_inner->is_syntax_error())
  726. set_is_syntax_error(m_inner->syntax_error_node());
  727. }
  728. DoubleQuotedString::~DoubleQuotedString()
  729. {
  730. }
  731. void DynamicEvaluate::dump(int level) const
  732. {
  733. Node::dump(level);
  734. m_inner->dump(level + 1);
  735. }
  736. RefPtr<Value> DynamicEvaluate::run(RefPtr<Shell> shell)
  737. {
  738. auto result = m_inner->run(shell)->resolve_without_cast(shell);
  739. // Dynamic Evaluation behaves differently between strings and lists.
  740. // Strings are treated as variables, and Lists are treated as commands.
  741. if (result->is_string()) {
  742. auto name_part = result->resolve_as_list(shell);
  743. ASSERT(name_part.size() == 1);
  744. return create<SimpleVariableValue>(name_part[0]);
  745. }
  746. // If it's anything else, we're just gonna cast it to a list.
  747. auto list = result->resolve_as_list(shell);
  748. return create<CommandValue>(move(list), position());
  749. }
  750. void DynamicEvaluate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  751. {
  752. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  753. m_inner->highlight_in_editor(editor, shell, metadata);
  754. }
  755. HitTestResult DynamicEvaluate::hit_test_position(size_t offset)
  756. {
  757. if (!position().contains(offset))
  758. return {};
  759. return m_inner->hit_test_position(offset);
  760. }
  761. DynamicEvaluate::DynamicEvaluate(Position position, NonnullRefPtr<Node> inner)
  762. : Node(move(position))
  763. , m_inner(move(inner))
  764. {
  765. if (m_inner->is_syntax_error())
  766. set_is_syntax_error(m_inner->syntax_error_node());
  767. }
  768. DynamicEvaluate::~DynamicEvaluate()
  769. {
  770. }
  771. void Fd2FdRedirection::dump(int level) const
  772. {
  773. Node::dump(level);
  774. print_indented(String::format("%d -> %d", m_old_fd, m_new_fd), level);
  775. }
  776. RefPtr<Value> Fd2FdRedirection::run(RefPtr<Shell>)
  777. {
  778. Command command;
  779. command.position = position();
  780. command.redirections.append(FdRedirection::create(m_new_fd, m_old_fd, Rewiring::Close::None));
  781. return create<CommandValue>(move(command));
  782. }
  783. void Fd2FdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  784. {
  785. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  786. }
  787. Fd2FdRedirection::Fd2FdRedirection(Position position, int src, int dst)
  788. : Node(move(position))
  789. , m_old_fd(src)
  790. , m_new_fd(dst)
  791. {
  792. }
  793. Fd2FdRedirection::~Fd2FdRedirection()
  794. {
  795. }
  796. void FunctionDeclaration::dump(int level) const
  797. {
  798. Node::dump(level);
  799. print_indented(String::format("(name: %s)\n", m_name.name.characters()), level + 1);
  800. print_indented("(argument namess)", level + 1);
  801. for (auto& arg : m_arguments)
  802. print_indented(String::format("(name: %s)\n", arg.name.characters()), level + 2);
  803. print_indented("(body)", level + 1);
  804. if (m_block)
  805. m_block->dump(level + 2);
  806. else
  807. print_indented("(null)", level + 2);
  808. }
  809. RefPtr<Value> FunctionDeclaration::run(RefPtr<Shell> shell)
  810. {
  811. Vector<String> args;
  812. for (auto& arg : m_arguments)
  813. args.append(arg.name);
  814. shell->define_function(m_name.name, move(args), m_block);
  815. return create<ListValue>({});
  816. }
  817. void FunctionDeclaration::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  818. {
  819. editor.stylize({ m_name.position.start_offset, m_name.position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
  820. for (auto& arg : m_arguments)
  821. editor.stylize({ arg.position.start_offset, arg.position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });
  822. metadata.is_first_in_list = true;
  823. if (m_block)
  824. m_block->highlight_in_editor(editor, shell, metadata);
  825. }
  826. HitTestResult FunctionDeclaration::hit_test_position(size_t offset)
  827. {
  828. if (!position().contains(offset))
  829. return {};
  830. if (!m_block)
  831. return {};
  832. auto result = m_block->hit_test_position(offset);
  833. if (result.matching_node && result.matching_node->is_simple_variable())
  834. result.closest_node_with_semantic_meaning = this;
  835. return result;
  836. }
  837. Vector<Line::CompletionSuggestion> FunctionDeclaration::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  838. {
  839. auto matching_node = hit_test_result.matching_node;
  840. if (!matching_node)
  841. return {};
  842. if (!matching_node->is_simple_variable())
  843. return matching_node->complete_for_editor(shell, offset, hit_test_result);
  844. auto corrected_offset = offset - matching_node->position().start_offset - 1; // Skip the first '$'
  845. auto* node = static_cast<SimpleVariable*>(matching_node.ptr());
  846. auto name = node->name().substring_view(0, corrected_offset);
  847. Vector<Line::CompletionSuggestion> results;
  848. for (auto& arg : m_arguments) {
  849. if (arg.name.starts_with(name))
  850. results.append(arg.name);
  851. }
  852. results.append(matching_node->complete_for_editor(shell, offset, hit_test_result));
  853. return results;
  854. }
  855. FunctionDeclaration::FunctionDeclaration(Position position, NameWithPosition name, Vector<NameWithPosition> arguments, RefPtr<AST::Node> body)
  856. : Node(move(position))
  857. , m_name(move(name))
  858. , m_arguments(arguments)
  859. , m_block(move(body))
  860. {
  861. if (m_block && m_block->is_syntax_error())
  862. set_is_syntax_error(m_block->syntax_error_node());
  863. }
  864. FunctionDeclaration::~FunctionDeclaration()
  865. {
  866. }
  867. void ForLoop::dump(int level) const
  868. {
  869. Node::dump(level);
  870. print_indented(String::format("%s in\n", m_variable_name.characters()), level + 1);
  871. if (m_iterated_expression)
  872. m_iterated_expression->dump(level + 2);
  873. else
  874. print_indented("(ever)", level + 2);
  875. print_indented("Running", level + 1);
  876. if (m_block)
  877. m_block->dump(level + 2);
  878. else
  879. print_indented("(null)", level + 2);
  880. }
  881. RefPtr<Value> ForLoop::run(RefPtr<Shell> shell)
  882. {
  883. if (!m_block)
  884. return create<ListValue>({});
  885. size_t consecutive_interruptions = 0;
  886. auto run = [&](auto& block_value) {
  887. if (shell->has_error(Shell::ShellError::InternalControlFlowBreak)) {
  888. shell->take_error();
  889. return IterationDecision::Break;
  890. }
  891. if (shell->has_error(Shell::ShellError::InternalControlFlowContinue)) {
  892. shell->take_error();
  893. return IterationDecision::Continue;
  894. }
  895. if (block_value->is_job()) {
  896. auto job = static_cast<JobValue*>(block_value.ptr())->job();
  897. if (!job || job->is_running_in_background())
  898. return IterationDecision::Continue;
  899. shell->block_on_job(job);
  900. if (job->signaled()) {
  901. if (job->termination_signal() == SIGINT)
  902. ++consecutive_interruptions;
  903. else
  904. return IterationDecision::Break;
  905. } else {
  906. consecutive_interruptions = 0;
  907. }
  908. }
  909. return IterationDecision::Continue;
  910. };
  911. if (m_iterated_expression) {
  912. m_iterated_expression->for_each_entry(shell, [&](auto value) {
  913. if (consecutive_interruptions == 2)
  914. return IterationDecision::Break;
  915. RefPtr<Value> block_value;
  916. {
  917. auto frame = shell->push_frame(String::formatted("for ({})", this));
  918. shell->set_local_variable(m_variable_name, value, true);
  919. block_value = m_block->run(shell);
  920. }
  921. return run(block_value);
  922. });
  923. } else {
  924. for (;;) {
  925. if (consecutive_interruptions == 2)
  926. break;
  927. RefPtr<Value> block_value = m_block->run(shell);
  928. if (run(block_value) == IterationDecision::Break)
  929. break;
  930. }
  931. }
  932. return create<ListValue>({});
  933. }
  934. void ForLoop::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  935. {
  936. auto is_loop = m_iterated_expression.is_null();
  937. editor.stylize({ m_position.start_offset, m_position.start_offset + (is_loop ? 4 : 3) }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  938. if (!is_loop) {
  939. if (m_in_kw_position.has_value())
  940. editor.stylize({ m_in_kw_position.value().start_offset, m_in_kw_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  941. metadata.is_first_in_list = false;
  942. m_iterated_expression->highlight_in_editor(editor, shell, metadata);
  943. }
  944. metadata.is_first_in_list = true;
  945. if (m_block)
  946. m_block->highlight_in_editor(editor, shell, metadata);
  947. }
  948. HitTestResult ForLoop::hit_test_position(size_t offset)
  949. {
  950. if (!position().contains(offset))
  951. return {};
  952. if (m_iterated_expression) {
  953. if (auto result = m_iterated_expression->hit_test_position(offset); result.matching_node)
  954. return result;
  955. }
  956. if (!m_block)
  957. return {};
  958. return m_block->hit_test_position(offset);
  959. }
  960. ForLoop::ForLoop(Position position, String variable_name, RefPtr<AST::Node> iterated_expr, RefPtr<AST::Node> block, Optional<Position> in_kw_position)
  961. : Node(move(position))
  962. , m_variable_name(move(variable_name))
  963. , m_iterated_expression(move(iterated_expr))
  964. , m_block(move(block))
  965. , m_in_kw_position(move(in_kw_position))
  966. {
  967. if (m_iterated_expression && m_iterated_expression->is_syntax_error())
  968. set_is_syntax_error(m_iterated_expression->syntax_error_node());
  969. else if (m_block && m_block->is_syntax_error())
  970. set_is_syntax_error(m_block->syntax_error_node());
  971. }
  972. ForLoop::~ForLoop()
  973. {
  974. }
  975. void Glob::dump(int level) const
  976. {
  977. Node::dump(level);
  978. print_indented(m_text, level + 1);
  979. }
  980. RefPtr<Value> Glob::run(RefPtr<Shell>)
  981. {
  982. return create<GlobValue>(m_text, position());
  983. }
  984. void Glob::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  985. {
  986. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Cyan) };
  987. if (metadata.is_first_in_list)
  988. style.unify_with({ Line::Style::Bold });
  989. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  990. }
  991. Glob::Glob(Position position, String text)
  992. : Node(move(position))
  993. , m_text(move(text))
  994. {
  995. }
  996. Glob::~Glob()
  997. {
  998. }
  999. void Execute::dump(int level) const
  1000. {
  1001. Node::dump(level);
  1002. if (m_capture_stdout)
  1003. print_indented("(Capturing stdout)", level + 1);
  1004. m_command->dump(level + 1);
  1005. }
  1006. void Execute::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(NonnullRefPtr<Value>)> callback)
  1007. {
  1008. if (m_command->would_execute())
  1009. return m_command->for_each_entry(shell, move(callback));
  1010. auto commands = shell->expand_aliases(m_command->run(shell)->resolve_as_commands(shell));
  1011. if (m_capture_stdout) {
  1012. int pipefd[2];
  1013. int rc = pipe(pipefd);
  1014. if (rc < 0) {
  1015. dbgln("Error: cannot pipe(): {}", strerror(errno));
  1016. return;
  1017. }
  1018. auto& last_in_commands = commands.last();
  1019. last_in_commands.redirections.prepend(FdRedirection::create(pipefd[1], STDOUT_FILENO, Rewiring::Close::Old));
  1020. last_in_commands.should_wait = false;
  1021. last_in_commands.should_notify_if_in_background = false;
  1022. last_in_commands.is_pipe_source = false;
  1023. Core::EventLoop loop;
  1024. auto notifier = Core::Notifier::construct(pipefd[0], Core::Notifier::Read);
  1025. DuplexMemoryStream stream;
  1026. enum {
  1027. Continue,
  1028. Break,
  1029. NothingLeft,
  1030. };
  1031. auto check_and_call = [&] {
  1032. auto ifs = shell->local_variable_or("IFS", "\n");
  1033. if (auto offset = stream.offset_of(ifs.bytes()); offset.has_value()) {
  1034. auto line_end = offset.value();
  1035. if (line_end == 0) {
  1036. auto rc = stream.discard_or_error(ifs.length());
  1037. ASSERT(rc);
  1038. if (shell->options.inline_exec_keep_empty_segments)
  1039. if (callback(create<StringValue>("")) == IterationDecision::Break) {
  1040. loop.quit(Break);
  1041. notifier->set_enabled(false);
  1042. return Break;
  1043. }
  1044. } else {
  1045. auto entry = ByteBuffer::create_uninitialized(line_end + ifs.length());
  1046. auto rc = stream.read_or_error(entry);
  1047. ASSERT(rc);
  1048. auto str = StringView(entry.data(), entry.size() - ifs.length());
  1049. if (callback(create<StringValue>(str)) == IterationDecision::Break) {
  1050. loop.quit(Break);
  1051. notifier->set_enabled(false);
  1052. return Break;
  1053. }
  1054. }
  1055. return Continue;
  1056. }
  1057. return NothingLeft;
  1058. };
  1059. notifier->on_ready_to_read = [&] {
  1060. constexpr static auto buffer_size = 16;
  1061. u8 buffer[buffer_size];
  1062. size_t remaining_size = buffer_size;
  1063. for (;;) {
  1064. notifier->set_event_mask(Core::Notifier::None);
  1065. bool should_enable_notifier = false;
  1066. ScopeGuard notifier_enabler { [&] {
  1067. if (should_enable_notifier)
  1068. notifier->set_event_mask(Core::Notifier::Read);
  1069. } };
  1070. if (check_and_call() == Break) {
  1071. loop.quit(Break);
  1072. return;
  1073. }
  1074. auto read_size = read(pipefd[0], buffer, remaining_size);
  1075. if (read_size < 0) {
  1076. int saved_errno = errno;
  1077. if (saved_errno == EINTR) {
  1078. should_enable_notifier = true;
  1079. continue;
  1080. }
  1081. if (saved_errno == 0)
  1082. continue;
  1083. dbgln("read() failed: {}", strerror(saved_errno));
  1084. break;
  1085. }
  1086. if (read_size == 0)
  1087. break;
  1088. should_enable_notifier = true;
  1089. stream.write({ buffer, (size_t)read_size });
  1090. }
  1091. loop.quit(NothingLeft);
  1092. };
  1093. auto jobs = shell->run_commands(commands);
  1094. ScopeGuard kill_jobs_if_around { [&] {
  1095. for (auto& job : jobs) {
  1096. if (job.is_running_in_background() && !job.exited() && !job.signaled()) {
  1097. job.set_should_announce_signal(false); // We're explicitly killing it here.
  1098. shell->kill_job(&job, SIGTERM);
  1099. }
  1100. }
  1101. } };
  1102. auto exit_reason = loop.exec();
  1103. notifier->on_ready_to_read = nullptr;
  1104. if (close(pipefd[0]) < 0) {
  1105. dbgln("close() failed: {}", strerror(errno));
  1106. }
  1107. if (exit_reason != Break && !stream.eof()) {
  1108. auto action = Continue;
  1109. do {
  1110. action = check_and_call();
  1111. if (action == Break)
  1112. return;
  1113. } while (action == Continue);
  1114. if (!stream.eof()) {
  1115. auto entry = ByteBuffer::create_uninitialized(stream.size());
  1116. auto rc = stream.read_or_error(entry);
  1117. ASSERT(rc);
  1118. callback(create<StringValue>(String::copy(entry)));
  1119. }
  1120. }
  1121. return;
  1122. }
  1123. auto jobs = shell->run_commands(commands);
  1124. if (!jobs.is_empty())
  1125. callback(create<JobValue>(&jobs.last()));
  1126. }
  1127. RefPtr<Value> Execute::run(RefPtr<Shell> shell)
  1128. {
  1129. if (m_command->would_execute())
  1130. return m_command->run(shell);
  1131. NonnullRefPtrVector<Value> values;
  1132. for_each_entry(shell, [&](auto value) {
  1133. values.append(*value);
  1134. return IterationDecision::Continue;
  1135. });
  1136. if (values.size() == 1 && values.first().is_job())
  1137. return values.first();
  1138. return create<ListValue>(move(values));
  1139. }
  1140. void Execute::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1141. {
  1142. if (m_capture_stdout)
  1143. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  1144. metadata.is_first_in_list = true;
  1145. m_command->highlight_in_editor(editor, shell, metadata);
  1146. }
  1147. HitTestResult Execute::hit_test_position(size_t offset)
  1148. {
  1149. if (!position().contains(offset))
  1150. return {};
  1151. auto result = m_command->hit_test_position(offset);
  1152. if (!result.closest_node_with_semantic_meaning)
  1153. result.closest_node_with_semantic_meaning = this;
  1154. if (!result.closest_command_node)
  1155. result.closest_command_node = m_command;
  1156. return result;
  1157. }
  1158. Vector<Line::CompletionSuggestion> Execute::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1159. {
  1160. auto matching_node = hit_test_result.matching_node;
  1161. if (!matching_node || !matching_node->is_bareword())
  1162. return {};
  1163. auto corrected_offset = offset - matching_node->position().start_offset;
  1164. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  1165. if (corrected_offset > node->text().length())
  1166. return {};
  1167. return shell.complete_program_name(node->text(), corrected_offset);
  1168. }
  1169. Execute::Execute(Position position, NonnullRefPtr<Node> command, bool capture_stdout)
  1170. : Node(move(position))
  1171. , m_command(move(command))
  1172. , m_capture_stdout(capture_stdout)
  1173. {
  1174. if (m_command->is_syntax_error())
  1175. set_is_syntax_error(m_command->syntax_error_node());
  1176. }
  1177. Execute::~Execute()
  1178. {
  1179. }
  1180. void IfCond::dump(int level) const
  1181. {
  1182. Node::dump(level);
  1183. print_indented("Condition", ++level);
  1184. m_condition->dump(level + 1);
  1185. print_indented("True Branch", level);
  1186. if (m_true_branch)
  1187. m_true_branch->dump(level + 1);
  1188. else
  1189. print_indented("(empty)", level + 1);
  1190. print_indented("False Branch", level);
  1191. if (m_false_branch)
  1192. m_false_branch->dump(level + 1);
  1193. else
  1194. print_indented("(empty)", level + 1);
  1195. }
  1196. RefPtr<Value> IfCond::run(RefPtr<Shell> shell)
  1197. {
  1198. auto cond = m_condition->run(shell)->resolve_without_cast(shell);
  1199. // The condition could be a builtin, in which case it has already run and exited.
  1200. if (cond && cond->is_job()) {
  1201. auto cond_job_value = static_cast<const JobValue*>(cond.ptr());
  1202. auto cond_job = cond_job_value->job();
  1203. shell->block_on_job(cond_job);
  1204. if (cond_job->signaled())
  1205. return create<ListValue>({}); // Exit early.
  1206. }
  1207. if (shell->last_return_code == 0) {
  1208. if (m_true_branch)
  1209. return m_true_branch->run(shell);
  1210. } else {
  1211. if (m_false_branch)
  1212. return m_false_branch->run(shell);
  1213. }
  1214. return create<ListValue>({});
  1215. }
  1216. void IfCond::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1217. {
  1218. metadata.is_first_in_list = true;
  1219. editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1220. if (m_else_position.has_value())
  1221. editor.stylize({ m_else_position.value().start_offset, m_else_position.value().start_offset + 4 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1222. m_condition->highlight_in_editor(editor, shell, metadata);
  1223. if (m_true_branch)
  1224. m_true_branch->highlight_in_editor(editor, shell, metadata);
  1225. if (m_false_branch)
  1226. m_false_branch->highlight_in_editor(editor, shell, metadata);
  1227. }
  1228. HitTestResult IfCond::hit_test_position(size_t offset)
  1229. {
  1230. if (!position().contains(offset))
  1231. return {};
  1232. if (auto result = m_condition->hit_test_position(offset); result.matching_node)
  1233. return result;
  1234. if (m_true_branch) {
  1235. if (auto result = m_true_branch->hit_test_position(offset); result.matching_node)
  1236. return result;
  1237. }
  1238. if (m_false_branch) {
  1239. if (auto result = m_false_branch->hit_test_position(offset); result.matching_node)
  1240. return result;
  1241. }
  1242. return {};
  1243. }
  1244. IfCond::IfCond(Position position, Optional<Position> else_position, NonnullRefPtr<Node> condition, RefPtr<Node> true_branch, RefPtr<Node> false_branch)
  1245. : Node(move(position))
  1246. , m_condition(move(condition))
  1247. , m_true_branch(move(true_branch))
  1248. , m_false_branch(move(false_branch))
  1249. , m_else_position(move(else_position))
  1250. {
  1251. if (m_condition->is_syntax_error())
  1252. set_is_syntax_error(m_condition->syntax_error_node());
  1253. else if (m_true_branch && m_true_branch->is_syntax_error())
  1254. set_is_syntax_error(m_true_branch->syntax_error_node());
  1255. else if (m_false_branch && m_false_branch->is_syntax_error())
  1256. set_is_syntax_error(m_false_branch->syntax_error_node());
  1257. m_condition = create<AST::Execute>(m_condition->position(), m_condition);
  1258. if (m_true_branch) {
  1259. auto true_branch = m_true_branch.release_nonnull();
  1260. m_true_branch = create<AST::Execute>(true_branch->position(), true_branch);
  1261. }
  1262. if (m_false_branch) {
  1263. auto false_branch = m_false_branch.release_nonnull();
  1264. m_false_branch = create<AST::Execute>(false_branch->position(), false_branch);
  1265. }
  1266. }
  1267. IfCond::~IfCond()
  1268. {
  1269. }
  1270. void Join::dump(int level) const
  1271. {
  1272. Node::dump(level);
  1273. m_left->dump(level + 1);
  1274. m_right->dump(level + 1);
  1275. }
  1276. RefPtr<Value> Join::run(RefPtr<Shell> shell)
  1277. {
  1278. auto left = m_left->to_lazy_evaluated_commands(shell);
  1279. auto right = m_right->to_lazy_evaluated_commands(shell);
  1280. return create<CommandSequenceValue>(join_commands(move(left), move(right)));
  1281. }
  1282. void Join::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1283. {
  1284. m_left->highlight_in_editor(editor, shell, metadata);
  1285. if (m_left->is_list() || m_left->is_command())
  1286. metadata.is_first_in_list = false;
  1287. m_right->highlight_in_editor(editor, shell, metadata);
  1288. }
  1289. HitTestResult Join::hit_test_position(size_t offset)
  1290. {
  1291. if (!position().contains(offset))
  1292. return {};
  1293. auto result = m_left->hit_test_position(offset);
  1294. if (result.matching_node)
  1295. return result;
  1296. return m_right->hit_test_position(offset);
  1297. }
  1298. RefPtr<Node> Join::leftmost_trivial_literal() const
  1299. {
  1300. if (auto value = m_left->leftmost_trivial_literal())
  1301. return value;
  1302. return m_right->leftmost_trivial_literal();
  1303. }
  1304. Join::Join(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  1305. : Node(move(position))
  1306. , m_left(move(left))
  1307. , m_right(move(right))
  1308. {
  1309. if (m_left->is_syntax_error())
  1310. set_is_syntax_error(m_left->syntax_error_node());
  1311. else if (m_right->is_syntax_error())
  1312. set_is_syntax_error(m_right->syntax_error_node());
  1313. }
  1314. Join::~Join()
  1315. {
  1316. }
  1317. void MatchExpr::dump(int level) const
  1318. {
  1319. Node::dump(level);
  1320. print_indented(String::formatted("(expression: {})", m_expr_name.characters()), level + 1);
  1321. m_matched_expr->dump(level + 2);
  1322. print_indented(String::formatted("(named: {})", m_expr_name.characters()), level + 1);
  1323. print_indented("(entries)", level + 1);
  1324. for (auto& entry : m_entries) {
  1325. StringBuilder builder;
  1326. builder.append("(match");
  1327. if (entry.match_names.has_value()) {
  1328. builder.append(" to names (");
  1329. bool first = true;
  1330. for (auto& name : entry.match_names.value()) {
  1331. if (!first)
  1332. builder.append(' ');
  1333. first = false;
  1334. builder.append(name);
  1335. }
  1336. builder.append("))");
  1337. } else {
  1338. builder.append(')');
  1339. }
  1340. print_indented(builder.string_view(), level + 2);
  1341. for (auto& node : entry.options)
  1342. node.dump(level + 3);
  1343. print_indented("(execute)", level + 2);
  1344. if (entry.body)
  1345. entry.body->dump(level + 3);
  1346. else
  1347. print_indented("(nothing)", level + 3);
  1348. }
  1349. }
  1350. RefPtr<Value> MatchExpr::run(RefPtr<Shell> shell)
  1351. {
  1352. auto value = m_matched_expr->run(shell)->resolve_without_cast(shell);
  1353. auto list = value->resolve_as_list(shell);
  1354. auto list_matches = [&](auto&& pattern, auto& spans) {
  1355. if (pattern.size() != list.size())
  1356. return false;
  1357. for (size_t i = 0; i < pattern.size(); ++i) {
  1358. Vector<AK::MaskSpan> mask_spans;
  1359. if (!list[i].matches(pattern[i], mask_spans))
  1360. return false;
  1361. for (auto& span : mask_spans)
  1362. spans.append(list[i].substring(span.start, span.length));
  1363. }
  1364. return true;
  1365. };
  1366. auto resolve_pattern = [&](auto& option) {
  1367. Vector<String> pattern;
  1368. if (option.is_glob()) {
  1369. pattern.append(static_cast<const Glob*>(&option)->text());
  1370. } else if (option.is_bareword()) {
  1371. pattern.append(static_cast<const BarewordLiteral*>(&option)->text());
  1372. } else {
  1373. auto list = option.run(shell);
  1374. option.for_each_entry(shell, [&](auto&& value) {
  1375. pattern.append(value->resolve_as_list(nullptr)); // Note: 'nullptr' incurs special behaviour,
  1376. // asking the node for a 'raw' value.
  1377. return IterationDecision::Continue;
  1378. });
  1379. }
  1380. return pattern;
  1381. };
  1382. auto frame = shell->push_frame(String::formatted("match ({})", this));
  1383. if (!m_expr_name.is_empty())
  1384. shell->set_local_variable(m_expr_name, value, true);
  1385. for (auto& entry : m_entries) {
  1386. for (auto& option : entry.options) {
  1387. Vector<String> spans;
  1388. if (list_matches(resolve_pattern(option), spans)) {
  1389. if (entry.body) {
  1390. if (entry.match_names.has_value()) {
  1391. size_t i = 0;
  1392. for (auto& name : entry.match_names.value()) {
  1393. if (spans.size() > i)
  1394. shell->set_local_variable(name, create<AST::StringValue>(spans[i]), true);
  1395. ++i;
  1396. }
  1397. }
  1398. return entry.body->run(shell);
  1399. } else {
  1400. return create<AST::ListValue>({});
  1401. }
  1402. }
  1403. }
  1404. }
  1405. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Non-exhaustive match rules!", position());
  1406. return create<AST::ListValue>({});
  1407. }
  1408. void MatchExpr::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1409. {
  1410. editor.stylize({ m_position.start_offset, m_position.start_offset + 5 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1411. if (m_as_position.has_value())
  1412. editor.stylize({ m_as_position.value().start_offset, m_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1413. metadata.is_first_in_list = false;
  1414. m_matched_expr->highlight_in_editor(editor, shell, metadata);
  1415. for (auto& entry : m_entries) {
  1416. metadata.is_first_in_list = false;
  1417. for (auto& option : entry.options)
  1418. option.highlight_in_editor(editor, shell, metadata);
  1419. metadata.is_first_in_list = true;
  1420. if (entry.body)
  1421. entry.body->highlight_in_editor(editor, shell, metadata);
  1422. for (auto& position : entry.pipe_positions)
  1423. editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1424. if (entry.match_as_position.has_value())
  1425. editor.stylize({ entry.match_as_position.value().start_offset, entry.match_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1426. }
  1427. }
  1428. HitTestResult MatchExpr::hit_test_position(size_t offset)
  1429. {
  1430. if (!position().contains(offset))
  1431. return {};
  1432. auto result = m_matched_expr->hit_test_position(offset);
  1433. if (result.matching_node)
  1434. return result;
  1435. for (auto& entry : m_entries) {
  1436. if (!entry.body)
  1437. continue;
  1438. auto result = entry.body->hit_test_position(offset);
  1439. if (result.matching_node)
  1440. return result;
  1441. }
  1442. return {};
  1443. }
  1444. MatchExpr::MatchExpr(Position position, NonnullRefPtr<Node> expr, String name, Optional<Position> as_position, Vector<MatchEntry> entries)
  1445. : Node(move(position))
  1446. , m_matched_expr(move(expr))
  1447. , m_expr_name(move(name))
  1448. , m_as_position(move(as_position))
  1449. , m_entries(move(entries))
  1450. {
  1451. if (m_matched_expr->is_syntax_error()) {
  1452. set_is_syntax_error(m_matched_expr->syntax_error_node());
  1453. } else {
  1454. for (auto& entry : m_entries) {
  1455. if (!entry.body)
  1456. continue;
  1457. if (entry.body->is_syntax_error()) {
  1458. set_is_syntax_error(entry.body->syntax_error_node());
  1459. break;
  1460. }
  1461. }
  1462. }
  1463. }
  1464. MatchExpr::~MatchExpr()
  1465. {
  1466. }
  1467. void Or::dump(int level) const
  1468. {
  1469. Node::dump(level);
  1470. m_left->dump(level + 1);
  1471. m_right->dump(level + 1);
  1472. }
  1473. RefPtr<Value> Or::run(RefPtr<Shell> shell)
  1474. {
  1475. auto commands = m_left->to_lazy_evaluated_commands(shell);
  1476. commands.last().next_chain.empend(*m_right, NodeWithAction::Or);
  1477. return create<CommandSequenceValue>(move(commands));
  1478. }
  1479. void Or::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1480. {
  1481. m_left->highlight_in_editor(editor, shell, metadata);
  1482. m_right->highlight_in_editor(editor, shell, metadata);
  1483. }
  1484. HitTestResult Or::hit_test_position(size_t offset)
  1485. {
  1486. if (!position().contains(offset))
  1487. return {};
  1488. auto result = m_left->hit_test_position(offset);
  1489. if (result.matching_node) {
  1490. if (!result.closest_command_node)
  1491. result.closest_command_node = m_right;
  1492. return result;
  1493. }
  1494. result = m_right->hit_test_position(offset);
  1495. if (!result.closest_command_node)
  1496. result.closest_command_node = m_right;
  1497. return result;
  1498. }
  1499. Or::Or(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position or_position)
  1500. : Node(move(position))
  1501. , m_left(move(left))
  1502. , m_right(move(right))
  1503. , m_or_position(or_position)
  1504. {
  1505. if (m_left->is_syntax_error())
  1506. set_is_syntax_error(m_left->syntax_error_node());
  1507. else if (m_right->is_syntax_error())
  1508. set_is_syntax_error(m_right->syntax_error_node());
  1509. }
  1510. Or::~Or()
  1511. {
  1512. }
  1513. void Pipe::dump(int level) const
  1514. {
  1515. Node::dump(level);
  1516. m_left->dump(level + 1);
  1517. m_right->dump(level + 1);
  1518. }
  1519. RefPtr<Value> Pipe::run(RefPtr<Shell> shell)
  1520. {
  1521. auto left = m_left->to_lazy_evaluated_commands(shell);
  1522. auto right = m_right->to_lazy_evaluated_commands(shell);
  1523. auto last_in_left = left.take_last();
  1524. auto first_in_right = right.take_first();
  1525. auto pipe_read_end = FdRedirection::create(-1, STDIN_FILENO, Rewiring::Close::Old);
  1526. auto pipe_write_end = FdRedirection::create(-1, STDOUT_FILENO, pipe_read_end, Rewiring::Close::RefreshOld);
  1527. first_in_right.redirections.append(pipe_read_end);
  1528. last_in_left.redirections.append(pipe_write_end);
  1529. last_in_left.should_wait = false;
  1530. last_in_left.is_pipe_source = true;
  1531. if (first_in_right.pipeline) {
  1532. last_in_left.pipeline = first_in_right.pipeline;
  1533. } else {
  1534. auto pipeline = create<Pipeline>();
  1535. last_in_left.pipeline = pipeline;
  1536. first_in_right.pipeline = pipeline;
  1537. }
  1538. Vector<Command> commands;
  1539. commands.append(left);
  1540. commands.append(last_in_left);
  1541. commands.append(first_in_right);
  1542. commands.append(right);
  1543. return create<CommandSequenceValue>(move(commands));
  1544. }
  1545. void Pipe::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1546. {
  1547. m_left->highlight_in_editor(editor, shell, metadata);
  1548. m_right->highlight_in_editor(editor, shell, metadata);
  1549. }
  1550. HitTestResult Pipe::hit_test_position(size_t offset)
  1551. {
  1552. if (!position().contains(offset))
  1553. return {};
  1554. auto result = m_left->hit_test_position(offset);
  1555. if (result.matching_node) {
  1556. if (!result.closest_command_node)
  1557. result.closest_command_node = m_right;
  1558. return result;
  1559. }
  1560. result = m_right->hit_test_position(offset);
  1561. if (!result.closest_command_node)
  1562. result.closest_command_node = m_right;
  1563. return result;
  1564. }
  1565. Pipe::Pipe(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  1566. : Node(move(position))
  1567. , m_left(move(left))
  1568. , m_right(move(right))
  1569. {
  1570. if (m_left->is_syntax_error())
  1571. set_is_syntax_error(m_left->syntax_error_node());
  1572. else if (m_right->is_syntax_error())
  1573. set_is_syntax_error(m_right->syntax_error_node());
  1574. }
  1575. Pipe::~Pipe()
  1576. {
  1577. }
  1578. PathRedirectionNode::PathRedirectionNode(Position position, int fd, NonnullRefPtr<Node> path)
  1579. : Node(move(position))
  1580. , m_fd(fd)
  1581. , m_path(move(path))
  1582. {
  1583. }
  1584. void PathRedirectionNode::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1585. {
  1586. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  1587. metadata.is_first_in_list = false;
  1588. m_path->highlight_in_editor(editor, shell, metadata);
  1589. if (m_path->is_bareword()) {
  1590. auto path_text = m_path->run(nullptr)->resolve_as_list(nullptr);
  1591. ASSERT(path_text.size() == 1);
  1592. // Apply a URL to the path.
  1593. auto& position = m_path->position();
  1594. auto& path = path_text[0];
  1595. if (!path.starts_with('/'))
  1596. path = String::format("%s/%s", shell.cwd.characters(), path.characters());
  1597. auto url = URL::create_with_file_protocol(path);
  1598. url.set_host(shell.hostname);
  1599. editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  1600. }
  1601. }
  1602. HitTestResult PathRedirectionNode::hit_test_position(size_t offset)
  1603. {
  1604. if (!position().contains(offset))
  1605. return {};
  1606. auto result = m_path->hit_test_position(offset);
  1607. if (!result.closest_node_with_semantic_meaning)
  1608. result.closest_node_with_semantic_meaning = this;
  1609. return result;
  1610. }
  1611. Vector<Line::CompletionSuggestion> PathRedirectionNode::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1612. {
  1613. auto matching_node = hit_test_result.matching_node;
  1614. if (!matching_node || !matching_node->is_bareword())
  1615. return {};
  1616. auto corrected_offset = offset - matching_node->position().start_offset;
  1617. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  1618. if (corrected_offset > node->text().length())
  1619. return {};
  1620. return shell.complete_path("", node->text(), corrected_offset);
  1621. }
  1622. PathRedirectionNode::~PathRedirectionNode()
  1623. {
  1624. }
  1625. void Range::dump(int level) const
  1626. {
  1627. Node::dump(level);
  1628. print_indented("(From)", level + 1);
  1629. m_start->dump(level + 2);
  1630. print_indented("(To)", level + 1);
  1631. m_end->dump(level + 2);
  1632. }
  1633. RefPtr<Value> Range::run(RefPtr<Shell> shell)
  1634. {
  1635. auto interpolate = [position = position()](RefPtr<Value> start, RefPtr<Value> end, RefPtr<Shell> shell) -> NonnullRefPtrVector<Value> {
  1636. NonnullRefPtrVector<Value> values;
  1637. if (start->is_string() && end->is_string()) {
  1638. auto start_str = start->resolve_as_list(shell)[0];
  1639. auto end_str = end->resolve_as_list(shell)[0];
  1640. Utf8View start_view { start_str }, end_view { end_str };
  1641. if (start_view.validate() && end_view.validate()) {
  1642. if (start_view.length() == 1 && end_view.length() == 1) {
  1643. // Interpolate between two code points.
  1644. auto start_code_point = *start_view.begin();
  1645. auto end_code_point = *end_view.begin();
  1646. auto step = start_code_point > end_code_point ? -1 : 1;
  1647. StringBuilder builder;
  1648. for (u32 code_point = start_code_point; code_point != end_code_point; code_point += step) {
  1649. builder.clear();
  1650. builder.append_code_point(code_point);
  1651. values.append(create<StringValue>(builder.to_string()));
  1652. }
  1653. // Append the ending code point too, most shells treat this as inclusive.
  1654. builder.clear();
  1655. builder.append_code_point(end_code_point);
  1656. values.append(create<StringValue>(builder.to_string()));
  1657. } else {
  1658. // Could be two numbers?
  1659. auto start_int = start_str.to_int();
  1660. auto end_int = end_str.to_int();
  1661. if (start_int.has_value() && end_int.has_value()) {
  1662. auto start = start_int.value();
  1663. auto end = end_int.value();
  1664. auto step = start > end ? -1 : 1;
  1665. for (int value = start; value != end; value += step)
  1666. values.append(create<StringValue>(String::number(value)));
  1667. // Append the range end too, most shells treat this as inclusive.
  1668. values.append(create<StringValue>(String::number(end)));
  1669. } else {
  1670. goto yield_start_end;
  1671. }
  1672. }
  1673. } else {
  1674. yield_start_end:;
  1675. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, String::formatted("Cannot interpolate between '{}' and '{}'!", start_str, end_str), position);
  1676. // We can't really interpolate between the two, so just yield both.
  1677. values.append(create<StringValue>(move(start_str)));
  1678. values.append(create<StringValue>(move(end_str)));
  1679. }
  1680. return values;
  1681. }
  1682. warnln("Shell: Cannot apply the requested interpolation");
  1683. return values;
  1684. };
  1685. auto start_value = m_start->run(shell);
  1686. auto end_value = m_end->run(shell);
  1687. if (!start_value || !end_value)
  1688. return create<ListValue>({});
  1689. return create<ListValue>(interpolate(*start_value, *end_value, shell));
  1690. }
  1691. void Range::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1692. {
  1693. m_start->highlight_in_editor(editor, shell, metadata);
  1694. // Highlight the '..'
  1695. editor.stylize({ m_start->position().end_offset, m_end->position().start_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1696. metadata.is_first_in_list = false;
  1697. m_end->highlight_in_editor(editor, shell, metadata);
  1698. }
  1699. HitTestResult Range::hit_test_position(size_t offset)
  1700. {
  1701. if (!position().contains(offset))
  1702. return {};
  1703. auto result = m_start->hit_test_position(offset);
  1704. if (result.matching_node) {
  1705. if (!result.closest_command_node)
  1706. result.closest_command_node = m_start;
  1707. return result;
  1708. }
  1709. result = m_end->hit_test_position(offset);
  1710. if (!result.closest_command_node)
  1711. result.closest_command_node = m_end;
  1712. return result;
  1713. }
  1714. Range::Range(Position position, NonnullRefPtr<Node> start, NonnullRefPtr<Node> end)
  1715. : Node(move(position))
  1716. , m_start(move(start))
  1717. , m_end(move(end))
  1718. {
  1719. if (m_start->is_syntax_error())
  1720. set_is_syntax_error(m_start->syntax_error_node());
  1721. else if (m_end->is_syntax_error())
  1722. set_is_syntax_error(m_end->syntax_error_node());
  1723. }
  1724. Range::~Range()
  1725. {
  1726. }
  1727. void ReadRedirection::dump(int level) const
  1728. {
  1729. Node::dump(level);
  1730. m_path->dump(level + 1);
  1731. print_indented(String::format("To %d", m_fd), level + 1);
  1732. }
  1733. RefPtr<Value> ReadRedirection::run(RefPtr<Shell> shell)
  1734. {
  1735. Command command;
  1736. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1737. StringBuilder builder;
  1738. builder.join(" ", path_segments);
  1739. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Read));
  1740. return create<CommandValue>(move(command));
  1741. }
  1742. ReadRedirection::ReadRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  1743. : PathRedirectionNode(move(position), fd, move(path))
  1744. {
  1745. }
  1746. ReadRedirection::~ReadRedirection()
  1747. {
  1748. }
  1749. void ReadWriteRedirection::dump(int level) const
  1750. {
  1751. Node::dump(level);
  1752. m_path->dump(level + 1);
  1753. print_indented(String::format("To/From %d", m_fd), level + 1);
  1754. }
  1755. RefPtr<Value> ReadWriteRedirection::run(RefPtr<Shell> shell)
  1756. {
  1757. Command command;
  1758. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1759. StringBuilder builder;
  1760. builder.join(" ", path_segments);
  1761. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::ReadWrite));
  1762. return create<CommandValue>(move(command));
  1763. }
  1764. ReadWriteRedirection::ReadWriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  1765. : PathRedirectionNode(move(position), fd, move(path))
  1766. {
  1767. }
  1768. ReadWriteRedirection::~ReadWriteRedirection()
  1769. {
  1770. }
  1771. void Sequence::dump(int level) const
  1772. {
  1773. Node::dump(level);
  1774. m_left->dump(level + 1);
  1775. m_right->dump(level + 1);
  1776. }
  1777. RefPtr<Value> Sequence::run(RefPtr<Shell> shell)
  1778. {
  1779. auto left = m_left->to_lazy_evaluated_commands(shell);
  1780. // This could happen if a comment is next to a command.
  1781. if (left.size() == 1) {
  1782. auto& command = left.first();
  1783. if (command.argv.is_empty() && command.redirections.is_empty() && command.next_chain.is_empty())
  1784. return m_right->run(shell);
  1785. }
  1786. if (left.last().should_wait)
  1787. left.last().next_chain.append(NodeWithAction { *m_right, NodeWithAction::Sequence });
  1788. else
  1789. left.append(m_right->to_lazy_evaluated_commands(shell));
  1790. return create<CommandSequenceValue>(move(left));
  1791. }
  1792. void Sequence::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1793. {
  1794. m_left->highlight_in_editor(editor, shell, metadata);
  1795. m_right->highlight_in_editor(editor, shell, metadata);
  1796. }
  1797. HitTestResult Sequence::hit_test_position(size_t offset)
  1798. {
  1799. if (!position().contains(offset))
  1800. return {};
  1801. auto result = m_left->hit_test_position(offset);
  1802. if (result.matching_node) {
  1803. if (!result.closest_command_node)
  1804. result.closest_command_node = m_right;
  1805. return result;
  1806. }
  1807. result = m_right->hit_test_position(offset);
  1808. if (!result.closest_command_node)
  1809. result.closest_command_node = m_right;
  1810. return result;
  1811. }
  1812. Sequence::Sequence(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position separator_position)
  1813. : Node(move(position))
  1814. , m_left(move(left))
  1815. , m_right(move(right))
  1816. , m_separator_position(separator_position)
  1817. {
  1818. if (m_left->is_syntax_error())
  1819. set_is_syntax_error(m_left->syntax_error_node());
  1820. else if (m_right->is_syntax_error())
  1821. set_is_syntax_error(m_right->syntax_error_node());
  1822. }
  1823. Sequence::~Sequence()
  1824. {
  1825. }
  1826. void Subshell::dump(int level) const
  1827. {
  1828. Node::dump(level);
  1829. if (m_block)
  1830. m_block->dump(level + 1);
  1831. }
  1832. RefPtr<Value> Subshell::run(RefPtr<Shell> shell)
  1833. {
  1834. if (!m_block)
  1835. return create<ListValue>({});
  1836. return create<AST::CommandSequenceValue>(m_block->to_lazy_evaluated_commands(shell));
  1837. }
  1838. void Subshell::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1839. {
  1840. metadata.is_first_in_list = true;
  1841. if (m_block)
  1842. m_block->highlight_in_editor(editor, shell, metadata);
  1843. }
  1844. HitTestResult Subshell::hit_test_position(size_t offset)
  1845. {
  1846. if (!position().contains(offset))
  1847. return {};
  1848. if (m_block)
  1849. return m_block->hit_test_position(offset);
  1850. return {};
  1851. }
  1852. Subshell::Subshell(Position position, RefPtr<Node> block)
  1853. : Node(move(position))
  1854. , m_block(block)
  1855. {
  1856. if (m_block && m_block->is_syntax_error())
  1857. set_is_syntax_error(m_block->syntax_error_node());
  1858. }
  1859. Subshell::~Subshell()
  1860. {
  1861. }
  1862. void SimpleVariable::dump(int level) const
  1863. {
  1864. Node::dump(level);
  1865. print_indented(m_name, level + 1);
  1866. }
  1867. RefPtr<Value> SimpleVariable::run(RefPtr<Shell>)
  1868. {
  1869. return create<SimpleVariableValue>(m_name);
  1870. }
  1871. void SimpleVariable::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  1872. {
  1873. Line::Style style { Line::Style::Foreground(214, 112, 214) };
  1874. if (metadata.is_first_in_list)
  1875. style.unify_with({ Line::Style::Bold });
  1876. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  1877. }
  1878. HitTestResult SimpleVariable::hit_test_position(size_t offset)
  1879. {
  1880. if (!position().contains(offset))
  1881. return {};
  1882. return { this, this, nullptr };
  1883. }
  1884. Vector<Line::CompletionSuggestion> SimpleVariable::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1885. {
  1886. auto matching_node = hit_test_result.matching_node;
  1887. if (!matching_node)
  1888. return {};
  1889. if (matching_node != this)
  1890. return {};
  1891. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  1892. if (corrected_offset > m_name.length() + 1)
  1893. return {};
  1894. return shell.complete_variable(m_name, corrected_offset);
  1895. }
  1896. SimpleVariable::SimpleVariable(Position position, String name)
  1897. : Node(move(position))
  1898. , m_name(move(name))
  1899. {
  1900. }
  1901. SimpleVariable::~SimpleVariable()
  1902. {
  1903. }
  1904. void SpecialVariable::dump(int level) const
  1905. {
  1906. Node::dump(level);
  1907. print_indented(String { &m_name, 1 }, level + 1);
  1908. }
  1909. RefPtr<Value> SpecialVariable::run(RefPtr<Shell>)
  1910. {
  1911. return create<SpecialVariableValue>(m_name);
  1912. }
  1913. void SpecialVariable::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  1914. {
  1915. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(214, 112, 214) });
  1916. }
  1917. Vector<Line::CompletionSuggestion> SpecialVariable::complete_for_editor(Shell&, size_t, const HitTestResult&)
  1918. {
  1919. return {};
  1920. }
  1921. HitTestResult SpecialVariable::hit_test_position(size_t offset)
  1922. {
  1923. if (!position().contains(offset))
  1924. return {};
  1925. return { this, this, nullptr };
  1926. }
  1927. SpecialVariable::SpecialVariable(Position position, char name)
  1928. : Node(move(position))
  1929. , m_name(name)
  1930. {
  1931. }
  1932. SpecialVariable::~SpecialVariable()
  1933. {
  1934. }
  1935. void Juxtaposition::dump(int level) const
  1936. {
  1937. Node::dump(level);
  1938. m_left->dump(level + 1);
  1939. m_right->dump(level + 1);
  1940. }
  1941. RefPtr<Value> Juxtaposition::run(RefPtr<Shell> shell)
  1942. {
  1943. auto left_value = m_left->run(shell)->resolve_without_cast(shell);
  1944. auto right_value = m_right->run(shell)->resolve_without_cast(shell);
  1945. auto left = left_value->resolve_as_list(shell);
  1946. auto right = right_value->resolve_as_list(shell);
  1947. if (left_value->is_string() && right_value->is_string()) {
  1948. ASSERT(left.size() == 1);
  1949. ASSERT(right.size() == 1);
  1950. StringBuilder builder;
  1951. builder.append(left[0]);
  1952. builder.append(right[0]);
  1953. return create<StringValue>(builder.to_string());
  1954. }
  1955. // Otherwise, treat them as lists and create a list product.
  1956. if (left.is_empty() || right.is_empty())
  1957. return create<ListValue>({});
  1958. Vector<String> result;
  1959. result.ensure_capacity(left.size() * right.size());
  1960. StringBuilder builder;
  1961. for (auto& left_element : left) {
  1962. for (auto& right_element : right) {
  1963. builder.append(left_element);
  1964. builder.append(right_element);
  1965. result.append(builder.to_string());
  1966. builder.clear();
  1967. }
  1968. }
  1969. return create<ListValue>(move(result));
  1970. }
  1971. void Juxtaposition::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1972. {
  1973. m_left->highlight_in_editor(editor, shell, metadata);
  1974. // '~/foo/bar' is special, we have to actually resolve the tilde
  1975. // since that resolution is a pure operation, we can just go ahead
  1976. // and do it to get the value :)
  1977. if (m_right->is_bareword() && m_left->is_tilde()) {
  1978. auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
  1979. auto bareword_value = m_right->run(shell)->resolve_as_list(shell)[0];
  1980. StringBuilder path_builder;
  1981. path_builder.append(tilde_value);
  1982. path_builder.append("/");
  1983. path_builder.append(bareword_value);
  1984. auto path = path_builder.to_string();
  1985. if (Core::File::exists(path)) {
  1986. auto realpath = shell.resolve_path(path);
  1987. auto url = URL::create_with_file_protocol(realpath);
  1988. url.set_host(shell.hostname);
  1989. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  1990. }
  1991. } else {
  1992. m_right->highlight_in_editor(editor, shell, metadata);
  1993. }
  1994. }
  1995. Vector<Line::CompletionSuggestion> Juxtaposition::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1996. {
  1997. auto matching_node = hit_test_result.matching_node;
  1998. // '~/foo/bar' is special, we have to actually resolve the tilde
  1999. // then complete the bareword with that path prefix.
  2000. if (m_right->is_bareword() && m_left->is_tilde()) {
  2001. auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
  2002. auto corrected_offset = offset - matching_node->position().start_offset;
  2003. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  2004. if (corrected_offset > node->text().length())
  2005. return {};
  2006. auto text = node->text().substring(1, node->text().length() - 1);
  2007. return shell.complete_path(tilde_value, text, corrected_offset - 1);
  2008. }
  2009. return Node::complete_for_editor(shell, offset, hit_test_result);
  2010. }
  2011. HitTestResult Juxtaposition::hit_test_position(size_t offset)
  2012. {
  2013. if (!position().contains(offset))
  2014. return {};
  2015. auto result = m_left->hit_test_position(offset);
  2016. if (!result.closest_node_with_semantic_meaning)
  2017. result.closest_node_with_semantic_meaning = this;
  2018. if (result.matching_node)
  2019. return result;
  2020. result = m_right->hit_test_position(offset);
  2021. if (!result.closest_node_with_semantic_meaning)
  2022. result.closest_node_with_semantic_meaning = this;
  2023. return result;
  2024. }
  2025. Juxtaposition::Juxtaposition(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  2026. : Node(move(position))
  2027. , m_left(move(left))
  2028. , m_right(move(right))
  2029. {
  2030. if (m_left->is_syntax_error())
  2031. set_is_syntax_error(m_left->syntax_error_node());
  2032. else if (m_right->is_syntax_error())
  2033. set_is_syntax_error(m_right->syntax_error_node());
  2034. }
  2035. Juxtaposition::~Juxtaposition()
  2036. {
  2037. }
  2038. void StringLiteral::dump(int level) const
  2039. {
  2040. Node::dump(level);
  2041. print_indented(m_text, level + 1);
  2042. }
  2043. RefPtr<Value> StringLiteral::run(RefPtr<Shell>)
  2044. {
  2045. return create<StringValue>(m_text);
  2046. }
  2047. void StringLiteral::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  2048. {
  2049. if (m_text.is_empty())
  2050. return;
  2051. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  2052. if (metadata.is_first_in_list)
  2053. style.unify_with({ Line::Style::Bold });
  2054. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  2055. }
  2056. StringLiteral::StringLiteral(Position position, String text)
  2057. : Node(move(position))
  2058. , m_text(move(text))
  2059. {
  2060. }
  2061. StringLiteral::~StringLiteral()
  2062. {
  2063. }
  2064. void StringPartCompose::dump(int level) const
  2065. {
  2066. Node::dump(level);
  2067. m_left->dump(level + 1);
  2068. m_right->dump(level + 1);
  2069. }
  2070. RefPtr<Value> StringPartCompose::run(RefPtr<Shell> shell)
  2071. {
  2072. auto left = m_left->run(shell)->resolve_as_list(shell);
  2073. auto right = m_right->run(shell)->resolve_as_list(shell);
  2074. StringBuilder builder;
  2075. builder.join(" ", left);
  2076. builder.join(" ", right);
  2077. return create<StringValue>(builder.to_string());
  2078. }
  2079. void StringPartCompose::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2080. {
  2081. m_left->highlight_in_editor(editor, shell, metadata);
  2082. m_right->highlight_in_editor(editor, shell, metadata);
  2083. }
  2084. HitTestResult StringPartCompose::hit_test_position(size_t offset)
  2085. {
  2086. if (!position().contains(offset))
  2087. return {};
  2088. auto result = m_left->hit_test_position(offset);
  2089. if (result.matching_node)
  2090. return result;
  2091. return m_right->hit_test_position(offset);
  2092. }
  2093. StringPartCompose::StringPartCompose(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  2094. : Node(move(position))
  2095. , m_left(move(left))
  2096. , m_right(move(right))
  2097. {
  2098. if (m_left->is_syntax_error())
  2099. set_is_syntax_error(m_left->syntax_error_node());
  2100. else if (m_right->is_syntax_error())
  2101. set_is_syntax_error(m_right->syntax_error_node());
  2102. }
  2103. StringPartCompose::~StringPartCompose()
  2104. {
  2105. }
  2106. void SyntaxError::dump(int level) const
  2107. {
  2108. Node::dump(level);
  2109. print_indented("(Error text)", level + 1);
  2110. print_indented(m_syntax_error_text, level + 2);
  2111. print_indented("(Can be recovered from)", level + 1);
  2112. print_indented(String::formatted("{}", m_is_continuable), level + 2);
  2113. }
  2114. RefPtr<Value> SyntaxError::run(RefPtr<Shell> shell)
  2115. {
  2116. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, m_syntax_error_text, position());
  2117. return create<StringValue>("");
  2118. }
  2119. void SyntaxError::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  2120. {
  2121. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Bold });
  2122. }
  2123. SyntaxError::SyntaxError(Position position, String error, bool is_continuable)
  2124. : Node(move(position))
  2125. , m_syntax_error_text(move(error))
  2126. , m_is_continuable(is_continuable)
  2127. {
  2128. m_is_syntax_error = true;
  2129. }
  2130. const SyntaxError& SyntaxError::syntax_error_node() const
  2131. {
  2132. return *this;
  2133. }
  2134. SyntaxError::~SyntaxError()
  2135. {
  2136. }
  2137. void Tilde::dump(int level) const
  2138. {
  2139. Node::dump(level);
  2140. print_indented(m_username, level + 1);
  2141. }
  2142. RefPtr<Value> Tilde::run(RefPtr<Shell>)
  2143. {
  2144. return create<TildeValue>(m_username);
  2145. }
  2146. void Tilde::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
  2147. {
  2148. }
  2149. HitTestResult Tilde::hit_test_position(size_t offset)
  2150. {
  2151. if (!position().contains(offset))
  2152. return {};
  2153. return { this, this, nullptr };
  2154. }
  2155. Vector<Line::CompletionSuggestion> Tilde::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  2156. {
  2157. auto matching_node = hit_test_result.matching_node;
  2158. if (!matching_node)
  2159. return {};
  2160. if (matching_node != this)
  2161. return {};
  2162. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  2163. if (corrected_offset > m_username.length() + 1)
  2164. return {};
  2165. return shell.complete_user(m_username, corrected_offset);
  2166. }
  2167. String Tilde::text() const
  2168. {
  2169. StringBuilder builder;
  2170. builder.append('~');
  2171. builder.append(m_username);
  2172. return builder.to_string();
  2173. }
  2174. Tilde::Tilde(Position position, String username)
  2175. : Node(move(position))
  2176. , m_username(move(username))
  2177. {
  2178. }
  2179. Tilde::~Tilde()
  2180. {
  2181. }
  2182. void WriteAppendRedirection::dump(int level) const
  2183. {
  2184. Node::dump(level);
  2185. m_path->dump(level + 1);
  2186. print_indented(String::format("From %d", m_fd), level + 1);
  2187. }
  2188. RefPtr<Value> WriteAppendRedirection::run(RefPtr<Shell> shell)
  2189. {
  2190. Command command;
  2191. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2192. StringBuilder builder;
  2193. builder.join(" ", path_segments);
  2194. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::WriteAppend));
  2195. return create<CommandValue>(move(command));
  2196. }
  2197. WriteAppendRedirection::WriteAppendRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2198. : PathRedirectionNode(move(position), fd, move(path))
  2199. {
  2200. }
  2201. WriteAppendRedirection::~WriteAppendRedirection()
  2202. {
  2203. }
  2204. void WriteRedirection::dump(int level) const
  2205. {
  2206. Node::dump(level);
  2207. m_path->dump(level + 1);
  2208. print_indented(String::format("From %d", m_fd), level + 1);
  2209. }
  2210. RefPtr<Value> WriteRedirection::run(RefPtr<Shell> shell)
  2211. {
  2212. Command command;
  2213. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2214. StringBuilder builder;
  2215. builder.join(" ", path_segments);
  2216. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Write));
  2217. return create<CommandValue>(move(command));
  2218. }
  2219. WriteRedirection::WriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2220. : PathRedirectionNode(move(position), fd, move(path))
  2221. {
  2222. }
  2223. WriteRedirection::~WriteRedirection()
  2224. {
  2225. }
  2226. void VariableDeclarations::dump(int level) const
  2227. {
  2228. Node::dump(level);
  2229. for (auto& var : m_variables) {
  2230. print_indented("Set", level + 1);
  2231. var.name->dump(level + 2);
  2232. var.value->dump(level + 2);
  2233. }
  2234. }
  2235. RefPtr<Value> VariableDeclarations::run(RefPtr<Shell> shell)
  2236. {
  2237. for (auto& var : m_variables) {
  2238. auto name_value = var.name->run(shell)->resolve_as_list(shell);
  2239. ASSERT(name_value.size() == 1);
  2240. auto name = name_value[0];
  2241. auto value = var.value->run(shell);
  2242. if (value->is_list()) {
  2243. auto parts = value->resolve_as_list(shell);
  2244. shell->set_local_variable(name, adopt(*new ListValue(move(parts))));
  2245. } else if (value->is_command()) {
  2246. shell->set_local_variable(name, value);
  2247. } else {
  2248. auto part = value->resolve_as_list(shell);
  2249. shell->set_local_variable(name, adopt(*new StringValue(part[0])));
  2250. }
  2251. }
  2252. return create<ListValue>({});
  2253. }
  2254. void VariableDeclarations::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2255. {
  2256. metadata.is_first_in_list = false;
  2257. for (auto& var : m_variables) {
  2258. var.name->highlight_in_editor(editor, shell, metadata);
  2259. // Highlight the '='.
  2260. editor.stylize({ var.name->position().end_offset - 1, var.name->position().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
  2261. var.value->highlight_in_editor(editor, shell, metadata);
  2262. }
  2263. }
  2264. HitTestResult VariableDeclarations::hit_test_position(size_t offset)
  2265. {
  2266. if (!position().contains(offset))
  2267. return {};
  2268. for (auto decl : m_variables) {
  2269. auto result = decl.value->hit_test_position(offset);
  2270. if (result.matching_node)
  2271. return result;
  2272. }
  2273. return { nullptr, nullptr, nullptr };
  2274. }
  2275. VariableDeclarations::VariableDeclarations(Position position, Vector<Variable> variables)
  2276. : Node(move(position))
  2277. , m_variables(move(variables))
  2278. {
  2279. for (auto& decl : m_variables) {
  2280. if (decl.name->is_syntax_error()) {
  2281. set_is_syntax_error(decl.name->syntax_error_node());
  2282. break;
  2283. }
  2284. if (decl.value->is_syntax_error()) {
  2285. set_is_syntax_error(decl.value->syntax_error_node());
  2286. break;
  2287. }
  2288. }
  2289. }
  2290. VariableDeclarations::~VariableDeclarations()
  2291. {
  2292. }
  2293. Value::~Value()
  2294. {
  2295. }
  2296. Vector<AST::Command> Value::resolve_as_commands(RefPtr<Shell> shell)
  2297. {
  2298. Command command;
  2299. command.argv = resolve_as_list(shell);
  2300. return { command };
  2301. }
  2302. ListValue::ListValue(Vector<String> values)
  2303. {
  2304. m_contained_values.ensure_capacity(values.size());
  2305. for (auto& str : values)
  2306. m_contained_values.append(adopt(*new StringValue(move(str))));
  2307. }
  2308. ListValue::~ListValue()
  2309. {
  2310. }
  2311. Vector<String> ListValue::resolve_as_list(RefPtr<Shell> shell)
  2312. {
  2313. Vector<String> values;
  2314. for (auto& value : m_contained_values)
  2315. values.append(value.resolve_as_list(shell));
  2316. return values;
  2317. }
  2318. NonnullRefPtr<Value> ListValue::resolve_without_cast(RefPtr<Shell> shell)
  2319. {
  2320. NonnullRefPtrVector<Value> values;
  2321. for (auto& value : m_contained_values)
  2322. values.append(value.resolve_without_cast(shell));
  2323. return create<ListValue>(move(values));
  2324. }
  2325. CommandValue::~CommandValue()
  2326. {
  2327. }
  2328. CommandSequenceValue::~CommandSequenceValue()
  2329. {
  2330. }
  2331. Vector<String> CommandSequenceValue::resolve_as_list(RefPtr<Shell>)
  2332. {
  2333. // TODO: Somehow raise an "error".
  2334. return {};
  2335. }
  2336. Vector<Command> CommandSequenceValue::resolve_as_commands(RefPtr<Shell>)
  2337. {
  2338. return m_contained_values;
  2339. }
  2340. Vector<String> CommandValue::resolve_as_list(RefPtr<Shell>)
  2341. {
  2342. // TODO: Somehow raise an "error".
  2343. return {};
  2344. }
  2345. Vector<Command> CommandValue::resolve_as_commands(RefPtr<Shell>)
  2346. {
  2347. return { m_command };
  2348. }
  2349. JobValue::~JobValue()
  2350. {
  2351. }
  2352. StringValue::~StringValue()
  2353. {
  2354. }
  2355. Vector<String> StringValue::resolve_as_list(RefPtr<Shell>)
  2356. {
  2357. if (is_list()) {
  2358. auto parts = StringView(m_string).split_view(m_split, m_keep_empty);
  2359. Vector<String> result;
  2360. result.ensure_capacity(parts.size());
  2361. for (auto& part : parts)
  2362. result.append(part);
  2363. return result;
  2364. }
  2365. return { m_string };
  2366. }
  2367. GlobValue::~GlobValue()
  2368. {
  2369. }
  2370. Vector<String> GlobValue::resolve_as_list(RefPtr<Shell> shell)
  2371. {
  2372. if (!shell)
  2373. return { m_glob };
  2374. auto results = shell->expand_globs(m_glob, shell->cwd);
  2375. if (results.is_empty())
  2376. shell->raise_error(Shell::ShellError::InvalidGlobError, "Glob did not match anything!", m_generation_position);
  2377. return results;
  2378. }
  2379. SimpleVariableValue::~SimpleVariableValue()
  2380. {
  2381. }
  2382. Vector<String> SimpleVariableValue::resolve_as_list(RefPtr<Shell> shell)
  2383. {
  2384. if (!shell)
  2385. return {};
  2386. if (auto value = resolve_without_cast(shell); value != this)
  2387. return value->resolve_as_list(shell);
  2388. char* env_value = getenv(m_name.characters());
  2389. if (env_value == nullptr)
  2390. return { "" };
  2391. Vector<String> res;
  2392. String str_env_value = String(env_value);
  2393. const auto& split_text = str_env_value.split_view(' ');
  2394. for (auto& part : split_text)
  2395. res.append(part);
  2396. return res;
  2397. }
  2398. NonnullRefPtr<Value> SimpleVariableValue::resolve_without_cast(RefPtr<Shell> shell)
  2399. {
  2400. ASSERT(shell);
  2401. if (auto value = shell->lookup_local_variable(m_name))
  2402. return value.release_nonnull();
  2403. return *this;
  2404. }
  2405. SpecialVariableValue::~SpecialVariableValue()
  2406. {
  2407. }
  2408. Vector<String> SpecialVariableValue::resolve_as_list(RefPtr<Shell> shell)
  2409. {
  2410. if (!shell)
  2411. return {};
  2412. switch (m_name) {
  2413. case '?':
  2414. return { String::number(shell->last_return_code) };
  2415. case '$':
  2416. return { String::number(getpid()) };
  2417. case '*':
  2418. if (auto argv = shell->lookup_local_variable("ARGV"))
  2419. return argv->resolve_as_list(shell);
  2420. return {};
  2421. case '#':
  2422. if (auto argv = shell->lookup_local_variable("ARGV")) {
  2423. if (argv->is_list()) {
  2424. auto list_argv = static_cast<AST::ListValue*>(argv.ptr());
  2425. return { String::number(list_argv->values().size()) };
  2426. }
  2427. return { "1" };
  2428. }
  2429. return { "0" };
  2430. default:
  2431. return { "" };
  2432. }
  2433. }
  2434. TildeValue::~TildeValue()
  2435. {
  2436. }
  2437. Vector<String> TildeValue::resolve_as_list(RefPtr<Shell> shell)
  2438. {
  2439. StringBuilder builder;
  2440. builder.append("~");
  2441. builder.append(m_username);
  2442. if (!shell)
  2443. return { builder.to_string() };
  2444. return { shell->expand_tilde(builder.to_string()) };
  2445. }
  2446. Result<NonnullRefPtr<Rewiring>, String> CloseRedirection::apply() const
  2447. {
  2448. return adopt(*new Rewiring(fd, fd, Rewiring::Close::ImmediatelyCloseNew));
  2449. }
  2450. CloseRedirection::~CloseRedirection()
  2451. {
  2452. }
  2453. Result<NonnullRefPtr<Rewiring>, String> PathRedirection::apply() const
  2454. {
  2455. auto check_fd_and_return = [my_fd = this->fd](int fd, const String& path) -> Result<NonnullRefPtr<Rewiring>, String> {
  2456. if (fd < 0) {
  2457. String error = strerror(errno);
  2458. dbgln("open() failed for '{}' with {}", path, error);
  2459. return error;
  2460. }
  2461. return adopt(*new Rewiring(fd, my_fd, Rewiring::Close::Old));
  2462. };
  2463. switch (direction) {
  2464. case AST::PathRedirection::WriteAppend:
  2465. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666), path);
  2466. case AST::PathRedirection::Write:
  2467. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666), path);
  2468. case AST::PathRedirection::Read:
  2469. return check_fd_and_return(open(path.characters(), O_RDONLY), path);
  2470. case AST::PathRedirection::ReadWrite:
  2471. return check_fd_and_return(open(path.characters(), O_RDWR | O_CREAT, 0666), path);
  2472. }
  2473. ASSERT_NOT_REACHED();
  2474. }
  2475. PathRedirection::~PathRedirection()
  2476. {
  2477. }
  2478. FdRedirection::~FdRedirection()
  2479. {
  2480. }
  2481. Redirection::~Redirection()
  2482. {
  2483. }
  2484. }