AST.cpp 88 KB

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