AST.cpp 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "AST.h"
  7. #include "Shell.h"
  8. #include <AK/MemoryStream.h>
  9. #include <AK/ScopeGuard.h>
  10. #include <AK/ScopedValueRollback.h>
  11. #include <AK/String.h>
  12. #include <AK/StringBuilder.h>
  13. #include <AK/URL.h>
  14. #include <LibCore/EventLoop.h>
  15. #include <LibCore/File.h>
  16. #include <errno.h>
  17. #include <fcntl.h>
  18. #include <signal.h>
  19. #include <unistd.h>
  20. ErrorOr<void> AK::Formatter<Shell::AST::Command>::format(FormatBuilder& builder, Shell::AST::Command const& value)
  21. {
  22. if (m_sign_mode != FormatBuilder::SignMode::Default)
  23. VERIFY_NOT_REACHED();
  24. if (m_alternative_form)
  25. VERIFY_NOT_REACHED();
  26. if (m_zero_pad)
  27. VERIFY_NOT_REACHED();
  28. if (m_mode != Mode::Default && m_mode != Mode::String)
  29. VERIFY_NOT_REACHED();
  30. if (m_width.has_value())
  31. VERIFY_NOT_REACHED();
  32. if (m_precision.has_value())
  33. VERIFY_NOT_REACHED();
  34. if (value.argv.is_empty()) {
  35. TRY(builder.put_literal("(ShellInternal)"));
  36. } else {
  37. bool first = true;
  38. for (auto& arg : value.argv) {
  39. if (!first)
  40. TRY(builder.put_literal(" "));
  41. first = false;
  42. TRY(builder.put_literal(arg));
  43. }
  44. }
  45. for (auto& redir : value.redirections) {
  46. TRY(builder.put_padding(' ', 1));
  47. if (redir.is_path_redirection()) {
  48. auto path_redir = (Shell::AST::PathRedirection const*)&redir;
  49. TRY(builder.put_i64(path_redir->fd));
  50. switch (path_redir->direction) {
  51. case Shell::AST::PathRedirection::Read:
  52. TRY(builder.put_literal("<"));
  53. break;
  54. case Shell::AST::PathRedirection::Write:
  55. TRY(builder.put_literal(">"));
  56. break;
  57. case Shell::AST::PathRedirection::WriteAppend:
  58. TRY(builder.put_literal(">>"));
  59. break;
  60. case Shell::AST::PathRedirection::ReadWrite:
  61. TRY(builder.put_literal("<>"));
  62. break;
  63. }
  64. TRY(builder.put_literal(path_redir->path));
  65. } else if (redir.is_fd_redirection()) {
  66. auto* fdredir = (Shell::AST::FdRedirection const*)&redir;
  67. TRY(builder.put_i64(fdredir->new_fd));
  68. TRY(builder.put_literal(">"));
  69. TRY(builder.put_i64(fdredir->old_fd));
  70. } else if (redir.is_close_redirection()) {
  71. auto close_redir = (Shell::AST::CloseRedirection const*)&redir;
  72. TRY(builder.put_i64(close_redir->fd));
  73. TRY(builder.put_literal(">&-"));
  74. } else {
  75. VERIFY_NOT_REACHED();
  76. }
  77. }
  78. if (!value.next_chain.is_empty()) {
  79. for (auto& command : value.next_chain) {
  80. switch (command.action) {
  81. case Shell::AST::NodeWithAction::And:
  82. TRY(builder.put_literal(" && "));
  83. break;
  84. case Shell::AST::NodeWithAction::Or:
  85. TRY(builder.put_literal(" || "));
  86. break;
  87. case Shell::AST::NodeWithAction::Sequence:
  88. TRY(builder.put_literal("; "));
  89. break;
  90. }
  91. TRY(builder.put_literal("("));
  92. TRY(builder.put_literal(command.node->class_name()));
  93. TRY(builder.put_literal("...)"));
  94. }
  95. }
  96. if (!value.should_wait)
  97. TRY(builder.put_literal("&"));
  98. return {};
  99. }
  100. namespace Shell::AST {
  101. static inline void print_indented(StringView str, int indent)
  102. {
  103. dbgln("{}{}", String::repeated(' ', indent * 2), str);
  104. }
  105. static inline Optional<Position> merge_positions(Optional<Position> const& left, Optional<Position> const& right)
  106. {
  107. if (!left.has_value())
  108. return right;
  109. if (!right.has_value())
  110. return left;
  111. return Position {
  112. .start_offset = left->start_offset,
  113. .end_offset = right->end_offset,
  114. .start_line = left->start_line,
  115. .end_line = right->end_line,
  116. };
  117. }
  118. static inline Vector<Command> join_commands(Vector<Command> left, Vector<Command> right)
  119. {
  120. Command command;
  121. auto last_in_left = left.take_last();
  122. auto first_in_right = right.take_first();
  123. command.argv.extend(last_in_left.argv);
  124. command.argv.extend(first_in_right.argv);
  125. command.redirections.extend(last_in_left.redirections);
  126. command.redirections.extend(first_in_right.redirections);
  127. command.should_wait = first_in_right.should_wait && last_in_left.should_wait;
  128. command.is_pipe_source = first_in_right.is_pipe_source;
  129. command.should_notify_if_in_background = first_in_right.should_notify_if_in_background || last_in_left.should_notify_if_in_background;
  130. command.position = merge_positions(last_in_left.position, first_in_right.position);
  131. Vector<Command> commands;
  132. commands.extend(left);
  133. commands.append(command);
  134. commands.extend(right);
  135. return commands;
  136. }
  137. static String resolve_slices(RefPtr<Shell> shell, String&& input_value, NonnullRefPtrVector<Slice> slices)
  138. {
  139. if (slices.is_empty())
  140. return move(input_value);
  141. for (auto& slice : slices) {
  142. auto value = slice.run(shell);
  143. if (shell && shell->has_any_error())
  144. break;
  145. if (!value) {
  146. shell->raise_error(Shell::ShellError::InvalidSliceContentsError, "Invalid slice contents", slice.position());
  147. return move(input_value);
  148. }
  149. auto index_values = value->resolve_as_list(shell);
  150. Vector<size_t> indices;
  151. indices.ensure_capacity(index_values.size());
  152. size_t i = 0;
  153. for (auto& value : index_values) {
  154. auto maybe_index = value.to_int();
  155. if (!maybe_index.has_value()) {
  156. shell->raise_error(Shell::ShellError::InvalidSliceContentsError, String::formatted("Invalid value in slice index {}: {} (expected a number)", i, value), slice.position());
  157. return move(input_value);
  158. }
  159. ++i;
  160. auto index = maybe_index.value();
  161. auto original_index = index;
  162. if (index < 0)
  163. index += input_value.length();
  164. if (index < 0 || (size_t)index >= input_value.length()) {
  165. shell->raise_error(Shell::ShellError::InvalidSliceContentsError, String::formatted("Slice index {} (evaluated as {}) out of value bounds [0-{})", index, original_index, input_value.length()), slice.position());
  166. return move(input_value);
  167. }
  168. indices.unchecked_append(index);
  169. }
  170. StringBuilder builder { indices.size() };
  171. for (auto& index : indices)
  172. builder.append(input_value[index]);
  173. input_value = builder.build();
  174. }
  175. return move(input_value);
  176. }
  177. static Vector<String> resolve_slices(RefPtr<Shell> shell, Vector<String>&& values, NonnullRefPtrVector<Slice> slices)
  178. {
  179. if (slices.is_empty())
  180. return move(values);
  181. for (auto& slice : slices) {
  182. auto value = slice.run(shell);
  183. if (shell && shell->has_any_error())
  184. break;
  185. if (!value) {
  186. shell->raise_error(Shell::ShellError::InvalidSliceContentsError, "Invalid slice contents", slice.position());
  187. return move(values);
  188. }
  189. auto index_values = value->resolve_as_list(shell);
  190. Vector<size_t> indices;
  191. indices.ensure_capacity(index_values.size());
  192. size_t i = 0;
  193. for (auto& value : index_values) {
  194. auto maybe_index = value.to_int();
  195. if (!maybe_index.has_value()) {
  196. shell->raise_error(Shell::ShellError::InvalidSliceContentsError, String::formatted("Invalid value in slice index {}: {} (expected a number)", i, value), slice.position());
  197. return move(values);
  198. }
  199. ++i;
  200. auto index = maybe_index.value();
  201. auto original_index = index;
  202. if (index < 0)
  203. index += values.size();
  204. if (index < 0 || (size_t)index >= values.size()) {
  205. shell->raise_error(Shell::ShellError::InvalidSliceContentsError, String::formatted("Slice index {} (evaluated as {}) out of value bounds [0-{})", index, original_index, values.size()), slice.position());
  206. return move(values);
  207. }
  208. indices.unchecked_append(index);
  209. }
  210. Vector<String> result;
  211. result.ensure_capacity(indices.size());
  212. for (auto& index : indices)
  213. result.unchecked_append(values[index]);
  214. values = move(result);
  215. }
  216. return move(values);
  217. }
  218. void Node::clear_syntax_error()
  219. {
  220. m_syntax_error_node->clear_syntax_error();
  221. }
  222. void Node::set_is_syntax_error(SyntaxError const& error_node)
  223. {
  224. if (!m_syntax_error_node) {
  225. m_syntax_error_node = error_node;
  226. } else {
  227. m_syntax_error_node->set_is_syntax_error(error_node);
  228. }
  229. }
  230. bool Node::is_syntax_error() const
  231. {
  232. return m_syntax_error_node && m_syntax_error_node->is_syntax_error();
  233. }
  234. void Node::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(NonnullRefPtr<Value>)> callback)
  235. {
  236. auto value = run(shell)->resolve_without_cast(shell);
  237. if (shell && shell->has_any_error())
  238. return;
  239. if (value->is_job()) {
  240. callback(value);
  241. return;
  242. }
  243. if (value->is_list_without_resolution()) {
  244. auto list = value->resolve_without_cast(shell);
  245. for (auto& element : static_cast<ListValue*>(list.ptr())->values()) {
  246. if (callback(element) == IterationDecision::Break)
  247. break;
  248. }
  249. return;
  250. }
  251. auto list = value->resolve_as_list(shell);
  252. for (auto& element : list) {
  253. if (callback(make_ref_counted<StringValue>(move(element))) == IterationDecision::Break)
  254. break;
  255. }
  256. }
  257. Vector<Command> Node::to_lazy_evaluated_commands(RefPtr<Shell> shell)
  258. {
  259. if (would_execute()) {
  260. // Wrap the node in a "should immediately execute next" command.
  261. return {
  262. Command { {}, {}, true, false, true, true, {}, { NodeWithAction(*this, NodeWithAction::Sequence) }, position() }
  263. };
  264. }
  265. return run(shell)->resolve_as_commands(shell);
  266. }
  267. void Node::dump(int level) const
  268. {
  269. print_indented(String::formatted("{} at {}:{} (from {}.{} to {}.{})",
  270. class_name().characters(),
  271. m_position.start_offset,
  272. m_position.end_offset,
  273. m_position.start_line.line_number,
  274. m_position.start_line.line_column,
  275. m_position.end_line.line_number,
  276. m_position.end_line.line_column),
  277. level);
  278. }
  279. Node::Node(Position position)
  280. : m_position(position)
  281. {
  282. }
  283. Vector<Line::CompletionSuggestion> Node::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
  284. {
  285. auto matching_node = hit_test_result.matching_node;
  286. if (matching_node) {
  287. auto kind = matching_node->kind();
  288. StringLiteral::EnclosureType enclosure_type = StringLiteral::EnclosureType::None;
  289. if (kind == Kind::StringLiteral)
  290. enclosure_type = static_cast<StringLiteral*>(matching_node.ptr())->enclosure_type();
  291. auto set_results_trivia = [enclosure_type](Vector<Line::CompletionSuggestion>&& suggestions) {
  292. if (enclosure_type != StringLiteral::EnclosureType::None) {
  293. for (auto& entry : suggestions)
  294. entry.trailing_trivia = { static_cast<u32>(enclosure_type == StringLiteral::EnclosureType::SingleQuotes ? '\'' : '"') };
  295. }
  296. return suggestions;
  297. };
  298. if (kind == Kind::BarewordLiteral || kind == Kind::StringLiteral) {
  299. Shell::EscapeMode escape_mode;
  300. StringView text;
  301. size_t corrected_offset;
  302. if (kind == Kind::BarewordLiteral) {
  303. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  304. text = node->text();
  305. escape_mode = Shell::EscapeMode::Bareword;
  306. corrected_offset = find_offset_into_node(text, offset - matching_node->position().start_offset, escape_mode);
  307. } else {
  308. auto* node = static_cast<StringLiteral*>(matching_node.ptr());
  309. text = node->text();
  310. escape_mode = enclosure_type == StringLiteral::EnclosureType::SingleQuotes ? Shell::EscapeMode::SingleQuotedString : Shell::EscapeMode::DoubleQuotedString;
  311. corrected_offset = find_offset_into_node(text, offset - matching_node->position().start_offset + 1, escape_mode);
  312. }
  313. if (corrected_offset > text.length())
  314. return {};
  315. // If the literal isn't an option, treat it as a path.
  316. if (!(text.starts_with("-") || text == "--" || text == "-"))
  317. return set_results_trivia(shell.complete_path("", text, corrected_offset, Shell::ExecutableOnly::No, hit_test_result.closest_command_node.ptr(), hit_test_result.matching_node, escape_mode));
  318. // If the literal is an option, we have to know the program name
  319. // should we have no way to get that, bail early.
  320. if (!hit_test_result.closest_command_node)
  321. return {};
  322. auto program_name_node = hit_test_result.closest_command_node->leftmost_trivial_literal();
  323. if (!program_name_node)
  324. return {};
  325. String program_name;
  326. if (program_name_node->is_bareword())
  327. program_name = static_cast<BarewordLiteral*>(program_name_node.ptr())->text();
  328. else
  329. program_name = static_cast<StringLiteral*>(program_name_node.ptr())->text();
  330. return set_results_trivia(shell.complete_option(program_name, text, corrected_offset, hit_test_result.closest_command_node.ptr(), hit_test_result.matching_node));
  331. }
  332. return {};
  333. }
  334. auto result = hit_test_position(offset);
  335. if (!result.matching_node)
  336. return shell.complete_path("", "", 0, Shell::ExecutableOnly::No, result.closest_command_node.ptr(), nullptr, Shell::EscapeMode::Bareword);
  337. auto node = result.matching_node;
  338. if (node->is_bareword() || node != result.closest_node_with_semantic_meaning)
  339. node = result.closest_node_with_semantic_meaning;
  340. if (!node)
  341. return {};
  342. return node->complete_for_editor(shell, offset, result);
  343. }
  344. Vector<Line::CompletionSuggestion> Node::complete_for_editor(Shell& shell, size_t offset)
  345. {
  346. return Node::complete_for_editor(shell, offset, { nullptr, nullptr, nullptr });
  347. }
  348. void And::dump(int level) const
  349. {
  350. Node::dump(level);
  351. m_left->dump(level + 1);
  352. m_right->dump(level + 1);
  353. }
  354. RefPtr<Value> And::run(RefPtr<Shell> shell)
  355. {
  356. auto commands = m_left->to_lazy_evaluated_commands(shell);
  357. if (shell && shell->has_any_error())
  358. return make_ref_counted<ListValue>({});
  359. commands.last().next_chain.append(NodeWithAction { *m_right, NodeWithAction::And });
  360. return make_ref_counted<CommandSequenceValue>(move(commands));
  361. }
  362. void And::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  363. {
  364. metadata.is_first_in_list = true;
  365. m_left->highlight_in_editor(editor, shell, metadata);
  366. m_right->highlight_in_editor(editor, shell, metadata);
  367. }
  368. HitTestResult And::hit_test_position(size_t offset) const
  369. {
  370. auto result = m_left->hit_test_position(offset);
  371. if (result.matching_node) {
  372. if (!result.closest_command_node)
  373. result.closest_command_node = m_right;
  374. return result;
  375. }
  376. result = m_right->hit_test_position(offset);
  377. if (!result.closest_command_node)
  378. result.closest_command_node = m_right;
  379. return result;
  380. }
  381. And::And(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position and_position)
  382. : Node(move(position))
  383. , m_left(move(left))
  384. , m_right(move(right))
  385. , m_and_position(and_position)
  386. {
  387. if (m_left->is_syntax_error())
  388. set_is_syntax_error(m_left->syntax_error_node());
  389. else if (m_right->is_syntax_error())
  390. set_is_syntax_error(m_right->syntax_error_node());
  391. }
  392. void ListConcatenate::dump(int level) const
  393. {
  394. Node::dump(level);
  395. for (auto& element : m_list)
  396. element->dump(level + 1);
  397. }
  398. RefPtr<Value> ListConcatenate::run(RefPtr<Shell> shell)
  399. {
  400. RefPtr<Value> result = nullptr;
  401. for (auto& element : m_list) {
  402. if (shell && shell->has_any_error())
  403. break;
  404. if (!result) {
  405. result = make_ref_counted<ListValue>({ element->run(shell)->resolve_without_cast(shell) });
  406. continue;
  407. }
  408. auto element_value = element->run(shell)->resolve_without_cast(shell);
  409. if (shell && shell->has_any_error())
  410. break;
  411. if (result->is_command() || element_value->is_command()) {
  412. auto joined_commands = join_commands(result->resolve_as_commands(shell), element_value->resolve_as_commands(shell));
  413. if (joined_commands.size() == 1) {
  414. auto& command = joined_commands[0];
  415. command.position = position();
  416. result = make_ref_counted<CommandValue>(command);
  417. } else {
  418. result = make_ref_counted<CommandSequenceValue>(move(joined_commands));
  419. }
  420. } else {
  421. NonnullRefPtrVector<Value> values;
  422. if (result->is_list_without_resolution()) {
  423. values.extend(static_cast<ListValue*>(result.ptr())->values());
  424. } else {
  425. for (auto& result : result->resolve_as_list(shell))
  426. values.append(make_ref_counted<StringValue>(result));
  427. }
  428. values.append(element_value);
  429. result = make_ref_counted<ListValue>(move(values));
  430. }
  431. }
  432. if (!result)
  433. return make_ref_counted<ListValue>({});
  434. return result;
  435. }
  436. void ListConcatenate::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(NonnullRefPtr<Value>)> callback)
  437. {
  438. for (auto& entry : m_list) {
  439. auto value = entry->run(shell);
  440. if (shell && shell->has_any_error())
  441. break;
  442. if (!value)
  443. continue;
  444. if (callback(value.release_nonnull()) == IterationDecision::Break)
  445. break;
  446. }
  447. }
  448. void ListConcatenate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  449. {
  450. auto first = metadata.is_first_in_list;
  451. metadata.is_first_in_list = false;
  452. metadata.is_first_in_list = first;
  453. for (auto& element : m_list) {
  454. element->highlight_in_editor(editor, shell, metadata);
  455. metadata.is_first_in_list = false;
  456. }
  457. }
  458. HitTestResult ListConcatenate::hit_test_position(size_t offset) const
  459. {
  460. bool first = true;
  461. for (auto& element : m_list) {
  462. auto result = element->hit_test_position(offset);
  463. if (!result.closest_node_with_semantic_meaning && !first)
  464. result.closest_node_with_semantic_meaning = this;
  465. if (result.matching_node)
  466. return result;
  467. first = false;
  468. }
  469. return {};
  470. }
  471. RefPtr<Node> ListConcatenate::leftmost_trivial_literal() const
  472. {
  473. if (m_list.is_empty())
  474. return nullptr;
  475. return m_list.first()->leftmost_trivial_literal();
  476. }
  477. ListConcatenate::ListConcatenate(Position position, Vector<NonnullRefPtr<Node>> list)
  478. : Node(move(position))
  479. , m_list(move(list))
  480. {
  481. for (auto& element : m_list) {
  482. if (element->is_syntax_error()) {
  483. set_is_syntax_error(element->syntax_error_node());
  484. break;
  485. }
  486. }
  487. }
  488. void Background::dump(int level) const
  489. {
  490. Node::dump(level);
  491. m_command->dump(level + 1);
  492. }
  493. RefPtr<Value> Background::run(RefPtr<Shell> shell)
  494. {
  495. auto commands = m_command->to_lazy_evaluated_commands(shell);
  496. for (auto& command : commands)
  497. command.should_wait = false;
  498. return make_ref_counted<CommandSequenceValue>(move(commands));
  499. }
  500. void Background::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  501. {
  502. m_command->highlight_in_editor(editor, shell, metadata);
  503. }
  504. HitTestResult Background::hit_test_position(size_t offset) const
  505. {
  506. return m_command->hit_test_position(offset);
  507. }
  508. Background::Background(Position position, NonnullRefPtr<Node> command)
  509. : Node(move(position))
  510. , m_command(move(command))
  511. {
  512. if (m_command->is_syntax_error())
  513. set_is_syntax_error(m_command->syntax_error_node());
  514. }
  515. void BarewordLiteral::dump(int level) const
  516. {
  517. Node::dump(level);
  518. print_indented(m_text, level + 1);
  519. }
  520. RefPtr<Value> BarewordLiteral::run(RefPtr<Shell>)
  521. {
  522. return make_ref_counted<StringValue>(m_text);
  523. }
  524. void BarewordLiteral::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  525. {
  526. if (metadata.is_first_in_list) {
  527. if (shell.is_runnable(m_text)) {
  528. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Bold });
  529. } else {
  530. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red) });
  531. }
  532. return;
  533. }
  534. if (m_text.starts_with('-')) {
  535. if (m_text == "--") {
  536. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  537. return;
  538. }
  539. if (m_text == "-")
  540. return;
  541. if (m_text.starts_with("--")) {
  542. auto index = m_text.find('=').value_or(m_text.length() - 1) + 1;
  543. editor.stylize({ m_position.start_offset, m_position.start_offset + index }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  544. } else {
  545. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  546. }
  547. }
  548. if (Core::File::exists(m_text)) {
  549. auto realpath = shell.resolve_path(m_text);
  550. auto url = URL::create_with_file_protocol(realpath);
  551. url.set_host(shell.hostname);
  552. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  553. }
  554. }
  555. BarewordLiteral::BarewordLiteral(Position position, String text)
  556. : Node(move(position))
  557. , m_text(move(text))
  558. {
  559. }
  560. void BraceExpansion::dump(int level) const
  561. {
  562. Node::dump(level);
  563. for (auto& entry : m_entries)
  564. entry.dump(level + 1);
  565. }
  566. RefPtr<Value> BraceExpansion::run(RefPtr<Shell> shell)
  567. {
  568. NonnullRefPtrVector<Value> values;
  569. for (auto& entry : m_entries) {
  570. if (shell && shell->has_any_error())
  571. break;
  572. auto value = entry.run(shell);
  573. if (value)
  574. values.append(value.release_nonnull());
  575. }
  576. return make_ref_counted<ListValue>(move(values));
  577. }
  578. HitTestResult BraceExpansion::hit_test_position(size_t offset) const
  579. {
  580. for (auto& entry : m_entries) {
  581. auto result = entry.hit_test_position(offset);
  582. if (result.matching_node) {
  583. if (!result.closest_command_node)
  584. result.closest_command_node = &entry;
  585. return result;
  586. }
  587. }
  588. return {};
  589. }
  590. void BraceExpansion::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  591. {
  592. for (auto& entry : m_entries) {
  593. entry.highlight_in_editor(editor, shell, metadata);
  594. metadata.is_first_in_list = false;
  595. }
  596. }
  597. BraceExpansion::BraceExpansion(Position position, NonnullRefPtrVector<Node> entries)
  598. : Node(move(position))
  599. , m_entries(move(entries))
  600. {
  601. for (auto& entry : m_entries) {
  602. if (entry.is_syntax_error()) {
  603. set_is_syntax_error(entry.syntax_error_node());
  604. break;
  605. }
  606. }
  607. }
  608. void CastToCommand::dump(int level) const
  609. {
  610. Node::dump(level);
  611. m_inner->dump(level + 1);
  612. }
  613. RefPtr<Value> CastToCommand::run(RefPtr<Shell> shell)
  614. {
  615. if (m_inner->is_command())
  616. return m_inner->run(shell);
  617. auto value = m_inner->run(shell)->resolve_without_cast(shell);
  618. if (shell && shell->has_any_error())
  619. return make_ref_counted<ListValue>({});
  620. if (value->is_command())
  621. return value;
  622. auto argv = value->resolve_as_list(shell);
  623. return make_ref_counted<CommandValue>(move(argv), position());
  624. }
  625. void CastToCommand::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  626. {
  627. m_inner->highlight_in_editor(editor, shell, metadata);
  628. }
  629. HitTestResult CastToCommand::hit_test_position(size_t offset) const
  630. {
  631. auto result = m_inner->hit_test_position(offset);
  632. if (!result.closest_node_with_semantic_meaning)
  633. result.closest_node_with_semantic_meaning = this;
  634. return result;
  635. }
  636. Vector<Line::CompletionSuggestion> CastToCommand::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
  637. {
  638. auto matching_node = hit_test_result.matching_node;
  639. if (!matching_node || !matching_node->is_bareword())
  640. return {};
  641. auto corrected_offset = offset - matching_node->position().start_offset;
  642. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  643. if (corrected_offset > node->text().length())
  644. return {};
  645. return shell.complete_program_name(node->text(), corrected_offset);
  646. }
  647. RefPtr<Node> CastToCommand::leftmost_trivial_literal() const
  648. {
  649. return m_inner->leftmost_trivial_literal();
  650. }
  651. CastToCommand::CastToCommand(Position position, NonnullRefPtr<Node> inner)
  652. : Node(move(position))
  653. , m_inner(move(inner))
  654. {
  655. if (m_inner->is_syntax_error())
  656. set_is_syntax_error(m_inner->syntax_error_node());
  657. }
  658. void CastToList::dump(int level) const
  659. {
  660. Node::dump(level);
  661. if (m_inner)
  662. m_inner->dump(level + 1);
  663. else
  664. print_indented("(empty)", level + 1);
  665. }
  666. RefPtr<Value> CastToList::run(RefPtr<Shell> shell)
  667. {
  668. if (!m_inner)
  669. return make_ref_counted<ListValue>({});
  670. auto inner_value = m_inner->run(shell)->resolve_without_cast(shell);
  671. if (shell && shell->has_any_error())
  672. return make_ref_counted<ListValue>({});
  673. if (inner_value->is_command() || inner_value->is_list())
  674. return inner_value;
  675. auto values = inner_value->resolve_as_list(shell);
  676. NonnullRefPtrVector<Value> cast_values;
  677. for (auto& value : values)
  678. cast_values.append(make_ref_counted<StringValue>(value));
  679. return make_ref_counted<ListValue>(cast_values);
  680. }
  681. void CastToList::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(NonnullRefPtr<Value>)> callback)
  682. {
  683. if (m_inner)
  684. m_inner->for_each_entry(shell, move(callback));
  685. }
  686. void CastToList::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  687. {
  688. if (m_inner)
  689. m_inner->highlight_in_editor(editor, shell, metadata);
  690. }
  691. HitTestResult CastToList::hit_test_position(size_t offset) const
  692. {
  693. if (!m_inner)
  694. return {};
  695. return m_inner->hit_test_position(offset);
  696. }
  697. RefPtr<Node> CastToList::leftmost_trivial_literal() const
  698. {
  699. return m_inner->leftmost_trivial_literal();
  700. }
  701. CastToList::CastToList(Position position, RefPtr<Node> inner)
  702. : Node(move(position))
  703. , m_inner(move(inner))
  704. {
  705. if (m_inner && m_inner->is_syntax_error())
  706. set_is_syntax_error(m_inner->syntax_error_node());
  707. }
  708. void CloseFdRedirection::dump(int level) const
  709. {
  710. Node::dump(level);
  711. print_indented(String::formatted("{} -> Close", m_fd), level);
  712. }
  713. RefPtr<Value> CloseFdRedirection::run(RefPtr<Shell>)
  714. {
  715. Command command;
  716. command.position = position();
  717. command.redirections.append(adopt_ref(*new CloseRedirection(m_fd)));
  718. return make_ref_counted<CommandValue>(move(command));
  719. }
  720. void CloseFdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  721. {
  722. editor.stylize({ m_position.start_offset, m_position.end_offset - 1 }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  723. editor.stylize({ m_position.end_offset - 1, m_position.end_offset }, { Line::Style::Foreground(0xff, 0x7e, 0x00) }); // Amber
  724. }
  725. CloseFdRedirection::CloseFdRedirection(Position position, int fd)
  726. : Node(move(position))
  727. , m_fd(fd)
  728. {
  729. }
  730. CloseFdRedirection::~CloseFdRedirection()
  731. {
  732. }
  733. void CommandLiteral::dump(int level) const
  734. {
  735. Node::dump(level);
  736. print_indented(String::formatted("(Generated command literal: {})", m_command), level + 1);
  737. }
  738. RefPtr<Value> CommandLiteral::run(RefPtr<Shell>)
  739. {
  740. return make_ref_counted<CommandValue>(m_command);
  741. }
  742. CommandLiteral::CommandLiteral(Position position, Command command)
  743. : Node(move(position))
  744. , m_command(move(command))
  745. {
  746. }
  747. CommandLiteral::~CommandLiteral()
  748. {
  749. }
  750. void Comment::dump(int level) const
  751. {
  752. Node::dump(level);
  753. print_indented(m_text, level + 1);
  754. }
  755. RefPtr<Value> Comment::run(RefPtr<Shell>)
  756. {
  757. return make_ref_counted<ListValue>({});
  758. }
  759. void Comment::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  760. {
  761. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(150, 150, 150) }); // Light gray
  762. }
  763. Comment::Comment(Position position, String text)
  764. : Node(move(position))
  765. , m_text(move(text))
  766. {
  767. }
  768. Comment::~Comment()
  769. {
  770. }
  771. void ContinuationControl::dump(int level) const
  772. {
  773. Node::dump(level);
  774. print_indented(m_kind == Continue ? "(Continue)" : "(Break)", level + 1);
  775. }
  776. RefPtr<Value> ContinuationControl::run(RefPtr<Shell> shell)
  777. {
  778. if (m_kind == Break)
  779. shell->raise_error(Shell::ShellError::InternalControlFlowBreak, {}, position());
  780. else if (m_kind == Continue)
  781. shell->raise_error(Shell::ShellError::InternalControlFlowContinue, {}, position());
  782. else
  783. VERIFY_NOT_REACHED();
  784. return make_ref_counted<ListValue>({});
  785. }
  786. void ContinuationControl::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  787. {
  788. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  789. }
  790. void DoubleQuotedString::dump(int level) const
  791. {
  792. Node::dump(level);
  793. m_inner->dump(level + 1);
  794. }
  795. RefPtr<Value> DoubleQuotedString::run(RefPtr<Shell> shell)
  796. {
  797. StringBuilder builder;
  798. auto values = m_inner->run(shell)->resolve_as_list(shell);
  799. builder.join("", values);
  800. return make_ref_counted<StringValue>(builder.to_string());
  801. }
  802. void DoubleQuotedString::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  803. {
  804. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  805. if (metadata.is_first_in_list)
  806. style.unify_with({ Line::Style::Bold });
  807. editor.stylize({ m_position.start_offset, m_position.end_offset }, style);
  808. metadata.is_first_in_list = false;
  809. m_inner->highlight_in_editor(editor, shell, metadata);
  810. }
  811. HitTestResult DoubleQuotedString::hit_test_position(size_t offset) const
  812. {
  813. return m_inner->hit_test_position(offset);
  814. }
  815. DoubleQuotedString::DoubleQuotedString(Position position, RefPtr<Node> inner)
  816. : Node(move(position))
  817. , m_inner(move(inner))
  818. {
  819. if (m_inner->is_syntax_error())
  820. set_is_syntax_error(m_inner->syntax_error_node());
  821. }
  822. DoubleQuotedString::~DoubleQuotedString()
  823. {
  824. }
  825. void DynamicEvaluate::dump(int level) const
  826. {
  827. Node::dump(level);
  828. m_inner->dump(level + 1);
  829. }
  830. RefPtr<Value> DynamicEvaluate::run(RefPtr<Shell> shell)
  831. {
  832. auto result = m_inner->run(shell)->resolve_without_cast(shell);
  833. if (shell && shell->has_any_error())
  834. return make_ref_counted<ListValue>({});
  835. // Dynamic Evaluation behaves differently between strings and lists.
  836. // Strings are treated as variables, and Lists are treated as commands.
  837. if (result->is_string()) {
  838. auto name_part = result->resolve_as_list(shell);
  839. VERIFY(name_part.size() == 1);
  840. return make_ref_counted<SimpleVariableValue>(name_part[0]);
  841. }
  842. // If it's anything else, we're just gonna cast it to a list.
  843. auto list = result->resolve_as_list(shell);
  844. return make_ref_counted<CommandValue>(move(list), position());
  845. }
  846. void DynamicEvaluate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  847. {
  848. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  849. m_inner->highlight_in_editor(editor, shell, metadata);
  850. }
  851. HitTestResult DynamicEvaluate::hit_test_position(size_t offset) const
  852. {
  853. return m_inner->hit_test_position(offset);
  854. }
  855. DynamicEvaluate::DynamicEvaluate(Position position, NonnullRefPtr<Node> inner)
  856. : Node(move(position))
  857. , m_inner(move(inner))
  858. {
  859. if (m_inner->is_syntax_error())
  860. set_is_syntax_error(m_inner->syntax_error_node());
  861. }
  862. DynamicEvaluate::~DynamicEvaluate()
  863. {
  864. }
  865. void Fd2FdRedirection::dump(int level) const
  866. {
  867. Node::dump(level);
  868. print_indented(String::formatted("{} -> {}", m_old_fd, m_new_fd), level);
  869. }
  870. RefPtr<Value> Fd2FdRedirection::run(RefPtr<Shell>)
  871. {
  872. Command command;
  873. command.position = position();
  874. command.redirections.append(FdRedirection::create(m_new_fd, m_old_fd, Rewiring::Close::None));
  875. return make_ref_counted<CommandValue>(move(command));
  876. }
  877. void Fd2FdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  878. {
  879. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  880. }
  881. Fd2FdRedirection::Fd2FdRedirection(Position position, int src, int dst)
  882. : Node(move(position))
  883. , m_old_fd(src)
  884. , m_new_fd(dst)
  885. {
  886. }
  887. Fd2FdRedirection::~Fd2FdRedirection()
  888. {
  889. }
  890. void FunctionDeclaration::dump(int level) const
  891. {
  892. Node::dump(level);
  893. print_indented(String::formatted("(name: {})\n", m_name.name), level + 1);
  894. print_indented("(argument names)", level + 1);
  895. for (auto& arg : m_arguments)
  896. print_indented(String::formatted("(name: {})\n", arg.name), level + 2);
  897. print_indented("(body)", level + 1);
  898. if (m_block)
  899. m_block->dump(level + 2);
  900. else
  901. print_indented("(null)", level + 2);
  902. }
  903. RefPtr<Value> FunctionDeclaration::run(RefPtr<Shell> shell)
  904. {
  905. Vector<String> args;
  906. for (auto& arg : m_arguments)
  907. args.append(arg.name);
  908. shell->define_function(m_name.name, move(args), m_block);
  909. return make_ref_counted<ListValue>({});
  910. }
  911. void FunctionDeclaration::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  912. {
  913. editor.stylize({ m_name.position.start_offset, m_name.position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
  914. for (auto& arg : m_arguments)
  915. editor.stylize({ arg.position.start_offset, arg.position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });
  916. metadata.is_first_in_list = true;
  917. if (m_block)
  918. m_block->highlight_in_editor(editor, shell, metadata);
  919. }
  920. HitTestResult FunctionDeclaration::hit_test_position(size_t offset) const
  921. {
  922. if (!m_block)
  923. return {};
  924. auto result = m_block->hit_test_position(offset);
  925. if (result.matching_node && result.matching_node->is_simple_variable())
  926. result.closest_node_with_semantic_meaning = this;
  927. return result;
  928. }
  929. Vector<Line::CompletionSuggestion> FunctionDeclaration::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
  930. {
  931. auto matching_node = hit_test_result.matching_node;
  932. if (!matching_node)
  933. return {};
  934. if (!matching_node->is_simple_variable())
  935. return matching_node->complete_for_editor(shell, offset, hit_test_result);
  936. auto corrected_offset = offset - matching_node->position().start_offset - 1; // Skip the first '$'
  937. auto* node = static_cast<SimpleVariable*>(matching_node.ptr());
  938. auto name = node->name().substring_view(0, corrected_offset);
  939. Vector<Line::CompletionSuggestion> results;
  940. for (auto& arg : m_arguments) {
  941. if (arg.name.starts_with(name))
  942. results.append(arg.name);
  943. }
  944. results.extend(matching_node->complete_for_editor(shell, offset, hit_test_result));
  945. return results;
  946. }
  947. FunctionDeclaration::FunctionDeclaration(Position position, NameWithPosition name, Vector<NameWithPosition> arguments, RefPtr<AST::Node> body)
  948. : Node(move(position))
  949. , m_name(move(name))
  950. , m_arguments(arguments)
  951. , m_block(move(body))
  952. {
  953. if (m_block && m_block->is_syntax_error())
  954. set_is_syntax_error(m_block->syntax_error_node());
  955. }
  956. FunctionDeclaration::~FunctionDeclaration()
  957. {
  958. }
  959. void ForLoop::dump(int level) const
  960. {
  961. Node::dump(level);
  962. if (m_variable.has_value())
  963. print_indented(String::formatted("iterating with {} in", m_variable->name), level + 1);
  964. if (m_index_variable.has_value())
  965. print_indented(String::formatted("with index name {} in", m_index_variable->name), level + 1);
  966. if (m_iterated_expression)
  967. m_iterated_expression->dump(level + 2);
  968. else
  969. print_indented("(ever)", level + 2);
  970. print_indented("Running", level + 1);
  971. if (m_block)
  972. m_block->dump(level + 2);
  973. else
  974. print_indented("(null)", level + 2);
  975. }
  976. RefPtr<Value> ForLoop::run(RefPtr<Shell> shell)
  977. {
  978. if (!m_block)
  979. return make_ref_counted<ListValue>({});
  980. size_t consecutive_interruptions = 0;
  981. auto run = [&](auto& block_value) {
  982. if (shell->has_error(Shell::ShellError::InternalControlFlowBreak)) {
  983. shell->take_error();
  984. return IterationDecision::Break;
  985. }
  986. if (shell->has_error(Shell::ShellError::InternalControlFlowContinue)) {
  987. shell->take_error();
  988. return IterationDecision::Continue;
  989. }
  990. if (shell->has_any_error() && !shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
  991. return IterationDecision::Break;
  992. if (block_value->is_job()) {
  993. auto job = static_cast<JobValue*>(block_value.ptr())->job();
  994. if (!job || job->is_running_in_background())
  995. return IterationDecision::Continue;
  996. shell->block_on_job(job);
  997. if (shell->has_any_error()) {
  998. if (shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
  999. ++consecutive_interruptions;
  1000. if (shell->has_error(Shell::ShellError::InternalControlFlowKilled))
  1001. return IterationDecision::Break;
  1002. }
  1003. }
  1004. return IterationDecision::Continue;
  1005. };
  1006. if (m_iterated_expression) {
  1007. auto variable_name = m_variable.has_value() ? m_variable->name : "it";
  1008. Optional<StringView> index_name = m_index_variable.has_value() ? Optional<StringView>(m_index_variable->name) : Optional<StringView>();
  1009. size_t i = 0;
  1010. m_iterated_expression->for_each_entry(shell, [&](auto value) {
  1011. if (consecutive_interruptions >= 2)
  1012. return IterationDecision::Break;
  1013. if (shell) {
  1014. if (shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
  1015. shell->take_error();
  1016. if (shell->has_any_error())
  1017. return IterationDecision::Break;
  1018. }
  1019. RefPtr<Value> block_value;
  1020. {
  1021. auto frame = shell->push_frame(String::formatted("for ({})", this));
  1022. shell->set_local_variable(variable_name, value, true);
  1023. if (index_name.has_value())
  1024. shell->set_local_variable(index_name.value(), make_ref_counted<AST::StringValue>(String::number(i)), true);
  1025. ++i;
  1026. block_value = m_block->run(shell);
  1027. }
  1028. return run(block_value);
  1029. });
  1030. } else {
  1031. for (;;) {
  1032. if (consecutive_interruptions >= 2)
  1033. break;
  1034. if (shell) {
  1035. if (shell->has_error(Shell::ShellError::InternalControlFlowInterrupted))
  1036. shell->take_error();
  1037. if (shell->has_any_error())
  1038. break;
  1039. }
  1040. RefPtr<Value> block_value = m_block->run(shell);
  1041. if (run(block_value) == IterationDecision::Break)
  1042. break;
  1043. }
  1044. }
  1045. return make_ref_counted<ListValue>({});
  1046. }
  1047. void ForLoop::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1048. {
  1049. auto is_loop = m_iterated_expression.is_null();
  1050. editor.stylize({ m_position.start_offset, m_position.start_offset + (is_loop ? 4 : 3) }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1051. if (!is_loop) {
  1052. if (m_in_kw_position.has_value())
  1053. editor.stylize({ m_in_kw_position.value().start_offset, m_in_kw_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1054. if (m_index_kw_position.has_value())
  1055. editor.stylize({ m_index_kw_position.value().start_offset, m_index_kw_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1056. metadata.is_first_in_list = false;
  1057. m_iterated_expression->highlight_in_editor(editor, shell, metadata);
  1058. }
  1059. if (m_index_variable.has_value())
  1060. editor.stylize({ m_index_variable->position.start_offset, m_index_variable->position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });
  1061. if (m_variable.has_value())
  1062. editor.stylize({ m_variable->position.start_offset, m_variable->position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });
  1063. metadata.is_first_in_list = true;
  1064. if (m_block)
  1065. m_block->highlight_in_editor(editor, shell, metadata);
  1066. }
  1067. HitTestResult ForLoop::hit_test_position(size_t offset) const
  1068. {
  1069. if (m_iterated_expression) {
  1070. if (auto result = m_iterated_expression->hit_test_position(offset); result.matching_node)
  1071. return result;
  1072. }
  1073. if (!m_block)
  1074. return {};
  1075. return m_block->hit_test_position(offset);
  1076. }
  1077. ForLoop::ForLoop(Position position, Optional<NameWithPosition> variable, Optional<NameWithPosition> index_variable, RefPtr<AST::Node> iterated_expr, RefPtr<AST::Node> block, Optional<Position> in_kw_position, Optional<Position> index_kw_position)
  1078. : Node(move(position))
  1079. , m_variable(move(variable))
  1080. , m_index_variable(move(index_variable))
  1081. , m_iterated_expression(move(iterated_expr))
  1082. , m_block(move(block))
  1083. , m_in_kw_position(move(in_kw_position))
  1084. , m_index_kw_position(move(index_kw_position))
  1085. {
  1086. if (m_iterated_expression && m_iterated_expression->is_syntax_error())
  1087. set_is_syntax_error(m_iterated_expression->syntax_error_node());
  1088. else if (m_block && m_block->is_syntax_error())
  1089. set_is_syntax_error(m_block->syntax_error_node());
  1090. }
  1091. ForLoop::~ForLoop()
  1092. {
  1093. }
  1094. void Glob::dump(int level) const
  1095. {
  1096. Node::dump(level);
  1097. print_indented(m_text, level + 1);
  1098. }
  1099. RefPtr<Value> Glob::run(RefPtr<Shell>)
  1100. {
  1101. return make_ref_counted<GlobValue>(m_text, position());
  1102. }
  1103. void Glob::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  1104. {
  1105. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Cyan) };
  1106. if (metadata.is_first_in_list)
  1107. style.unify_with({ Line::Style::Bold });
  1108. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  1109. }
  1110. Glob::Glob(Position position, String text)
  1111. : Node(move(position))
  1112. , m_text(move(text))
  1113. {
  1114. }
  1115. Glob::~Glob()
  1116. {
  1117. }
  1118. void Heredoc::dump(int level) const
  1119. {
  1120. Node::dump(level);
  1121. print_indented("(End Key)", level + 1);
  1122. print_indented(m_end, level + 2);
  1123. print_indented("(Allows Interpolation)", level + 1);
  1124. print_indented(String::formatted("{}", m_allows_interpolation), level + 2);
  1125. print_indented("(Contents)", level + 1);
  1126. if (m_contents)
  1127. m_contents->dump(level + 2);
  1128. else
  1129. print_indented("(null)", level + 2);
  1130. }
  1131. RefPtr<Value> Heredoc::run(RefPtr<Shell> shell)
  1132. {
  1133. if (!m_deindent)
  1134. return m_contents->run(shell);
  1135. // To deindent, first split to lines...
  1136. auto value = m_contents->run(shell);
  1137. if (shell && shell->has_any_error())
  1138. return make_ref_counted<ListValue>({});
  1139. if (!value)
  1140. return value;
  1141. auto list = value->resolve_as_list(shell);
  1142. // The list better have one entry, otherwise we've put the wrong kind of node inside this heredoc
  1143. VERIFY(list.size() == 1);
  1144. auto lines = list.first().split_view('\n');
  1145. // Now just trim each line and put them back in a string
  1146. StringBuilder builder { list.first().length() };
  1147. for (auto& line : lines) {
  1148. builder.append(line.trim_whitespace(TrimMode::Left));
  1149. builder.append('\n');
  1150. }
  1151. return make_ref_counted<StringValue>(builder.to_string());
  1152. }
  1153. void Heredoc::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1154. {
  1155. Line::Style content_style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  1156. if (metadata.is_first_in_list)
  1157. content_style.unify_with({ Line::Style::Bold });
  1158. if (!m_contents)
  1159. content_style.unify_with({ Line::Style::Foreground(Line::Style::XtermColor::Red) }, true);
  1160. editor.stylize({ m_position.start_offset, m_position.end_offset }, content_style);
  1161. if (m_contents)
  1162. m_contents->highlight_in_editor(editor, shell, metadata);
  1163. }
  1164. HitTestResult Heredoc::hit_test_position(size_t offset) const
  1165. {
  1166. if (!m_contents)
  1167. return {};
  1168. return m_contents->hit_test_position(offset);
  1169. }
  1170. Heredoc::Heredoc(Position position, String end, bool allow_interpolation, bool deindent)
  1171. : Node(move(position))
  1172. , m_end(move(end))
  1173. , m_allows_interpolation(allow_interpolation)
  1174. , m_deindent(deindent)
  1175. {
  1176. }
  1177. Heredoc::~Heredoc()
  1178. {
  1179. }
  1180. void HistoryEvent::dump(int level) const
  1181. {
  1182. Node::dump(level);
  1183. print_indented("Event Selector", level + 1);
  1184. switch (m_selector.event.kind) {
  1185. case HistorySelector::EventKind::IndexFromStart:
  1186. print_indented("IndexFromStart", level + 2);
  1187. break;
  1188. case HistorySelector::EventKind::IndexFromEnd:
  1189. print_indented("IndexFromEnd", level + 2);
  1190. break;
  1191. case HistorySelector::EventKind::ContainingStringLookup:
  1192. print_indented("ContainingStringLookup", level + 2);
  1193. break;
  1194. case HistorySelector::EventKind::StartingStringLookup:
  1195. print_indented("StartingStringLookup", level + 2);
  1196. break;
  1197. }
  1198. print_indented(String::formatted("{}({})", m_selector.event.index, m_selector.event.text), level + 3);
  1199. print_indented("Word Selector", level + 1);
  1200. auto print_word_selector = [&](HistorySelector::WordSelector const& selector) {
  1201. switch (selector.kind) {
  1202. case HistorySelector::WordSelectorKind::Index:
  1203. print_indented(String::formatted("Index {}", selector.selector), level + 3);
  1204. break;
  1205. case HistorySelector::WordSelectorKind::Last:
  1206. print_indented(String::formatted("Last"), level + 3);
  1207. break;
  1208. }
  1209. };
  1210. if (m_selector.word_selector_range.end.has_value()) {
  1211. print_indented("Range Start", level + 2);
  1212. print_word_selector(m_selector.word_selector_range.start);
  1213. print_indented("Range End", level + 2);
  1214. print_word_selector(m_selector.word_selector_range.end.value());
  1215. } else {
  1216. print_indented("Direct Address", level + 2);
  1217. print_word_selector(m_selector.word_selector_range.start);
  1218. }
  1219. }
  1220. RefPtr<Value> HistoryEvent::run(RefPtr<Shell> shell)
  1221. {
  1222. if (!shell)
  1223. return make_ref_counted<AST::ListValue>({});
  1224. auto editor = shell->editor();
  1225. if (!editor) {
  1226. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "No history available!", position());
  1227. return make_ref_counted<AST::ListValue>({});
  1228. }
  1229. auto& history = editor->history();
  1230. // FIXME: Implement reverse iterators and find()?
  1231. auto find_reverse = [](auto it_start, auto it_end, auto finder) {
  1232. auto it = it_end;
  1233. while (it != it_start) {
  1234. --it;
  1235. if (finder(*it))
  1236. return it;
  1237. }
  1238. return it_end;
  1239. };
  1240. // First, resolve the event itself.
  1241. String resolved_history;
  1242. switch (m_selector.event.kind) {
  1243. case HistorySelector::EventKind::IndexFromStart:
  1244. if (m_selector.event.index >= history.size()) {
  1245. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event index out of bounds", m_selector.event.text_position);
  1246. return make_ref_counted<AST::ListValue>({});
  1247. }
  1248. resolved_history = history[m_selector.event.index].entry;
  1249. break;
  1250. case HistorySelector::EventKind::IndexFromEnd:
  1251. if (m_selector.event.index >= history.size()) {
  1252. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event index out of bounds", m_selector.event.text_position);
  1253. return make_ref_counted<AST::ListValue>({});
  1254. }
  1255. resolved_history = history[history.size() - m_selector.event.index - 1].entry;
  1256. break;
  1257. case HistorySelector::EventKind::ContainingStringLookup: {
  1258. auto it = find_reverse(history.begin(), history.end(), [&](auto& entry) { return entry.entry.contains(m_selector.event.text); });
  1259. if (it.is_end()) {
  1260. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event did not match any entry", m_selector.event.text_position);
  1261. return make_ref_counted<AST::ListValue>({});
  1262. }
  1263. resolved_history = it->entry;
  1264. break;
  1265. }
  1266. case HistorySelector::EventKind::StartingStringLookup: {
  1267. auto it = find_reverse(history.begin(), history.end(), [&](auto& entry) { return entry.entry.starts_with(m_selector.event.text); });
  1268. if (it.is_end()) {
  1269. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History event did not match any entry", m_selector.event.text_position);
  1270. return make_ref_counted<AST::ListValue>({});
  1271. }
  1272. resolved_history = it->entry;
  1273. break;
  1274. }
  1275. }
  1276. // Then, split it up to "words".
  1277. auto nodes = Parser { resolved_history }.parse_as_multiple_expressions();
  1278. // Now take the "words" as described by the word selectors.
  1279. bool is_range = m_selector.word_selector_range.end.has_value();
  1280. if (is_range) {
  1281. auto start_index = m_selector.word_selector_range.start.resolve(nodes.size());
  1282. auto end_index = m_selector.word_selector_range.end->resolve(nodes.size());
  1283. if (start_index >= nodes.size()) {
  1284. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History word index out of bounds", m_selector.word_selector_range.start.position);
  1285. return make_ref_counted<AST::ListValue>({});
  1286. }
  1287. if (end_index >= nodes.size()) {
  1288. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History word index out of bounds", m_selector.word_selector_range.end->position);
  1289. return make_ref_counted<AST::ListValue>({});
  1290. }
  1291. decltype(nodes) resolved_nodes;
  1292. resolved_nodes.append(nodes.data() + start_index, end_index - start_index + 1);
  1293. NonnullRefPtr<AST::Node> list = make_ref_counted<AST::ListConcatenate>(position(), move(resolved_nodes));
  1294. return list->run(shell);
  1295. }
  1296. auto index = m_selector.word_selector_range.start.resolve(nodes.size());
  1297. if (index >= nodes.size()) {
  1298. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "History word index out of bounds", m_selector.word_selector_range.start.position);
  1299. return make_ref_counted<AST::ListValue>({});
  1300. }
  1301. return nodes[index].run(shell);
  1302. }
  1303. void HistoryEvent::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  1304. {
  1305. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Green) };
  1306. if (metadata.is_first_in_list)
  1307. style.unify_with({ Line::Style::Bold });
  1308. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  1309. }
  1310. HistoryEvent::HistoryEvent(Position position, HistorySelector selector)
  1311. : Node(move(position))
  1312. , m_selector(move(selector))
  1313. {
  1314. if (m_selector.word_selector_range.start.syntax_error_node)
  1315. set_is_syntax_error(*m_selector.word_selector_range.start.syntax_error_node);
  1316. else if (m_selector.word_selector_range.end.has_value() && m_selector.word_selector_range.end->syntax_error_node)
  1317. set_is_syntax_error(*m_selector.word_selector_range.end->syntax_error_node);
  1318. }
  1319. HistoryEvent::~HistoryEvent()
  1320. {
  1321. }
  1322. void Execute::dump(int level) const
  1323. {
  1324. Node::dump(level);
  1325. if (m_capture_stdout)
  1326. print_indented("(Capturing stdout)", level + 1);
  1327. m_command->dump(level + 1);
  1328. }
  1329. void Execute::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(NonnullRefPtr<Value>)> callback)
  1330. {
  1331. if (m_command->would_execute())
  1332. return m_command->for_each_entry(shell, move(callback));
  1333. auto unexpanded_commands = m_command->run(shell)->resolve_as_commands(shell);
  1334. if (shell && shell->has_any_error())
  1335. return;
  1336. if (!shell)
  1337. return;
  1338. auto commands = shell->expand_aliases(move(unexpanded_commands));
  1339. if (m_capture_stdout) {
  1340. // Make sure that we're going to be running _something_.
  1341. auto has_one_command = false;
  1342. for (auto& command : commands) {
  1343. if (command.argv.is_empty() && !command.pipeline && command.next_chain.is_empty())
  1344. continue;
  1345. has_one_command = true;
  1346. break;
  1347. }
  1348. if (!has_one_command) {
  1349. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Cannot capture standard output when no command is being executed", m_position);
  1350. return;
  1351. }
  1352. int pipefd[2];
  1353. int rc = pipe(pipefd);
  1354. if (rc < 0) {
  1355. dbgln("Error: cannot pipe(): {}", strerror(errno));
  1356. return;
  1357. }
  1358. auto& last_in_commands = commands.last();
  1359. last_in_commands.redirections.prepend(FdRedirection::create(pipefd[1], STDOUT_FILENO, Rewiring::Close::Old));
  1360. last_in_commands.should_wait = false;
  1361. last_in_commands.should_notify_if_in_background = false;
  1362. last_in_commands.is_pipe_source = false;
  1363. Core::EventLoop loop;
  1364. auto notifier = Core::Notifier::construct(pipefd[0], Core::Notifier::Read);
  1365. DuplexMemoryStream stream;
  1366. enum {
  1367. Continue,
  1368. Break,
  1369. NothingLeft,
  1370. };
  1371. auto check_and_call = [&] {
  1372. auto ifs = shell->local_variable_or("IFS", "\n");
  1373. if (auto offset = stream.offset_of(ifs.bytes()); offset.has_value()) {
  1374. auto line_end = offset.value();
  1375. if (line_end == 0) {
  1376. auto rc = stream.discard_or_error(ifs.length());
  1377. VERIFY(rc);
  1378. if (shell->options.inline_exec_keep_empty_segments)
  1379. if (callback(make_ref_counted<StringValue>("")) == IterationDecision::Break) {
  1380. loop.quit(Break);
  1381. notifier->set_enabled(false);
  1382. return Break;
  1383. }
  1384. } else {
  1385. auto entry_result = ByteBuffer::create_uninitialized(line_end + ifs.length());
  1386. if (entry_result.is_error()) {
  1387. loop.quit(Break);
  1388. notifier->set_enabled(false);
  1389. return Break;
  1390. }
  1391. auto entry = entry_result.release_value();
  1392. auto rc = stream.read_or_error(entry);
  1393. VERIFY(rc);
  1394. auto str = StringView(entry.data(), entry.size() - ifs.length());
  1395. if (callback(make_ref_counted<StringValue>(str)) == IterationDecision::Break) {
  1396. loop.quit(Break);
  1397. notifier->set_enabled(false);
  1398. return Break;
  1399. }
  1400. }
  1401. return Continue;
  1402. }
  1403. return NothingLeft;
  1404. };
  1405. notifier->on_ready_to_read = [&] {
  1406. constexpr static auto buffer_size = 16;
  1407. u8 buffer[buffer_size];
  1408. size_t remaining_size = buffer_size;
  1409. for (;;) {
  1410. notifier->set_event_mask(Core::Notifier::None);
  1411. bool should_enable_notifier = false;
  1412. ScopeGuard notifier_enabler { [&] {
  1413. if (should_enable_notifier)
  1414. notifier->set_event_mask(Core::Notifier::Read);
  1415. } };
  1416. if (check_and_call() == Break) {
  1417. loop.quit(Break);
  1418. return;
  1419. }
  1420. auto read_size = read(pipefd[0], buffer, remaining_size);
  1421. if (read_size < 0) {
  1422. int saved_errno = errno;
  1423. if (saved_errno == EINTR) {
  1424. should_enable_notifier = true;
  1425. continue;
  1426. }
  1427. if (saved_errno == 0)
  1428. continue;
  1429. dbgln("read() failed: {}", strerror(saved_errno));
  1430. break;
  1431. }
  1432. if (read_size == 0)
  1433. break;
  1434. should_enable_notifier = true;
  1435. stream.write({ buffer, (size_t)read_size });
  1436. }
  1437. loop.quit(NothingLeft);
  1438. };
  1439. auto jobs = shell->run_commands(commands);
  1440. ScopeGuard kill_jobs_if_around { [&] {
  1441. for (auto& job : jobs) {
  1442. if (job.is_running_in_background() && !job.exited() && !job.signaled()) {
  1443. job.set_should_announce_signal(false); // We're explicitly killing it here.
  1444. shell->kill_job(&job, SIGTERM);
  1445. }
  1446. }
  1447. } };
  1448. auto exit_reason = loop.exec();
  1449. notifier->on_ready_to_read = nullptr;
  1450. if (close(pipefd[0]) < 0) {
  1451. dbgln("close() failed: {}", strerror(errno));
  1452. }
  1453. if (exit_reason != Break && !stream.eof()) {
  1454. auto action = Continue;
  1455. do {
  1456. action = check_and_call();
  1457. if (action == Break)
  1458. return;
  1459. } while (action == Continue);
  1460. if (!stream.eof()) {
  1461. auto entry_result = ByteBuffer::create_uninitialized(stream.size());
  1462. if (entry_result.is_error()) {
  1463. shell->raise_error(Shell::ShellError::OutOfMemory, {}, position());
  1464. return;
  1465. }
  1466. auto entry = entry_result.release_value();
  1467. auto rc = stream.read_or_error(entry);
  1468. VERIFY(rc);
  1469. callback(make_ref_counted<StringValue>(String::copy(entry)));
  1470. }
  1471. }
  1472. return;
  1473. }
  1474. auto jobs = shell->run_commands(commands);
  1475. if (!jobs.is_empty())
  1476. callback(make_ref_counted<JobValue>(&jobs.last()));
  1477. }
  1478. RefPtr<Value> Execute::run(RefPtr<Shell> shell)
  1479. {
  1480. if (shell && shell->has_any_error())
  1481. return make_ref_counted<ListValue>({});
  1482. if (m_command->would_execute())
  1483. return m_command->run(shell);
  1484. NonnullRefPtrVector<Value> values;
  1485. for_each_entry(shell, [&](auto value) {
  1486. values.append(*value);
  1487. return IterationDecision::Continue;
  1488. });
  1489. if (values.size() == 1 && values.first().is_job())
  1490. return values.first();
  1491. return make_ref_counted<ListValue>(move(values));
  1492. }
  1493. void Execute::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1494. {
  1495. if (m_capture_stdout)
  1496. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  1497. metadata.is_first_in_list = true;
  1498. m_command->highlight_in_editor(editor, shell, metadata);
  1499. }
  1500. HitTestResult Execute::hit_test_position(size_t offset) const
  1501. {
  1502. auto result = m_command->hit_test_position(offset);
  1503. if (!result.closest_node_with_semantic_meaning)
  1504. result.closest_node_with_semantic_meaning = this;
  1505. if (!result.closest_command_node)
  1506. result.closest_command_node = m_command;
  1507. return result;
  1508. }
  1509. Vector<Line::CompletionSuggestion> Execute::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
  1510. {
  1511. auto matching_node = hit_test_result.matching_node;
  1512. if (!matching_node || !matching_node->is_bareword())
  1513. return {};
  1514. auto corrected_offset = offset - matching_node->position().start_offset;
  1515. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  1516. if (corrected_offset > node->text().length())
  1517. return {};
  1518. return shell.complete_program_name(node->text(), corrected_offset);
  1519. }
  1520. Execute::Execute(Position position, NonnullRefPtr<Node> command, bool capture_stdout)
  1521. : Node(move(position))
  1522. , m_command(move(command))
  1523. , m_capture_stdout(capture_stdout)
  1524. {
  1525. if (m_command->is_syntax_error())
  1526. set_is_syntax_error(m_command->syntax_error_node());
  1527. }
  1528. Execute::~Execute()
  1529. {
  1530. }
  1531. void IfCond::dump(int level) const
  1532. {
  1533. Node::dump(level);
  1534. print_indented("Condition", ++level);
  1535. m_condition->dump(level + 1);
  1536. print_indented("True Branch", level);
  1537. if (m_true_branch)
  1538. m_true_branch->dump(level + 1);
  1539. else
  1540. print_indented("(empty)", level + 1);
  1541. print_indented("False Branch", level);
  1542. if (m_false_branch)
  1543. m_false_branch->dump(level + 1);
  1544. else
  1545. print_indented("(empty)", level + 1);
  1546. }
  1547. RefPtr<Value> IfCond::run(RefPtr<Shell> shell)
  1548. {
  1549. auto cond = m_condition->run(shell)->resolve_without_cast(shell);
  1550. if (shell && shell->has_any_error())
  1551. return make_ref_counted<ListValue>({});
  1552. // The condition could be a builtin, in which case it has already run and exited.
  1553. if (cond->is_job()) {
  1554. auto cond_job_value = static_cast<JobValue const*>(cond.ptr());
  1555. auto cond_job = cond_job_value->job();
  1556. shell->block_on_job(cond_job);
  1557. }
  1558. if (shell->last_return_code == 0) {
  1559. if (m_true_branch)
  1560. return m_true_branch->run(shell);
  1561. } else {
  1562. if (m_false_branch)
  1563. return m_false_branch->run(shell);
  1564. }
  1565. return make_ref_counted<ListValue>({});
  1566. }
  1567. void IfCond::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1568. {
  1569. metadata.is_first_in_list = true;
  1570. editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1571. if (m_else_position.has_value())
  1572. editor.stylize({ m_else_position.value().start_offset, m_else_position.value().start_offset + 4 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1573. m_condition->highlight_in_editor(editor, shell, metadata);
  1574. if (m_true_branch)
  1575. m_true_branch->highlight_in_editor(editor, shell, metadata);
  1576. if (m_false_branch)
  1577. m_false_branch->highlight_in_editor(editor, shell, metadata);
  1578. }
  1579. HitTestResult IfCond::hit_test_position(size_t offset) const
  1580. {
  1581. if (auto result = m_condition->hit_test_position(offset); result.matching_node)
  1582. return result;
  1583. if (m_true_branch) {
  1584. if (auto result = m_true_branch->hit_test_position(offset); result.matching_node)
  1585. return result;
  1586. }
  1587. if (m_false_branch) {
  1588. if (auto result = m_false_branch->hit_test_position(offset); result.matching_node)
  1589. return result;
  1590. }
  1591. return {};
  1592. }
  1593. IfCond::IfCond(Position position, Optional<Position> else_position, NonnullRefPtr<Node> condition, RefPtr<Node> true_branch, RefPtr<Node> false_branch)
  1594. : Node(move(position))
  1595. , m_condition(move(condition))
  1596. , m_true_branch(move(true_branch))
  1597. , m_false_branch(move(false_branch))
  1598. , m_else_position(move(else_position))
  1599. {
  1600. if (m_condition->is_syntax_error())
  1601. set_is_syntax_error(m_condition->syntax_error_node());
  1602. else if (m_true_branch && m_true_branch->is_syntax_error())
  1603. set_is_syntax_error(m_true_branch->syntax_error_node());
  1604. else if (m_false_branch && m_false_branch->is_syntax_error())
  1605. set_is_syntax_error(m_false_branch->syntax_error_node());
  1606. m_condition = make_ref_counted<AST::Execute>(m_condition->position(), m_condition);
  1607. if (m_true_branch) {
  1608. auto true_branch = m_true_branch.release_nonnull();
  1609. if (true_branch->is_execute())
  1610. m_true_branch = static_ptr_cast<AST::Execute>(true_branch)->command();
  1611. else
  1612. m_true_branch = move(true_branch);
  1613. }
  1614. if (m_false_branch) {
  1615. auto false_branch = m_false_branch.release_nonnull();
  1616. if (false_branch->is_execute())
  1617. m_false_branch = static_ptr_cast<AST::Execute>(false_branch)->command();
  1618. else
  1619. m_false_branch = move(false_branch);
  1620. }
  1621. }
  1622. IfCond::~IfCond()
  1623. {
  1624. }
  1625. void ImmediateExpression::dump(int level) const
  1626. {
  1627. Node::dump(level);
  1628. print_indented("(function)", level + 1);
  1629. print_indented(m_function.name, level + 2);
  1630. print_indented("(arguments)", level + 1);
  1631. for (auto& argument : arguments())
  1632. argument.dump(level + 2);
  1633. }
  1634. RefPtr<Value> ImmediateExpression::run(RefPtr<Shell> shell)
  1635. {
  1636. auto node = shell->run_immediate_function(m_function.name, *this, arguments());
  1637. if (node)
  1638. return node->run(shell);
  1639. return make_ref_counted<ListValue>({});
  1640. }
  1641. void ImmediateExpression::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1642. {
  1643. // '${' - FIXME: This could also be '$\\\n{'
  1644. editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  1645. // Function name
  1646. Line::Style function_style { Line::Style::Foreground(Line::Style::XtermColor::Red) };
  1647. if (shell.has_immediate_function(function_name()))
  1648. function_style = { Line::Style::Foreground(Line::Style::XtermColor::Green) };
  1649. editor.stylize({ m_function.position.start_offset, m_function.position.end_offset }, move(function_style));
  1650. // Arguments
  1651. for (auto& argument : m_arguments) {
  1652. metadata.is_first_in_list = false;
  1653. argument.highlight_in_editor(editor, shell, metadata);
  1654. }
  1655. // Closing brace
  1656. if (m_closing_brace_position.has_value())
  1657. editor.stylize({ m_closing_brace_position->start_offset, m_closing_brace_position->end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  1658. }
  1659. Vector<Line::CompletionSuggestion> ImmediateExpression::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
  1660. {
  1661. auto matching_node = hit_test_result.matching_node;
  1662. if (!matching_node || matching_node != this)
  1663. return {};
  1664. auto corrected_offset = offset - m_function.position.start_offset;
  1665. if (corrected_offset > m_function.name.length())
  1666. return {};
  1667. return shell.complete_immediate_function_name(m_function.name, corrected_offset);
  1668. }
  1669. HitTestResult ImmediateExpression::hit_test_position(size_t offset) const
  1670. {
  1671. if (m_function.position.contains(offset))
  1672. return { this, this, this };
  1673. for (auto& argument : m_arguments) {
  1674. if (auto result = argument.hit_test_position(offset); result.matching_node)
  1675. return result;
  1676. }
  1677. return {};
  1678. }
  1679. ImmediateExpression::ImmediateExpression(Position position, NameWithPosition function, NonnullRefPtrVector<AST::Node> arguments, Optional<Position> closing_brace_position)
  1680. : Node(move(position))
  1681. , m_arguments(move(arguments))
  1682. , m_function(move(function))
  1683. , m_closing_brace_position(move(closing_brace_position))
  1684. {
  1685. if (is_syntax_error())
  1686. return;
  1687. for (auto& argument : m_arguments) {
  1688. if (argument.is_syntax_error()) {
  1689. set_is_syntax_error(argument.syntax_error_node());
  1690. return;
  1691. }
  1692. }
  1693. }
  1694. ImmediateExpression::~ImmediateExpression()
  1695. {
  1696. }
  1697. void Join::dump(int level) const
  1698. {
  1699. Node::dump(level);
  1700. m_left->dump(level + 1);
  1701. m_right->dump(level + 1);
  1702. }
  1703. RefPtr<Value> Join::run(RefPtr<Shell> shell)
  1704. {
  1705. auto left = m_left->to_lazy_evaluated_commands(shell);
  1706. if (shell && shell->has_any_error())
  1707. return make_ref_counted<ListValue>({});
  1708. if (left.last().should_wait && !left.last().next_chain.is_empty()) {
  1709. // Join (C0s*; C1) X -> (C0s*; Join C1 X)
  1710. auto& lhs_node = left.last().next_chain.last().node;
  1711. lhs_node = make_ref_counted<Join>(m_position, lhs_node, m_right);
  1712. return make_ref_counted<CommandSequenceValue>(move(left));
  1713. }
  1714. auto right = m_right->to_lazy_evaluated_commands(shell);
  1715. if (shell && shell->has_any_error())
  1716. return make_ref_counted<ListValue>({});
  1717. return make_ref_counted<CommandSequenceValue>(join_commands(move(left), move(right)));
  1718. }
  1719. void Join::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1720. {
  1721. m_left->highlight_in_editor(editor, shell, metadata);
  1722. if (m_left->is_list() || m_left->is_command())
  1723. metadata.is_first_in_list = false;
  1724. m_right->highlight_in_editor(editor, shell, metadata);
  1725. }
  1726. HitTestResult Join::hit_test_position(size_t offset) const
  1727. {
  1728. auto result = m_left->hit_test_position(offset);
  1729. if (result.matching_node)
  1730. return result;
  1731. return m_right->hit_test_position(offset);
  1732. }
  1733. RefPtr<Node> Join::leftmost_trivial_literal() const
  1734. {
  1735. if (auto value = m_left->leftmost_trivial_literal())
  1736. return value;
  1737. return m_right->leftmost_trivial_literal();
  1738. }
  1739. Join::Join(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  1740. : Node(move(position))
  1741. , m_left(move(left))
  1742. , m_right(move(right))
  1743. {
  1744. if (m_left->is_syntax_error())
  1745. set_is_syntax_error(m_left->syntax_error_node());
  1746. else if (m_right->is_syntax_error())
  1747. set_is_syntax_error(m_right->syntax_error_node());
  1748. }
  1749. Join::~Join()
  1750. {
  1751. }
  1752. void MatchExpr::dump(int level) const
  1753. {
  1754. Node::dump(level);
  1755. print_indented(String::formatted("(expression: {})", m_expr_name.characters()), level + 1);
  1756. m_matched_expr->dump(level + 2);
  1757. print_indented(String::formatted("(named: {})", m_expr_name.characters()), level + 1);
  1758. print_indented("(entries)", level + 1);
  1759. for (auto& entry : m_entries) {
  1760. StringBuilder builder;
  1761. builder.append("(match");
  1762. if (entry.match_names.has_value()) {
  1763. builder.append(" to names (");
  1764. bool first = true;
  1765. for (auto& name : entry.match_names.value()) {
  1766. if (!first)
  1767. builder.append(' ');
  1768. first = false;
  1769. builder.append(name);
  1770. }
  1771. builder.append("))");
  1772. } else {
  1773. builder.append(')');
  1774. }
  1775. print_indented(builder.string_view(), level + 2);
  1776. for (auto& node : entry.options)
  1777. node.dump(level + 3);
  1778. print_indented("(execute)", level + 2);
  1779. if (entry.body)
  1780. entry.body->dump(level + 3);
  1781. else
  1782. print_indented("(nothing)", level + 3);
  1783. }
  1784. }
  1785. RefPtr<Value> MatchExpr::run(RefPtr<Shell> shell)
  1786. {
  1787. auto value = m_matched_expr->run(shell)->resolve_without_cast(shell);
  1788. if (shell && shell->has_any_error())
  1789. return make_ref_counted<ListValue>({});
  1790. auto list = value->resolve_as_list(shell);
  1791. auto list_matches = [&](auto&& pattern, auto& spans) {
  1792. if (pattern.size() != list.size())
  1793. return false;
  1794. for (size_t i = 0; i < pattern.size(); ++i) {
  1795. Vector<AK::MaskSpan> mask_spans;
  1796. if (!list[i].matches(pattern[i], mask_spans))
  1797. return false;
  1798. for (auto& span : mask_spans)
  1799. spans.append(list[i].substring(span.start, span.length));
  1800. }
  1801. return true;
  1802. };
  1803. auto resolve_pattern = [&](auto& option) {
  1804. Vector<String> pattern;
  1805. if (option.is_glob()) {
  1806. pattern.append(static_cast<const Glob*>(&option)->text());
  1807. } else if (option.is_bareword()) {
  1808. pattern.append(static_cast<const BarewordLiteral*>(&option)->text());
  1809. } else {
  1810. auto list = option.run(shell);
  1811. if (shell && shell->has_any_error())
  1812. return pattern;
  1813. option.for_each_entry(shell, [&](auto&& value) {
  1814. pattern.extend(value->resolve_as_list(nullptr)); // Note: 'nullptr' incurs special behavior,
  1815. // asking the node for a 'raw' value.
  1816. return IterationDecision::Continue;
  1817. });
  1818. }
  1819. return pattern;
  1820. };
  1821. auto frame = shell->push_frame(String::formatted("match ({})", this));
  1822. if (!m_expr_name.is_empty())
  1823. shell->set_local_variable(m_expr_name, value, true);
  1824. for (auto& entry : m_entries) {
  1825. for (auto& option : entry.options) {
  1826. Vector<String> spans;
  1827. if (list_matches(resolve_pattern(option), spans)) {
  1828. if (entry.body) {
  1829. if (entry.match_names.has_value()) {
  1830. size_t i = 0;
  1831. for (auto& name : entry.match_names.value()) {
  1832. if (spans.size() > i)
  1833. shell->set_local_variable(name, make_ref_counted<AST::StringValue>(spans[i]), true);
  1834. ++i;
  1835. }
  1836. }
  1837. return entry.body->run(shell);
  1838. } else {
  1839. return make_ref_counted<AST::ListValue>({});
  1840. }
  1841. }
  1842. }
  1843. }
  1844. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Non-exhaustive match rules!", position());
  1845. return make_ref_counted<AST::ListValue>({});
  1846. }
  1847. void MatchExpr::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1848. {
  1849. editor.stylize({ m_position.start_offset, m_position.start_offset + 5 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1850. if (m_as_position.has_value())
  1851. editor.stylize({ m_as_position.value().start_offset, m_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1852. metadata.is_first_in_list = false;
  1853. m_matched_expr->highlight_in_editor(editor, shell, metadata);
  1854. for (auto& entry : m_entries) {
  1855. metadata.is_first_in_list = false;
  1856. for (auto& option : entry.options)
  1857. option.highlight_in_editor(editor, shell, metadata);
  1858. metadata.is_first_in_list = true;
  1859. if (entry.body)
  1860. entry.body->highlight_in_editor(editor, shell, metadata);
  1861. for (auto& position : entry.pipe_positions)
  1862. editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1863. if (entry.match_as_position.has_value())
  1864. editor.stylize({ entry.match_as_position.value().start_offset, entry.match_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1865. }
  1866. }
  1867. HitTestResult MatchExpr::hit_test_position(size_t offset) const
  1868. {
  1869. auto result = m_matched_expr->hit_test_position(offset);
  1870. if (result.matching_node)
  1871. return result;
  1872. for (auto& entry : m_entries) {
  1873. if (!entry.body)
  1874. continue;
  1875. auto result = entry.body->hit_test_position(offset);
  1876. if (result.matching_node)
  1877. return result;
  1878. }
  1879. return {};
  1880. }
  1881. MatchExpr::MatchExpr(Position position, NonnullRefPtr<Node> expr, String name, Optional<Position> as_position, Vector<MatchEntry> entries)
  1882. : Node(move(position))
  1883. , m_matched_expr(move(expr))
  1884. , m_expr_name(move(name))
  1885. , m_as_position(move(as_position))
  1886. , m_entries(move(entries))
  1887. {
  1888. if (m_matched_expr->is_syntax_error()) {
  1889. set_is_syntax_error(m_matched_expr->syntax_error_node());
  1890. } else {
  1891. for (auto& entry : m_entries) {
  1892. if (!entry.body)
  1893. continue;
  1894. if (entry.body->is_syntax_error()) {
  1895. set_is_syntax_error(entry.body->syntax_error_node());
  1896. break;
  1897. }
  1898. }
  1899. }
  1900. }
  1901. MatchExpr::~MatchExpr()
  1902. {
  1903. }
  1904. void Or::dump(int level) const
  1905. {
  1906. Node::dump(level);
  1907. m_left->dump(level + 1);
  1908. m_right->dump(level + 1);
  1909. }
  1910. RefPtr<Value> Or::run(RefPtr<Shell> shell)
  1911. {
  1912. auto commands = m_left->to_lazy_evaluated_commands(shell);
  1913. if (shell && shell->has_any_error())
  1914. return make_ref_counted<ListValue>({});
  1915. commands.last().next_chain.empend(*m_right, NodeWithAction::Or);
  1916. return make_ref_counted<CommandSequenceValue>(move(commands));
  1917. }
  1918. void Or::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1919. {
  1920. m_left->highlight_in_editor(editor, shell, metadata);
  1921. m_right->highlight_in_editor(editor, shell, metadata);
  1922. }
  1923. HitTestResult Or::hit_test_position(size_t offset) const
  1924. {
  1925. auto result = m_left->hit_test_position(offset);
  1926. if (result.matching_node) {
  1927. if (!result.closest_command_node)
  1928. result.closest_command_node = m_right;
  1929. return result;
  1930. }
  1931. result = m_right->hit_test_position(offset);
  1932. if (!result.closest_command_node)
  1933. result.closest_command_node = m_right;
  1934. return result;
  1935. }
  1936. Or::Or(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position or_position)
  1937. : Node(move(position))
  1938. , m_left(move(left))
  1939. , m_right(move(right))
  1940. , m_or_position(or_position)
  1941. {
  1942. if (m_left->is_syntax_error())
  1943. set_is_syntax_error(m_left->syntax_error_node());
  1944. else if (m_right->is_syntax_error())
  1945. set_is_syntax_error(m_right->syntax_error_node());
  1946. }
  1947. Or::~Or()
  1948. {
  1949. }
  1950. void Pipe::dump(int level) const
  1951. {
  1952. Node::dump(level);
  1953. m_left->dump(level + 1);
  1954. m_right->dump(level + 1);
  1955. }
  1956. RefPtr<Value> Pipe::run(RefPtr<Shell> shell)
  1957. {
  1958. auto left = m_left->to_lazy_evaluated_commands(shell);
  1959. if (shell && shell->has_any_error())
  1960. return make_ref_counted<ListValue>({});
  1961. auto right = m_right->to_lazy_evaluated_commands(shell);
  1962. if (shell && shell->has_any_error())
  1963. return make_ref_counted<ListValue>({});
  1964. auto last_in_left = left.take_last();
  1965. auto first_in_right = right.take_first();
  1966. auto pipe_read_end = FdRedirection::create(-1, STDIN_FILENO, Rewiring::Close::Old);
  1967. auto pipe_write_end = FdRedirection::create(-1, STDOUT_FILENO, pipe_read_end, Rewiring::Close::RefreshOld);
  1968. auto insert_at_start_or_after_last_pipe = [&](auto& pipe, auto& command) {
  1969. size_t insert_index = 0;
  1970. auto& redirections = command.redirections;
  1971. for (ssize_t i = redirections.size() - 1; i >= 0; --i) {
  1972. auto& redirection = redirections[i];
  1973. if (!redirection.is_fd_redirection())
  1974. continue;
  1975. auto& fd_redirection = static_cast<FdRedirection&>(redirection);
  1976. if (fd_redirection.old_fd == -1) {
  1977. insert_index = i;
  1978. break;
  1979. }
  1980. }
  1981. redirections.insert(insert_index, pipe);
  1982. };
  1983. insert_at_start_or_after_last_pipe(pipe_read_end, first_in_right);
  1984. insert_at_start_or_after_last_pipe(pipe_write_end, last_in_left);
  1985. last_in_left.should_wait = false;
  1986. last_in_left.is_pipe_source = true;
  1987. if (first_in_right.pipeline) {
  1988. last_in_left.pipeline = first_in_right.pipeline;
  1989. } else {
  1990. auto pipeline = make_ref_counted<Pipeline>();
  1991. last_in_left.pipeline = pipeline;
  1992. first_in_right.pipeline = pipeline;
  1993. }
  1994. Vector<Command> commands;
  1995. commands.extend(left);
  1996. commands.append(last_in_left);
  1997. commands.append(first_in_right);
  1998. commands.extend(right);
  1999. return make_ref_counted<CommandSequenceValue>(move(commands));
  2000. }
  2001. void Pipe::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2002. {
  2003. m_left->highlight_in_editor(editor, shell, metadata);
  2004. m_right->highlight_in_editor(editor, shell, metadata);
  2005. }
  2006. HitTestResult Pipe::hit_test_position(size_t offset) const
  2007. {
  2008. auto result = m_left->hit_test_position(offset);
  2009. if (result.matching_node) {
  2010. if (!result.closest_command_node)
  2011. result.closest_command_node = m_right;
  2012. return result;
  2013. }
  2014. result = m_right->hit_test_position(offset);
  2015. if (!result.closest_command_node)
  2016. result.closest_command_node = m_right;
  2017. return result;
  2018. }
  2019. Pipe::Pipe(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  2020. : Node(move(position))
  2021. , m_left(move(left))
  2022. , m_right(move(right))
  2023. {
  2024. if (m_left->is_syntax_error())
  2025. set_is_syntax_error(m_left->syntax_error_node());
  2026. else if (m_right->is_syntax_error())
  2027. set_is_syntax_error(m_right->syntax_error_node());
  2028. }
  2029. Pipe::~Pipe()
  2030. {
  2031. }
  2032. PathRedirectionNode::PathRedirectionNode(Position position, int fd, NonnullRefPtr<Node> path)
  2033. : Node(move(position))
  2034. , m_fd(fd)
  2035. , m_path(move(path))
  2036. {
  2037. }
  2038. void PathRedirectionNode::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2039. {
  2040. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  2041. metadata.is_first_in_list = false;
  2042. m_path->highlight_in_editor(editor, shell, metadata);
  2043. if (m_path->is_bareword()) {
  2044. auto path_text = m_path->run(nullptr)->resolve_as_list(nullptr);
  2045. VERIFY(path_text.size() == 1);
  2046. // Apply a URL to the path.
  2047. auto& position = m_path->position();
  2048. auto& path = path_text[0];
  2049. if (!path.starts_with('/'))
  2050. path = String::formatted("{}/{}", shell.cwd, path);
  2051. auto url = URL::create_with_file_protocol(path);
  2052. url.set_host(shell.hostname);
  2053. editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  2054. }
  2055. }
  2056. HitTestResult PathRedirectionNode::hit_test_position(size_t offset) const
  2057. {
  2058. auto result = m_path->hit_test_position(offset);
  2059. if (!result.closest_node_with_semantic_meaning)
  2060. result.closest_node_with_semantic_meaning = this;
  2061. return result;
  2062. }
  2063. Vector<Line::CompletionSuggestion> PathRedirectionNode::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
  2064. {
  2065. auto matching_node = hit_test_result.matching_node;
  2066. if (!matching_node || !matching_node->is_bareword())
  2067. return {};
  2068. auto corrected_offset = offset - matching_node->position().start_offset;
  2069. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  2070. if (corrected_offset > node->text().length())
  2071. return {};
  2072. return shell.complete_path("", node->text(), corrected_offset, Shell::ExecutableOnly::No, nullptr, nullptr);
  2073. }
  2074. PathRedirectionNode::~PathRedirectionNode()
  2075. {
  2076. }
  2077. void Range::dump(int level) const
  2078. {
  2079. Node::dump(level);
  2080. print_indented("(From)", level + 1);
  2081. m_start->dump(level + 2);
  2082. print_indented("(To)", level + 1);
  2083. m_end->dump(level + 2);
  2084. }
  2085. RefPtr<Value> Range::run(RefPtr<Shell> shell)
  2086. {
  2087. auto interpolate = [position = position()](RefPtr<Value> start, RefPtr<Value> end, RefPtr<Shell> shell) -> NonnullRefPtrVector<Value> {
  2088. NonnullRefPtrVector<Value> values;
  2089. if (start->is_string() && end->is_string()) {
  2090. auto start_str = start->resolve_as_list(shell)[0];
  2091. auto end_str = end->resolve_as_list(shell)[0];
  2092. Utf8View start_view { start_str }, end_view { end_str };
  2093. if (start_view.validate() && end_view.validate()) {
  2094. if (start_view.length() == 1 && end_view.length() == 1) {
  2095. // Interpolate between two code points.
  2096. auto start_code_point = *start_view.begin();
  2097. auto end_code_point = *end_view.begin();
  2098. auto step = start_code_point > end_code_point ? -1 : 1;
  2099. StringBuilder builder;
  2100. for (u32 code_point = start_code_point; code_point != end_code_point; code_point += step) {
  2101. builder.clear();
  2102. builder.append_code_point(code_point);
  2103. values.append(make_ref_counted<StringValue>(builder.to_string()));
  2104. }
  2105. // Append the ending code point too, most shells treat this as inclusive.
  2106. builder.clear();
  2107. builder.append_code_point(end_code_point);
  2108. values.append(make_ref_counted<StringValue>(builder.to_string()));
  2109. } else {
  2110. // Could be two numbers?
  2111. auto start_int = start_str.to_int();
  2112. auto end_int = end_str.to_int();
  2113. if (start_int.has_value() && end_int.has_value()) {
  2114. auto start = start_int.value();
  2115. auto end = end_int.value();
  2116. auto step = start > end ? -1 : 1;
  2117. for (int value = start; value != end; value += step)
  2118. values.append(make_ref_counted<StringValue>(String::number(value)));
  2119. // Append the range end too, most shells treat this as inclusive.
  2120. values.append(make_ref_counted<StringValue>(String::number(end)));
  2121. } else {
  2122. goto yield_start_end;
  2123. }
  2124. }
  2125. } else {
  2126. yield_start_end:;
  2127. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, String::formatted("Cannot interpolate between '{}' and '{}'!", start_str, end_str), position);
  2128. // We can't really interpolate between the two, so just yield both.
  2129. values.append(make_ref_counted<StringValue>(move(start_str)));
  2130. values.append(make_ref_counted<StringValue>(move(end_str)));
  2131. }
  2132. return values;
  2133. }
  2134. warnln("Shell: Cannot apply the requested interpolation");
  2135. return values;
  2136. };
  2137. auto start_value = m_start->run(shell);
  2138. if (shell && shell->has_any_error())
  2139. return make_ref_counted<ListValue>({});
  2140. auto end_value = m_end->run(shell);
  2141. if (shell && shell->has_any_error())
  2142. return make_ref_counted<ListValue>({});
  2143. if (!start_value || !end_value)
  2144. return make_ref_counted<ListValue>({});
  2145. return make_ref_counted<ListValue>(interpolate(*start_value, *end_value, shell));
  2146. }
  2147. void Range::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2148. {
  2149. m_start->highlight_in_editor(editor, shell, metadata);
  2150. // Highlight the '..'
  2151. editor.stylize({ m_start->position().end_offset, m_end->position().start_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  2152. metadata.is_first_in_list = false;
  2153. m_end->highlight_in_editor(editor, shell, metadata);
  2154. }
  2155. HitTestResult Range::hit_test_position(size_t offset) const
  2156. {
  2157. auto result = m_start->hit_test_position(offset);
  2158. if (result.matching_node) {
  2159. if (!result.closest_command_node)
  2160. result.closest_command_node = m_start;
  2161. return result;
  2162. }
  2163. result = m_end->hit_test_position(offset);
  2164. if (!result.closest_command_node)
  2165. result.closest_command_node = m_end;
  2166. return result;
  2167. }
  2168. Range::Range(Position position, NonnullRefPtr<Node> start, NonnullRefPtr<Node> end)
  2169. : Node(move(position))
  2170. , m_start(move(start))
  2171. , m_end(move(end))
  2172. {
  2173. if (m_start->is_syntax_error())
  2174. set_is_syntax_error(m_start->syntax_error_node());
  2175. else if (m_end->is_syntax_error())
  2176. set_is_syntax_error(m_end->syntax_error_node());
  2177. }
  2178. Range::~Range()
  2179. {
  2180. }
  2181. void ReadRedirection::dump(int level) const
  2182. {
  2183. Node::dump(level);
  2184. m_path->dump(level + 1);
  2185. print_indented(String::formatted("To {}", m_fd), level + 1);
  2186. }
  2187. RefPtr<Value> ReadRedirection::run(RefPtr<Shell> shell)
  2188. {
  2189. Command command;
  2190. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2191. if (shell && shell->has_any_error())
  2192. return make_ref_counted<ListValue>({});
  2193. StringBuilder builder;
  2194. builder.join(" ", path_segments);
  2195. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Read));
  2196. return make_ref_counted<CommandValue>(move(command));
  2197. }
  2198. ReadRedirection::ReadRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2199. : PathRedirectionNode(move(position), fd, move(path))
  2200. {
  2201. }
  2202. ReadRedirection::~ReadRedirection()
  2203. {
  2204. }
  2205. void ReadWriteRedirection::dump(int level) const
  2206. {
  2207. Node::dump(level);
  2208. m_path->dump(level + 1);
  2209. print_indented(String::formatted("To/From {}", m_fd), level + 1);
  2210. }
  2211. RefPtr<Value> ReadWriteRedirection::run(RefPtr<Shell> shell)
  2212. {
  2213. Command command;
  2214. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2215. if (shell && shell->has_any_error())
  2216. return make_ref_counted<ListValue>({});
  2217. StringBuilder builder;
  2218. builder.join(" ", path_segments);
  2219. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::ReadWrite));
  2220. return make_ref_counted<CommandValue>(move(command));
  2221. }
  2222. ReadWriteRedirection::ReadWriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2223. : PathRedirectionNode(move(position), fd, move(path))
  2224. {
  2225. }
  2226. ReadWriteRedirection::~ReadWriteRedirection()
  2227. {
  2228. }
  2229. void Sequence::dump(int level) const
  2230. {
  2231. Node::dump(level);
  2232. for (auto& entry : m_entries)
  2233. entry.dump(level + 1);
  2234. }
  2235. RefPtr<Value> Sequence::run(RefPtr<Shell> shell)
  2236. {
  2237. Vector<Command> all_commands;
  2238. Command* last_command_in_sequence = nullptr;
  2239. for (auto& entry : m_entries) {
  2240. if (shell && shell->has_any_error())
  2241. break;
  2242. if (!last_command_in_sequence) {
  2243. auto commands = entry.to_lazy_evaluated_commands(shell);
  2244. all_commands.extend(move(commands));
  2245. last_command_in_sequence = &all_commands.last();
  2246. continue;
  2247. }
  2248. if (last_command_in_sequence->should_wait) {
  2249. last_command_in_sequence->next_chain.append(NodeWithAction { entry, NodeWithAction::Sequence });
  2250. } else {
  2251. all_commands.extend(entry.to_lazy_evaluated_commands(shell));
  2252. last_command_in_sequence = &all_commands.last();
  2253. }
  2254. }
  2255. return make_ref_counted<CommandSequenceValue>(move(all_commands));
  2256. }
  2257. void Sequence::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2258. {
  2259. for (auto& entry : m_entries)
  2260. entry.highlight_in_editor(editor, shell, metadata);
  2261. }
  2262. HitTestResult Sequence::hit_test_position(size_t offset) const
  2263. {
  2264. for (auto& entry : m_entries) {
  2265. auto result = entry.hit_test_position(offset);
  2266. if (result.matching_node) {
  2267. if (!result.closest_command_node)
  2268. result.closest_command_node = entry;
  2269. return result;
  2270. }
  2271. }
  2272. return {};
  2273. }
  2274. RefPtr<Node> Sequence::leftmost_trivial_literal() const
  2275. {
  2276. for (auto& entry : m_entries) {
  2277. if (auto node = entry.leftmost_trivial_literal())
  2278. return node;
  2279. }
  2280. return nullptr;
  2281. }
  2282. Sequence::Sequence(Position position, NonnullRefPtrVector<Node> entries, Vector<Position> separator_positions)
  2283. : Node(move(position))
  2284. , m_entries(move(entries))
  2285. , m_separator_positions(separator_positions)
  2286. {
  2287. for (auto& entry : m_entries) {
  2288. if (entry.is_syntax_error()) {
  2289. set_is_syntax_error(entry.syntax_error_node());
  2290. break;
  2291. }
  2292. }
  2293. }
  2294. Sequence::~Sequence()
  2295. {
  2296. }
  2297. void Subshell::dump(int level) const
  2298. {
  2299. Node::dump(level);
  2300. if (m_block)
  2301. m_block->dump(level + 1);
  2302. }
  2303. RefPtr<Value> Subshell::run(RefPtr<Shell> shell)
  2304. {
  2305. if (!m_block)
  2306. return make_ref_counted<ListValue>({});
  2307. return make_ref_counted<AST::CommandSequenceValue>(m_block->to_lazy_evaluated_commands(shell));
  2308. }
  2309. void Subshell::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2310. {
  2311. metadata.is_first_in_list = true;
  2312. if (m_block)
  2313. m_block->highlight_in_editor(editor, shell, metadata);
  2314. }
  2315. HitTestResult Subshell::hit_test_position(size_t offset) const
  2316. {
  2317. if (m_block)
  2318. return m_block->hit_test_position(offset);
  2319. return {};
  2320. }
  2321. Subshell::Subshell(Position position, RefPtr<Node> block)
  2322. : Node(move(position))
  2323. , m_block(block)
  2324. {
  2325. if (m_block && m_block->is_syntax_error())
  2326. set_is_syntax_error(m_block->syntax_error_node());
  2327. }
  2328. Subshell::~Subshell()
  2329. {
  2330. }
  2331. void Slice::dump(int level) const
  2332. {
  2333. Node::dump(level);
  2334. m_selector->dump(level + 1);
  2335. }
  2336. RefPtr<Value> Slice::run(RefPtr<Shell> shell)
  2337. {
  2338. return m_selector->run(shell);
  2339. }
  2340. void Slice::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2341. {
  2342. m_selector->highlight_in_editor(editor, shell, metadata);
  2343. }
  2344. HitTestResult Slice::hit_test_position(size_t offset) const
  2345. {
  2346. return m_selector->hit_test_position(offset);
  2347. }
  2348. Vector<Line::CompletionSuggestion> Slice::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
  2349. {
  2350. // TODO: Maybe intercept this, and suggest values in range?
  2351. return m_selector->complete_for_editor(shell, offset, hit_test_result);
  2352. }
  2353. Slice::Slice(Position position, NonnullRefPtr<AST::Node> selector)
  2354. : Node(move(position))
  2355. , m_selector(move(selector))
  2356. {
  2357. if (m_selector->is_syntax_error())
  2358. set_is_syntax_error(m_selector->syntax_error_node());
  2359. }
  2360. Slice::~Slice()
  2361. {
  2362. }
  2363. void SimpleVariable::dump(int level) const
  2364. {
  2365. Node::dump(level);
  2366. print_indented("(Name)", level + 1);
  2367. print_indented(m_name, level + 2);
  2368. print_indented("(Slice)", level + 1);
  2369. if (m_slice)
  2370. m_slice->dump(level + 2);
  2371. else
  2372. print_indented("(None)", level + 2);
  2373. }
  2374. RefPtr<Value> SimpleVariable::run(RefPtr<Shell>)
  2375. {
  2376. NonnullRefPtr<Value> value = make_ref_counted<SimpleVariableValue>(m_name);
  2377. if (m_slice)
  2378. value = value->with_slices(*m_slice);
  2379. return value;
  2380. }
  2381. void SimpleVariable::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2382. {
  2383. Line::Style style { Line::Style::Foreground(214, 112, 214) };
  2384. if (metadata.is_first_in_list)
  2385. style.unify_with({ Line::Style::Bold });
  2386. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  2387. if (m_slice)
  2388. m_slice->highlight_in_editor(editor, shell, metadata);
  2389. }
  2390. HitTestResult SimpleVariable::hit_test_position(size_t offset) const
  2391. {
  2392. if (!position().contains(offset))
  2393. return {};
  2394. if (m_slice && m_slice->position().contains(offset))
  2395. return m_slice->hit_test_position(offset);
  2396. return { this, this, nullptr };
  2397. }
  2398. Vector<Line::CompletionSuggestion> SimpleVariable::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
  2399. {
  2400. auto matching_node = hit_test_result.matching_node;
  2401. if (!matching_node)
  2402. return {};
  2403. if (matching_node != this)
  2404. return {};
  2405. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  2406. if (corrected_offset > m_name.length() + 1)
  2407. return {};
  2408. return shell.complete_variable(m_name, corrected_offset);
  2409. }
  2410. SimpleVariable::SimpleVariable(Position position, String name)
  2411. : VariableNode(move(position))
  2412. , m_name(move(name))
  2413. {
  2414. }
  2415. SimpleVariable::~SimpleVariable()
  2416. {
  2417. }
  2418. void SpecialVariable::dump(int level) const
  2419. {
  2420. Node::dump(level);
  2421. print_indented("(Name)", level + 1);
  2422. print_indented(String { &m_name, 1 }, level + 1);
  2423. print_indented("(Slice)", level + 1);
  2424. if (m_slice)
  2425. m_slice->dump(level + 2);
  2426. else
  2427. print_indented("(None)", level + 2);
  2428. }
  2429. RefPtr<Value> SpecialVariable::run(RefPtr<Shell>)
  2430. {
  2431. NonnullRefPtr<Value> value = make_ref_counted<SpecialVariableValue>(m_name);
  2432. if (m_slice)
  2433. value = value->with_slices(*m_slice);
  2434. return value;
  2435. }
  2436. void SpecialVariable::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2437. {
  2438. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(214, 112, 214) });
  2439. if (m_slice)
  2440. m_slice->highlight_in_editor(editor, shell, metadata);
  2441. }
  2442. Vector<Line::CompletionSuggestion> SpecialVariable::complete_for_editor(Shell&, size_t, HitTestResult const&)
  2443. {
  2444. return {};
  2445. }
  2446. HitTestResult SpecialVariable::hit_test_position(size_t offset) const
  2447. {
  2448. if (m_slice && m_slice->position().contains(offset))
  2449. return m_slice->hit_test_position(offset);
  2450. return { this, this, nullptr };
  2451. }
  2452. SpecialVariable::SpecialVariable(Position position, char name)
  2453. : VariableNode(move(position))
  2454. , m_name(name)
  2455. {
  2456. }
  2457. SpecialVariable::~SpecialVariable()
  2458. {
  2459. }
  2460. void Juxtaposition::dump(int level) const
  2461. {
  2462. Node::dump(level);
  2463. m_left->dump(level + 1);
  2464. m_right->dump(level + 1);
  2465. }
  2466. RefPtr<Value> Juxtaposition::run(RefPtr<Shell> shell)
  2467. {
  2468. auto left_value = m_left->run(shell)->resolve_without_cast(shell);
  2469. if (shell && shell->has_any_error())
  2470. return make_ref_counted<ListValue>({});
  2471. auto right_value = m_right->run(shell)->resolve_without_cast(shell);
  2472. if (shell && shell->has_any_error())
  2473. return make_ref_counted<ListValue>({});
  2474. auto left = left_value->resolve_as_list(shell);
  2475. auto right = right_value->resolve_as_list(shell);
  2476. if (left_value->is_string() && right_value->is_string()) {
  2477. VERIFY(left.size() == 1);
  2478. VERIFY(right.size() == 1);
  2479. StringBuilder builder;
  2480. builder.append(left[0]);
  2481. builder.append(right[0]);
  2482. return make_ref_counted<StringValue>(builder.to_string());
  2483. }
  2484. // Otherwise, treat them as lists and create a list product.
  2485. if (left.is_empty() || right.is_empty())
  2486. return make_ref_counted<ListValue>({});
  2487. Vector<String> result;
  2488. result.ensure_capacity(left.size() * right.size());
  2489. StringBuilder builder;
  2490. for (auto& left_element : left) {
  2491. for (auto& right_element : right) {
  2492. builder.append(left_element);
  2493. builder.append(right_element);
  2494. result.append(builder.to_string());
  2495. builder.clear();
  2496. }
  2497. }
  2498. return make_ref_counted<ListValue>(move(result));
  2499. }
  2500. void Juxtaposition::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2501. {
  2502. m_left->highlight_in_editor(editor, shell, metadata);
  2503. // '~/foo/bar' is special, we have to actually resolve the tilde
  2504. // since that resolution is a pure operation, we can just go ahead
  2505. // and do it to get the value :)
  2506. if (m_right->is_bareword() && m_left->is_tilde()) {
  2507. auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
  2508. auto bareword_value = m_right->run(shell)->resolve_as_list(shell)[0];
  2509. StringBuilder path_builder;
  2510. path_builder.append(tilde_value);
  2511. path_builder.append("/");
  2512. path_builder.append(bareword_value);
  2513. auto path = path_builder.to_string();
  2514. if (Core::File::exists(path)) {
  2515. auto realpath = shell.resolve_path(path);
  2516. auto url = URL::create_with_file_protocol(realpath);
  2517. url.set_host(shell.hostname);
  2518. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  2519. }
  2520. } else {
  2521. m_right->highlight_in_editor(editor, shell, metadata);
  2522. }
  2523. }
  2524. Vector<Line::CompletionSuggestion> Juxtaposition::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
  2525. {
  2526. auto matching_node = hit_test_result.matching_node;
  2527. if (m_left->would_execute() || m_right->would_execute()) {
  2528. return {};
  2529. }
  2530. // '~/foo/bar' is special, we have to actually resolve the tilde
  2531. // then complete the bareword with that path prefix.
  2532. auto left_values = m_left->run(shell)->resolve_as_list(shell);
  2533. if (left_values.is_empty())
  2534. return m_right->complete_for_editor(shell, offset, hit_test_result);
  2535. auto& left_value = left_values.first();
  2536. auto right_values = m_right->run(shell)->resolve_as_list(shell);
  2537. StringView right_value {};
  2538. auto corrected_offset = offset - matching_node->position().start_offset;
  2539. if (!right_values.is_empty())
  2540. right_value = right_values.first();
  2541. if (m_left->is_tilde() && !right_value.is_empty()) {
  2542. right_value = right_value.substring_view(1);
  2543. corrected_offset--;
  2544. }
  2545. if (corrected_offset > right_value.length())
  2546. return {};
  2547. return shell.complete_path(left_value, right_value, corrected_offset, Shell::ExecutableOnly::No, hit_test_result.closest_command_node.ptr(), hit_test_result.matching_node);
  2548. }
  2549. HitTestResult Juxtaposition::hit_test_position(size_t offset) const
  2550. {
  2551. auto result = m_left->hit_test_position(offset);
  2552. if (!result.closest_node_with_semantic_meaning)
  2553. result.closest_node_with_semantic_meaning = this;
  2554. if (result.matching_node)
  2555. return result;
  2556. result = m_right->hit_test_position(offset);
  2557. if (!result.closest_node_with_semantic_meaning)
  2558. result.closest_node_with_semantic_meaning = this;
  2559. return result;
  2560. }
  2561. Juxtaposition::Juxtaposition(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  2562. : Node(move(position))
  2563. , m_left(move(left))
  2564. , m_right(move(right))
  2565. {
  2566. if (m_left->is_syntax_error())
  2567. set_is_syntax_error(m_left->syntax_error_node());
  2568. else if (m_right->is_syntax_error())
  2569. set_is_syntax_error(m_right->syntax_error_node());
  2570. }
  2571. Juxtaposition::~Juxtaposition()
  2572. {
  2573. }
  2574. void StringLiteral::dump(int level) const
  2575. {
  2576. Node::dump(level);
  2577. print_indented(m_text, level + 1);
  2578. }
  2579. RefPtr<Value> StringLiteral::run(RefPtr<Shell>)
  2580. {
  2581. return make_ref_counted<StringValue>(m_text);
  2582. }
  2583. void StringLiteral::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  2584. {
  2585. if (m_text.is_empty())
  2586. return;
  2587. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  2588. if (metadata.is_first_in_list)
  2589. style.unify_with({ Line::Style::Bold });
  2590. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  2591. }
  2592. StringLiteral::StringLiteral(Position position, String text, EnclosureType enclosure_type)
  2593. : Node(move(position))
  2594. , m_text(move(text))
  2595. , m_enclosure_type(enclosure_type)
  2596. {
  2597. }
  2598. StringLiteral::~StringLiteral()
  2599. {
  2600. }
  2601. void StringPartCompose::dump(int level) const
  2602. {
  2603. Node::dump(level);
  2604. m_left->dump(level + 1);
  2605. m_right->dump(level + 1);
  2606. }
  2607. RefPtr<Value> StringPartCompose::run(RefPtr<Shell> shell)
  2608. {
  2609. auto left = m_left->run(shell)->resolve_as_list(shell);
  2610. if (shell && shell->has_any_error())
  2611. return make_ref_counted<ListValue>({});
  2612. auto right = m_right->run(shell)->resolve_as_list(shell);
  2613. if (shell && shell->has_any_error())
  2614. return make_ref_counted<ListValue>({});
  2615. StringBuilder builder;
  2616. builder.join(" ", left);
  2617. builder.join(" ", right);
  2618. return make_ref_counted<StringValue>(builder.to_string());
  2619. }
  2620. void StringPartCompose::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2621. {
  2622. m_left->highlight_in_editor(editor, shell, metadata);
  2623. m_right->highlight_in_editor(editor, shell, metadata);
  2624. }
  2625. HitTestResult StringPartCompose::hit_test_position(size_t offset) const
  2626. {
  2627. auto result = m_left->hit_test_position(offset);
  2628. if (result.matching_node)
  2629. return result;
  2630. return m_right->hit_test_position(offset);
  2631. }
  2632. StringPartCompose::StringPartCompose(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  2633. : Node(move(position))
  2634. , m_left(move(left))
  2635. , m_right(move(right))
  2636. {
  2637. if (m_left->is_syntax_error())
  2638. set_is_syntax_error(m_left->syntax_error_node());
  2639. else if (m_right->is_syntax_error())
  2640. set_is_syntax_error(m_right->syntax_error_node());
  2641. }
  2642. StringPartCompose::~StringPartCompose()
  2643. {
  2644. }
  2645. void SyntaxError::dump(int level) const
  2646. {
  2647. Node::dump(level);
  2648. print_indented("(Error text)", level + 1);
  2649. print_indented(m_syntax_error_text, level + 2);
  2650. print_indented("(Can be recovered from)", level + 1);
  2651. print_indented(String::formatted("{}", m_is_continuable), level + 2);
  2652. }
  2653. RefPtr<Value> SyntaxError::run(RefPtr<Shell> shell)
  2654. {
  2655. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, m_syntax_error_text, position());
  2656. return make_ref_counted<StringValue>("");
  2657. }
  2658. void SyntaxError::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  2659. {
  2660. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Bold });
  2661. }
  2662. SyntaxError::SyntaxError(Position position, String error, bool is_continuable)
  2663. : Node(move(position))
  2664. , m_syntax_error_text(move(error))
  2665. , m_is_continuable(is_continuable)
  2666. {
  2667. }
  2668. SyntaxError const& SyntaxError::syntax_error_node() const
  2669. {
  2670. return *this;
  2671. }
  2672. SyntaxError::~SyntaxError()
  2673. {
  2674. }
  2675. void SyntheticNode::dump(int level) const
  2676. {
  2677. Node::dump(level);
  2678. }
  2679. RefPtr<Value> SyntheticNode::run(RefPtr<Shell>)
  2680. {
  2681. return m_value;
  2682. }
  2683. void SyntheticNode::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
  2684. {
  2685. }
  2686. SyntheticNode::SyntheticNode(Position position, NonnullRefPtr<Value> value)
  2687. : Node(move(position))
  2688. , m_value(move(value))
  2689. {
  2690. }
  2691. void Tilde::dump(int level) const
  2692. {
  2693. Node::dump(level);
  2694. print_indented(m_username, level + 1);
  2695. }
  2696. RefPtr<Value> Tilde::run(RefPtr<Shell>)
  2697. {
  2698. return make_ref_counted<TildeValue>(m_username);
  2699. }
  2700. void Tilde::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
  2701. {
  2702. }
  2703. HitTestResult Tilde::hit_test_position(size_t offset) const
  2704. {
  2705. if (!position().contains(offset))
  2706. return {};
  2707. return { this, this, nullptr };
  2708. }
  2709. Vector<Line::CompletionSuggestion> Tilde::complete_for_editor(Shell& shell, size_t offset, HitTestResult const& hit_test_result)
  2710. {
  2711. auto matching_node = hit_test_result.matching_node;
  2712. if (!matching_node)
  2713. return {};
  2714. if (matching_node != this)
  2715. return {};
  2716. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  2717. if (corrected_offset > m_username.length() + 1)
  2718. return {};
  2719. return shell.complete_user(m_username, corrected_offset);
  2720. }
  2721. String Tilde::text() const
  2722. {
  2723. StringBuilder builder;
  2724. builder.append('~');
  2725. builder.append(m_username);
  2726. return builder.to_string();
  2727. }
  2728. Tilde::Tilde(Position position, String username)
  2729. : Node(move(position))
  2730. , m_username(move(username))
  2731. {
  2732. }
  2733. Tilde::~Tilde()
  2734. {
  2735. }
  2736. void WriteAppendRedirection::dump(int level) const
  2737. {
  2738. Node::dump(level);
  2739. m_path->dump(level + 1);
  2740. print_indented(String::formatted("From {}", m_fd), level + 1);
  2741. }
  2742. RefPtr<Value> WriteAppendRedirection::run(RefPtr<Shell> shell)
  2743. {
  2744. Command command;
  2745. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2746. if (shell && shell->has_any_error())
  2747. return make_ref_counted<ListValue>({});
  2748. StringBuilder builder;
  2749. builder.join(" ", path_segments);
  2750. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::WriteAppend));
  2751. return make_ref_counted<CommandValue>(move(command));
  2752. }
  2753. WriteAppendRedirection::WriteAppendRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2754. : PathRedirectionNode(move(position), fd, move(path))
  2755. {
  2756. }
  2757. WriteAppendRedirection::~WriteAppendRedirection()
  2758. {
  2759. }
  2760. void WriteRedirection::dump(int level) const
  2761. {
  2762. Node::dump(level);
  2763. m_path->dump(level + 1);
  2764. print_indented(String::formatted("From {}", m_fd), level + 1);
  2765. }
  2766. RefPtr<Value> WriteRedirection::run(RefPtr<Shell> shell)
  2767. {
  2768. Command command;
  2769. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2770. if (shell && shell->has_any_error())
  2771. return make_ref_counted<ListValue>({});
  2772. StringBuilder builder;
  2773. builder.join(" ", path_segments);
  2774. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Write));
  2775. return make_ref_counted<CommandValue>(move(command));
  2776. }
  2777. WriteRedirection::WriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2778. : PathRedirectionNode(move(position), fd, move(path))
  2779. {
  2780. }
  2781. WriteRedirection::~WriteRedirection()
  2782. {
  2783. }
  2784. void VariableDeclarations::dump(int level) const
  2785. {
  2786. Node::dump(level);
  2787. for (auto& var : m_variables) {
  2788. print_indented("Set", level + 1);
  2789. var.name->dump(level + 2);
  2790. var.value->dump(level + 2);
  2791. }
  2792. }
  2793. RefPtr<Value> VariableDeclarations::run(RefPtr<Shell> shell)
  2794. {
  2795. for (auto& var : m_variables) {
  2796. auto name_value = var.name->run(shell)->resolve_as_list(shell);
  2797. if (shell && shell->has_any_error())
  2798. break;
  2799. VERIFY(name_value.size() == 1);
  2800. auto name = name_value[0];
  2801. auto value = var.value->run(shell);
  2802. if (shell && shell->has_any_error())
  2803. break;
  2804. shell->set_local_variable(name, value.release_nonnull());
  2805. }
  2806. return make_ref_counted<ListValue>({});
  2807. }
  2808. void VariableDeclarations::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2809. {
  2810. metadata.is_first_in_list = false;
  2811. for (auto& var : m_variables) {
  2812. var.name->highlight_in_editor(editor, shell, metadata);
  2813. // Highlight the '='.
  2814. editor.stylize({ var.name->position().end_offset - 1, var.name->position().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
  2815. var.value->highlight_in_editor(editor, shell, metadata);
  2816. }
  2817. }
  2818. HitTestResult VariableDeclarations::hit_test_position(size_t offset) const
  2819. {
  2820. for (auto decl : m_variables) {
  2821. auto result = decl.value->hit_test_position(offset);
  2822. if (result.matching_node)
  2823. return result;
  2824. }
  2825. return { nullptr, nullptr, nullptr };
  2826. }
  2827. VariableDeclarations::VariableDeclarations(Position position, Vector<Variable> variables)
  2828. : Node(move(position))
  2829. , m_variables(move(variables))
  2830. {
  2831. for (auto& decl : m_variables) {
  2832. if (decl.name->is_syntax_error()) {
  2833. set_is_syntax_error(decl.name->syntax_error_node());
  2834. break;
  2835. }
  2836. if (decl.value->is_syntax_error()) {
  2837. set_is_syntax_error(decl.value->syntax_error_node());
  2838. break;
  2839. }
  2840. }
  2841. }
  2842. VariableDeclarations::~VariableDeclarations()
  2843. {
  2844. }
  2845. Value::~Value()
  2846. {
  2847. }
  2848. String Value::resolve_as_string(RefPtr<Shell> shell)
  2849. {
  2850. if (shell)
  2851. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Conversion to string not allowed");
  2852. return {};
  2853. }
  2854. Vector<AST::Command> Value::resolve_as_commands(RefPtr<Shell> shell)
  2855. {
  2856. Command command;
  2857. command.argv = resolve_as_list(shell);
  2858. return { command };
  2859. }
  2860. ListValue::ListValue(Vector<String> values)
  2861. {
  2862. if (values.is_empty())
  2863. return;
  2864. m_contained_values.ensure_capacity(values.size());
  2865. for (auto& str : values)
  2866. m_contained_values.append(adopt_ref(*new StringValue(move(str))));
  2867. }
  2868. NonnullRefPtr<Value> Value::with_slices(NonnullRefPtr<Slice> slice) const&
  2869. {
  2870. auto value = clone();
  2871. value->m_slices.append(move(slice));
  2872. return value;
  2873. }
  2874. NonnullRefPtr<Value> Value::with_slices(NonnullRefPtrVector<Slice> slices) const&
  2875. {
  2876. auto value = clone();
  2877. value->m_slices.extend(move(slices));
  2878. return value;
  2879. }
  2880. ListValue::~ListValue()
  2881. {
  2882. }
  2883. Vector<String> ListValue::resolve_as_list(RefPtr<Shell> shell)
  2884. {
  2885. Vector<String> values;
  2886. for (auto& value : m_contained_values)
  2887. values.extend(value.resolve_as_list(shell));
  2888. return resolve_slices(shell, move(values), m_slices);
  2889. }
  2890. NonnullRefPtr<Value> ListValue::resolve_without_cast(RefPtr<Shell> shell)
  2891. {
  2892. NonnullRefPtrVector<Value> values;
  2893. for (auto& value : m_contained_values)
  2894. values.append(value.resolve_without_cast(shell));
  2895. NonnullRefPtr<Value> value = make_ref_counted<ListValue>(move(values));
  2896. if (!m_slices.is_empty())
  2897. value = value->with_slices(m_slices);
  2898. return value;
  2899. }
  2900. CommandValue::~CommandValue()
  2901. {
  2902. }
  2903. CommandSequenceValue::~CommandSequenceValue()
  2904. {
  2905. }
  2906. Vector<String> CommandSequenceValue::resolve_as_list(RefPtr<Shell> shell)
  2907. {
  2908. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Unexpected cast of a command sequence to a list");
  2909. return {};
  2910. }
  2911. Vector<Command> CommandSequenceValue::resolve_as_commands(RefPtr<Shell>)
  2912. {
  2913. return m_contained_values;
  2914. }
  2915. Vector<String> CommandValue::resolve_as_list(RefPtr<Shell>)
  2916. {
  2917. return m_command.argv;
  2918. }
  2919. Vector<Command> CommandValue::resolve_as_commands(RefPtr<Shell>)
  2920. {
  2921. return { m_command };
  2922. }
  2923. JobValue::~JobValue()
  2924. {
  2925. }
  2926. StringValue::~StringValue()
  2927. {
  2928. }
  2929. String StringValue::resolve_as_string(RefPtr<Shell> shell)
  2930. {
  2931. if (m_split.is_null())
  2932. return m_string;
  2933. return Value::resolve_as_string(shell);
  2934. }
  2935. Vector<String> StringValue::resolve_as_list(RefPtr<Shell> shell)
  2936. {
  2937. if (is_list()) {
  2938. auto parts = StringView(m_string).split_view(m_split, m_keep_empty);
  2939. Vector<String> result;
  2940. result.ensure_capacity(parts.size());
  2941. for (auto& part : parts)
  2942. result.append(part);
  2943. return resolve_slices(shell, move(result), m_slices);
  2944. }
  2945. return { resolve_slices(shell, String { m_string }, m_slices) };
  2946. }
  2947. NonnullRefPtr<Value> StringValue::resolve_without_cast(RefPtr<Shell> shell)
  2948. {
  2949. if (is_list())
  2950. return make_ref_counted<AST::ListValue>(resolve_as_list(shell)); // No need to reapply the slices.
  2951. return *this;
  2952. }
  2953. GlobValue::~GlobValue()
  2954. {
  2955. }
  2956. Vector<String> GlobValue::resolve_as_list(RefPtr<Shell> shell)
  2957. {
  2958. if (!shell)
  2959. return { resolve_slices(shell, String { m_glob }, m_slices) };
  2960. auto results = shell->expand_globs(m_glob, shell->cwd);
  2961. if (results.is_empty())
  2962. shell->raise_error(Shell::ShellError::InvalidGlobError, "Glob did not match anything!", m_generation_position);
  2963. return resolve_slices(shell, move(results), m_slices);
  2964. }
  2965. SimpleVariableValue::~SimpleVariableValue()
  2966. {
  2967. }
  2968. String SimpleVariableValue::resolve_as_string(RefPtr<Shell> shell)
  2969. {
  2970. if (!shell)
  2971. return resolve_slices(shell, String {}, m_slices);
  2972. if (auto value = resolve_without_cast(shell); value != this)
  2973. return value->resolve_as_string(shell);
  2974. char* env_value = getenv(m_name.characters());
  2975. return resolve_slices(shell, env_value, m_slices);
  2976. }
  2977. Vector<String> SimpleVariableValue::resolve_as_list(RefPtr<Shell> shell)
  2978. {
  2979. if (!shell)
  2980. return resolve_slices(shell, Vector<String> {}, m_slices);
  2981. if (auto value = resolve_without_cast(shell); value != this)
  2982. return value->resolve_as_list(shell);
  2983. char* env_value = getenv(m_name.characters());
  2984. if (env_value == nullptr)
  2985. return { resolve_slices(shell, "", m_slices) };
  2986. return { resolve_slices(shell, String { env_value }, m_slices) };
  2987. }
  2988. NonnullRefPtr<Value> SimpleVariableValue::resolve_without_cast(RefPtr<Shell> shell)
  2989. {
  2990. VERIFY(shell);
  2991. if (auto value = shell->lookup_local_variable(m_name)) {
  2992. auto result = value.release_nonnull();
  2993. // If a slice is applied, add it.
  2994. if (!m_slices.is_empty())
  2995. result = result->with_slices(m_slices);
  2996. return result;
  2997. }
  2998. return *this;
  2999. }
  3000. SpecialVariableValue::~SpecialVariableValue()
  3001. {
  3002. }
  3003. String SpecialVariableValue::resolve_as_string(RefPtr<Shell> shell)
  3004. {
  3005. if (!shell)
  3006. return {};
  3007. auto result = resolve_as_list(shell);
  3008. if (result.size() == 1)
  3009. return result[0];
  3010. if (result.is_empty())
  3011. return {};
  3012. return Value::resolve_as_string(shell);
  3013. }
  3014. Vector<String> SpecialVariableValue::resolve_as_list(RefPtr<Shell> shell)
  3015. {
  3016. if (!shell)
  3017. return {};
  3018. switch (m_name) {
  3019. case '?':
  3020. return { resolve_slices(shell, String::number(shell->last_return_code.value_or(0)), m_slices) };
  3021. case '$':
  3022. return { resolve_slices(shell, String::number(getpid()), m_slices) };
  3023. case '*':
  3024. if (auto argv = shell->lookup_local_variable("ARGV"))
  3025. return resolve_slices(shell, argv->resolve_as_list(shell), m_slices);
  3026. return resolve_slices(shell, Vector<String> {}, m_slices);
  3027. case '#':
  3028. if (auto argv = shell->lookup_local_variable("ARGV")) {
  3029. if (argv->is_list()) {
  3030. auto list_argv = static_cast<AST::ListValue*>(argv.ptr());
  3031. return { resolve_slices(shell, String::number(list_argv->values().size()), m_slices) };
  3032. }
  3033. return { resolve_slices(shell, "1", m_slices) };
  3034. }
  3035. return { resolve_slices(shell, "0", m_slices) };
  3036. default:
  3037. return { resolve_slices(shell, "", m_slices) };
  3038. }
  3039. }
  3040. TildeValue::~TildeValue()
  3041. {
  3042. }
  3043. String TildeValue::resolve_as_string(RefPtr<Shell> shell)
  3044. {
  3045. return resolve_as_list(shell).first();
  3046. }
  3047. Vector<String> TildeValue::resolve_as_list(RefPtr<Shell> shell)
  3048. {
  3049. StringBuilder builder;
  3050. builder.append("~");
  3051. builder.append(m_username);
  3052. if (!shell)
  3053. return { resolve_slices(shell, builder.to_string(), m_slices) };
  3054. return { resolve_slices(shell, shell->expand_tilde(builder.to_string()), m_slices) };
  3055. }
  3056. ErrorOr<NonnullRefPtr<Rewiring>> CloseRedirection::apply() const
  3057. {
  3058. return adopt_nonnull_ref_or_enomem(new (nothrow) Rewiring(fd, fd, Rewiring::Close::ImmediatelyCloseNew));
  3059. }
  3060. CloseRedirection::~CloseRedirection()
  3061. {
  3062. }
  3063. ErrorOr<NonnullRefPtr<Rewiring>> PathRedirection::apply() const
  3064. {
  3065. auto check_fd_and_return = [my_fd = this->fd](int fd, String const& path) -> ErrorOr<NonnullRefPtr<Rewiring>> {
  3066. if (fd < 0) {
  3067. auto error = Error::from_errno(errno);
  3068. dbgln("open() failed for '{}' with {}", path, error);
  3069. return error;
  3070. }
  3071. return adopt_nonnull_ref_or_enomem(new (nothrow) Rewiring(fd, my_fd, Rewiring::Close::Old));
  3072. };
  3073. switch (direction) {
  3074. case AST::PathRedirection::WriteAppend:
  3075. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666), path);
  3076. case AST::PathRedirection::Write:
  3077. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666), path);
  3078. case AST::PathRedirection::Read:
  3079. return check_fd_and_return(open(path.characters(), O_RDONLY), path);
  3080. case AST::PathRedirection::ReadWrite:
  3081. return check_fd_and_return(open(path.characters(), O_RDWR | O_CREAT, 0666), path);
  3082. }
  3083. VERIFY_NOT_REACHED();
  3084. }
  3085. PathRedirection::~PathRedirection()
  3086. {
  3087. }
  3088. FdRedirection::~FdRedirection()
  3089. {
  3090. }
  3091. Redirection::~Redirection()
  3092. {
  3093. }
  3094. }