AST.cpp 109 KB

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