AST.cpp 95 KB

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