AST.cpp 115 KB

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