AST.cpp 95 KB

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