AST.cpp 130 KB

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