AST.cpp 129 KB

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