AST.cpp 119 KB

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