AST.cpp 123 KB

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