AST.cpp 99 KB

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