AST.cpp 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160
  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. m_true_branch = create<AST::Execute>(true_branch->position(), true_branch);
  1417. }
  1418. if (m_false_branch) {
  1419. auto false_branch = m_false_branch.release_nonnull();
  1420. m_false_branch = create<AST::Execute>(false_branch->position(), false_branch);
  1421. }
  1422. }
  1423. IfCond::~IfCond()
  1424. {
  1425. }
  1426. void Join::dump(int level) const
  1427. {
  1428. Node::dump(level);
  1429. m_left->dump(level + 1);
  1430. m_right->dump(level + 1);
  1431. }
  1432. RefPtr<Value> Join::run(RefPtr<Shell> shell)
  1433. {
  1434. auto left = m_left->to_lazy_evaluated_commands(shell);
  1435. auto right = m_right->to_lazy_evaluated_commands(shell);
  1436. return create<CommandSequenceValue>(join_commands(move(left), move(right)));
  1437. }
  1438. void Join::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1439. {
  1440. m_left->highlight_in_editor(editor, shell, metadata);
  1441. if (m_left->is_list() || m_left->is_command())
  1442. metadata.is_first_in_list = false;
  1443. m_right->highlight_in_editor(editor, shell, metadata);
  1444. }
  1445. HitTestResult Join::hit_test_position(size_t offset)
  1446. {
  1447. if (!position().contains(offset))
  1448. return {};
  1449. auto result = m_left->hit_test_position(offset);
  1450. if (result.matching_node)
  1451. return result;
  1452. return m_right->hit_test_position(offset);
  1453. }
  1454. RefPtr<Node> Join::leftmost_trivial_literal() const
  1455. {
  1456. if (auto value = m_left->leftmost_trivial_literal())
  1457. return value;
  1458. return m_right->leftmost_trivial_literal();
  1459. }
  1460. Join::Join(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  1461. : Node(move(position))
  1462. , m_left(move(left))
  1463. , m_right(move(right))
  1464. {
  1465. if (m_left->is_syntax_error())
  1466. set_is_syntax_error(m_left->syntax_error_node());
  1467. else if (m_right->is_syntax_error())
  1468. set_is_syntax_error(m_right->syntax_error_node());
  1469. }
  1470. Join::~Join()
  1471. {
  1472. }
  1473. void MatchExpr::dump(int level) const
  1474. {
  1475. Node::dump(level);
  1476. print_indented(String::formatted("(expression: {})", m_expr_name.characters()), level + 1);
  1477. m_matched_expr->dump(level + 2);
  1478. print_indented(String::formatted("(named: {})", m_expr_name.characters()), level + 1);
  1479. print_indented("(entries)", level + 1);
  1480. for (auto& entry : m_entries) {
  1481. StringBuilder builder;
  1482. builder.append("(match");
  1483. if (entry.match_names.has_value()) {
  1484. builder.append(" to names (");
  1485. bool first = true;
  1486. for (auto& name : entry.match_names.value()) {
  1487. if (!first)
  1488. builder.append(' ');
  1489. first = false;
  1490. builder.append(name);
  1491. }
  1492. builder.append("))");
  1493. } else {
  1494. builder.append(')');
  1495. }
  1496. print_indented(builder.string_view(), level + 2);
  1497. for (auto& node : entry.options)
  1498. node.dump(level + 3);
  1499. print_indented("(execute)", level + 2);
  1500. if (entry.body)
  1501. entry.body->dump(level + 3);
  1502. else
  1503. print_indented("(nothing)", level + 3);
  1504. }
  1505. }
  1506. RefPtr<Value> MatchExpr::run(RefPtr<Shell> shell)
  1507. {
  1508. auto value = m_matched_expr->run(shell)->resolve_without_cast(shell);
  1509. auto list = value->resolve_as_list(shell);
  1510. auto list_matches = [&](auto&& pattern, auto& spans) {
  1511. if (pattern.size() != list.size())
  1512. return false;
  1513. for (size_t i = 0; i < pattern.size(); ++i) {
  1514. Vector<AK::MaskSpan> mask_spans;
  1515. if (!list[i].matches(pattern[i], mask_spans))
  1516. return false;
  1517. for (auto& span : mask_spans)
  1518. spans.append(list[i].substring(span.start, span.length));
  1519. }
  1520. return true;
  1521. };
  1522. auto resolve_pattern = [&](auto& option) {
  1523. Vector<String> pattern;
  1524. if (option.is_glob()) {
  1525. pattern.append(static_cast<const Glob*>(&option)->text());
  1526. } else if (option.is_bareword()) {
  1527. pattern.append(static_cast<const BarewordLiteral*>(&option)->text());
  1528. } else {
  1529. auto list = option.run(shell);
  1530. option.for_each_entry(shell, [&](auto&& value) {
  1531. pattern.append(value->resolve_as_list(nullptr)); // Note: 'nullptr' incurs special behaviour,
  1532. // asking the node for a 'raw' value.
  1533. return IterationDecision::Continue;
  1534. });
  1535. }
  1536. return pattern;
  1537. };
  1538. auto frame = shell->push_frame(String::formatted("match ({})", this));
  1539. if (!m_expr_name.is_empty())
  1540. shell->set_local_variable(m_expr_name, value, true);
  1541. for (auto& entry : m_entries) {
  1542. for (auto& option : entry.options) {
  1543. Vector<String> spans;
  1544. if (list_matches(resolve_pattern(option), spans)) {
  1545. if (entry.body) {
  1546. if (entry.match_names.has_value()) {
  1547. size_t i = 0;
  1548. for (auto& name : entry.match_names.value()) {
  1549. if (spans.size() > i)
  1550. shell->set_local_variable(name, create<AST::StringValue>(spans[i]), true);
  1551. ++i;
  1552. }
  1553. }
  1554. return entry.body->run(shell);
  1555. } else {
  1556. return create<AST::ListValue>({});
  1557. }
  1558. }
  1559. }
  1560. }
  1561. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Non-exhaustive match rules!", position());
  1562. return create<AST::ListValue>({});
  1563. }
  1564. void MatchExpr::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1565. {
  1566. editor.stylize({ m_position.start_offset, m_position.start_offset + 5 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1567. if (m_as_position.has_value())
  1568. editor.stylize({ m_as_position.value().start_offset, m_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1569. metadata.is_first_in_list = false;
  1570. m_matched_expr->highlight_in_editor(editor, shell, metadata);
  1571. for (auto& entry : m_entries) {
  1572. metadata.is_first_in_list = false;
  1573. for (auto& option : entry.options)
  1574. option.highlight_in_editor(editor, shell, metadata);
  1575. metadata.is_first_in_list = true;
  1576. if (entry.body)
  1577. entry.body->highlight_in_editor(editor, shell, metadata);
  1578. for (auto& position : entry.pipe_positions)
  1579. editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1580. if (entry.match_as_position.has_value())
  1581. editor.stylize({ entry.match_as_position.value().start_offset, entry.match_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1582. }
  1583. }
  1584. HitTestResult MatchExpr::hit_test_position(size_t offset)
  1585. {
  1586. if (!position().contains(offset))
  1587. return {};
  1588. auto result = m_matched_expr->hit_test_position(offset);
  1589. if (result.matching_node)
  1590. return result;
  1591. for (auto& entry : m_entries) {
  1592. if (!entry.body)
  1593. continue;
  1594. auto result = entry.body->hit_test_position(offset);
  1595. if (result.matching_node)
  1596. return result;
  1597. }
  1598. return {};
  1599. }
  1600. MatchExpr::MatchExpr(Position position, NonnullRefPtr<Node> expr, String name, Optional<Position> as_position, Vector<MatchEntry> entries)
  1601. : Node(move(position))
  1602. , m_matched_expr(move(expr))
  1603. , m_expr_name(move(name))
  1604. , m_as_position(move(as_position))
  1605. , m_entries(move(entries))
  1606. {
  1607. if (m_matched_expr->is_syntax_error()) {
  1608. set_is_syntax_error(m_matched_expr->syntax_error_node());
  1609. } else {
  1610. for (auto& entry : m_entries) {
  1611. if (!entry.body)
  1612. continue;
  1613. if (entry.body->is_syntax_error()) {
  1614. set_is_syntax_error(entry.body->syntax_error_node());
  1615. break;
  1616. }
  1617. }
  1618. }
  1619. }
  1620. MatchExpr::~MatchExpr()
  1621. {
  1622. }
  1623. void Or::dump(int level) const
  1624. {
  1625. Node::dump(level);
  1626. m_left->dump(level + 1);
  1627. m_right->dump(level + 1);
  1628. }
  1629. RefPtr<Value> Or::run(RefPtr<Shell> shell)
  1630. {
  1631. auto commands = m_left->to_lazy_evaluated_commands(shell);
  1632. commands.last().next_chain.empend(*m_right, NodeWithAction::Or);
  1633. return create<CommandSequenceValue>(move(commands));
  1634. }
  1635. void Or::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1636. {
  1637. m_left->highlight_in_editor(editor, shell, metadata);
  1638. m_right->highlight_in_editor(editor, shell, metadata);
  1639. }
  1640. HitTestResult Or::hit_test_position(size_t offset)
  1641. {
  1642. if (!position().contains(offset))
  1643. return {};
  1644. auto result = m_left->hit_test_position(offset);
  1645. if (result.matching_node) {
  1646. if (!result.closest_command_node)
  1647. result.closest_command_node = m_right;
  1648. return result;
  1649. }
  1650. result = m_right->hit_test_position(offset);
  1651. if (!result.closest_command_node)
  1652. result.closest_command_node = m_right;
  1653. return result;
  1654. }
  1655. Or::Or(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position or_position)
  1656. : Node(move(position))
  1657. , m_left(move(left))
  1658. , m_right(move(right))
  1659. , m_or_position(or_position)
  1660. {
  1661. if (m_left->is_syntax_error())
  1662. set_is_syntax_error(m_left->syntax_error_node());
  1663. else if (m_right->is_syntax_error())
  1664. set_is_syntax_error(m_right->syntax_error_node());
  1665. }
  1666. Or::~Or()
  1667. {
  1668. }
  1669. void Pipe::dump(int level) const
  1670. {
  1671. Node::dump(level);
  1672. m_left->dump(level + 1);
  1673. m_right->dump(level + 1);
  1674. }
  1675. RefPtr<Value> Pipe::run(RefPtr<Shell> shell)
  1676. {
  1677. auto left = m_left->to_lazy_evaluated_commands(shell);
  1678. auto right = m_right->to_lazy_evaluated_commands(shell);
  1679. auto last_in_left = left.take_last();
  1680. auto first_in_right = right.take_first();
  1681. auto pipe_read_end = FdRedirection::create(-1, STDIN_FILENO, Rewiring::Close::Old);
  1682. auto pipe_write_end = FdRedirection::create(-1, STDOUT_FILENO, pipe_read_end, Rewiring::Close::RefreshOld);
  1683. first_in_right.redirections.append(pipe_read_end);
  1684. last_in_left.redirections.append(pipe_write_end);
  1685. last_in_left.should_wait = false;
  1686. last_in_left.is_pipe_source = true;
  1687. if (first_in_right.pipeline) {
  1688. last_in_left.pipeline = first_in_right.pipeline;
  1689. } else {
  1690. auto pipeline = create<Pipeline>();
  1691. last_in_left.pipeline = pipeline;
  1692. first_in_right.pipeline = pipeline;
  1693. }
  1694. Vector<Command> commands;
  1695. commands.append(left);
  1696. commands.append(last_in_left);
  1697. commands.append(first_in_right);
  1698. commands.append(right);
  1699. return create<CommandSequenceValue>(move(commands));
  1700. }
  1701. void Pipe::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1702. {
  1703. m_left->highlight_in_editor(editor, shell, metadata);
  1704. m_right->highlight_in_editor(editor, shell, metadata);
  1705. }
  1706. HitTestResult Pipe::hit_test_position(size_t offset)
  1707. {
  1708. if (!position().contains(offset))
  1709. return {};
  1710. auto result = m_left->hit_test_position(offset);
  1711. if (result.matching_node) {
  1712. if (!result.closest_command_node)
  1713. result.closest_command_node = m_right;
  1714. return result;
  1715. }
  1716. result = m_right->hit_test_position(offset);
  1717. if (!result.closest_command_node)
  1718. result.closest_command_node = m_right;
  1719. return result;
  1720. }
  1721. Pipe::Pipe(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  1722. : Node(move(position))
  1723. , m_left(move(left))
  1724. , m_right(move(right))
  1725. {
  1726. if (m_left->is_syntax_error())
  1727. set_is_syntax_error(m_left->syntax_error_node());
  1728. else if (m_right->is_syntax_error())
  1729. set_is_syntax_error(m_right->syntax_error_node());
  1730. }
  1731. Pipe::~Pipe()
  1732. {
  1733. }
  1734. PathRedirectionNode::PathRedirectionNode(Position position, int fd, NonnullRefPtr<Node> path)
  1735. : Node(move(position))
  1736. , m_fd(fd)
  1737. , m_path(move(path))
  1738. {
  1739. }
  1740. void PathRedirectionNode::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1741. {
  1742. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  1743. metadata.is_first_in_list = false;
  1744. m_path->highlight_in_editor(editor, shell, metadata);
  1745. if (m_path->is_bareword()) {
  1746. auto path_text = m_path->run(nullptr)->resolve_as_list(nullptr);
  1747. ASSERT(path_text.size() == 1);
  1748. // Apply a URL to the path.
  1749. auto& position = m_path->position();
  1750. auto& path = path_text[0];
  1751. if (!path.starts_with('/'))
  1752. path = String::format("%s/%s", shell.cwd.characters(), path.characters());
  1753. auto url = URL::create_with_file_protocol(path);
  1754. url.set_host(shell.hostname);
  1755. editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  1756. }
  1757. }
  1758. HitTestResult PathRedirectionNode::hit_test_position(size_t offset)
  1759. {
  1760. if (!position().contains(offset))
  1761. return {};
  1762. auto result = m_path->hit_test_position(offset);
  1763. if (!result.closest_node_with_semantic_meaning)
  1764. result.closest_node_with_semantic_meaning = this;
  1765. return result;
  1766. }
  1767. Vector<Line::CompletionSuggestion> PathRedirectionNode::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1768. {
  1769. auto matching_node = hit_test_result.matching_node;
  1770. if (!matching_node || !matching_node->is_bareword())
  1771. return {};
  1772. auto corrected_offset = offset - matching_node->position().start_offset;
  1773. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  1774. if (corrected_offset > node->text().length())
  1775. return {};
  1776. return shell.complete_path("", node->text(), corrected_offset);
  1777. }
  1778. PathRedirectionNode::~PathRedirectionNode()
  1779. {
  1780. }
  1781. void Range::dump(int level) const
  1782. {
  1783. Node::dump(level);
  1784. print_indented("(From)", level + 1);
  1785. m_start->dump(level + 2);
  1786. print_indented("(To)", level + 1);
  1787. m_end->dump(level + 2);
  1788. }
  1789. RefPtr<Value> Range::run(RefPtr<Shell> shell)
  1790. {
  1791. auto interpolate = [position = position()](RefPtr<Value> start, RefPtr<Value> end, RefPtr<Shell> shell) -> NonnullRefPtrVector<Value> {
  1792. NonnullRefPtrVector<Value> values;
  1793. if (start->is_string() && end->is_string()) {
  1794. auto start_str = start->resolve_as_list(shell)[0];
  1795. auto end_str = end->resolve_as_list(shell)[0];
  1796. Utf8View start_view { start_str }, end_view { end_str };
  1797. if (start_view.validate() && end_view.validate()) {
  1798. if (start_view.length() == 1 && end_view.length() == 1) {
  1799. // Interpolate between two code points.
  1800. auto start_code_point = *start_view.begin();
  1801. auto end_code_point = *end_view.begin();
  1802. auto step = start_code_point > end_code_point ? -1 : 1;
  1803. StringBuilder builder;
  1804. for (u32 code_point = start_code_point; code_point != end_code_point; code_point += step) {
  1805. builder.clear();
  1806. builder.append_code_point(code_point);
  1807. values.append(create<StringValue>(builder.to_string()));
  1808. }
  1809. // Append the ending code point too, most shells treat this as inclusive.
  1810. builder.clear();
  1811. builder.append_code_point(end_code_point);
  1812. values.append(create<StringValue>(builder.to_string()));
  1813. } else {
  1814. // Could be two numbers?
  1815. auto start_int = start_str.to_int();
  1816. auto end_int = end_str.to_int();
  1817. if (start_int.has_value() && end_int.has_value()) {
  1818. auto start = start_int.value();
  1819. auto end = end_int.value();
  1820. auto step = start > end ? -1 : 1;
  1821. for (int value = start; value != end; value += step)
  1822. values.append(create<StringValue>(String::number(value)));
  1823. // Append the range end too, most shells treat this as inclusive.
  1824. values.append(create<StringValue>(String::number(end)));
  1825. } else {
  1826. goto yield_start_end;
  1827. }
  1828. }
  1829. } else {
  1830. yield_start_end:;
  1831. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, String::formatted("Cannot interpolate between '{}' and '{}'!", start_str, end_str), position);
  1832. // We can't really interpolate between the two, so just yield both.
  1833. values.append(create<StringValue>(move(start_str)));
  1834. values.append(create<StringValue>(move(end_str)));
  1835. }
  1836. return values;
  1837. }
  1838. warnln("Shell: Cannot apply the requested interpolation");
  1839. return values;
  1840. };
  1841. auto start_value = m_start->run(shell);
  1842. auto end_value = m_end->run(shell);
  1843. if (!start_value || !end_value)
  1844. return create<ListValue>({});
  1845. return create<ListValue>(interpolate(*start_value, *end_value, shell));
  1846. }
  1847. void Range::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1848. {
  1849. m_start->highlight_in_editor(editor, shell, metadata);
  1850. // Highlight the '..'
  1851. editor.stylize({ m_start->position().end_offset, m_end->position().start_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1852. metadata.is_first_in_list = false;
  1853. m_end->highlight_in_editor(editor, shell, metadata);
  1854. }
  1855. HitTestResult Range::hit_test_position(size_t offset)
  1856. {
  1857. if (!position().contains(offset))
  1858. return {};
  1859. auto result = m_start->hit_test_position(offset);
  1860. if (result.matching_node) {
  1861. if (!result.closest_command_node)
  1862. result.closest_command_node = m_start;
  1863. return result;
  1864. }
  1865. result = m_end->hit_test_position(offset);
  1866. if (!result.closest_command_node)
  1867. result.closest_command_node = m_end;
  1868. return result;
  1869. }
  1870. Range::Range(Position position, NonnullRefPtr<Node> start, NonnullRefPtr<Node> end)
  1871. : Node(move(position))
  1872. , m_start(move(start))
  1873. , m_end(move(end))
  1874. {
  1875. if (m_start->is_syntax_error())
  1876. set_is_syntax_error(m_start->syntax_error_node());
  1877. else if (m_end->is_syntax_error())
  1878. set_is_syntax_error(m_end->syntax_error_node());
  1879. }
  1880. Range::~Range()
  1881. {
  1882. }
  1883. void ReadRedirection::dump(int level) const
  1884. {
  1885. Node::dump(level);
  1886. m_path->dump(level + 1);
  1887. print_indented(String::format("To %d", m_fd), level + 1);
  1888. }
  1889. RefPtr<Value> ReadRedirection::run(RefPtr<Shell> shell)
  1890. {
  1891. Command command;
  1892. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1893. StringBuilder builder;
  1894. builder.join(" ", path_segments);
  1895. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Read));
  1896. return create<CommandValue>(move(command));
  1897. }
  1898. ReadRedirection::ReadRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  1899. : PathRedirectionNode(move(position), fd, move(path))
  1900. {
  1901. }
  1902. ReadRedirection::~ReadRedirection()
  1903. {
  1904. }
  1905. void ReadWriteRedirection::dump(int level) const
  1906. {
  1907. Node::dump(level);
  1908. m_path->dump(level + 1);
  1909. print_indented(String::format("To/From %d", m_fd), level + 1);
  1910. }
  1911. RefPtr<Value> ReadWriteRedirection::run(RefPtr<Shell> shell)
  1912. {
  1913. Command command;
  1914. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1915. StringBuilder builder;
  1916. builder.join(" ", path_segments);
  1917. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::ReadWrite));
  1918. return create<CommandValue>(move(command));
  1919. }
  1920. ReadWriteRedirection::ReadWriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  1921. : PathRedirectionNode(move(position), fd, move(path))
  1922. {
  1923. }
  1924. ReadWriteRedirection::~ReadWriteRedirection()
  1925. {
  1926. }
  1927. void Sequence::dump(int level) const
  1928. {
  1929. Node::dump(level);
  1930. m_left->dump(level + 1);
  1931. m_right->dump(level + 1);
  1932. }
  1933. RefPtr<Value> Sequence::run(RefPtr<Shell> shell)
  1934. {
  1935. auto left = m_left->to_lazy_evaluated_commands(shell);
  1936. // This could happen if a comment is next to a command.
  1937. if (left.size() == 1) {
  1938. auto& command = left.first();
  1939. if (command.argv.is_empty() && command.redirections.is_empty() && command.next_chain.is_empty())
  1940. return m_right->run(shell);
  1941. }
  1942. if (left.last().should_wait)
  1943. left.last().next_chain.append(NodeWithAction { *m_right, NodeWithAction::Sequence });
  1944. else
  1945. left.append(m_right->to_lazy_evaluated_commands(shell));
  1946. return create<CommandSequenceValue>(move(left));
  1947. }
  1948. void Sequence::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1949. {
  1950. m_left->highlight_in_editor(editor, shell, metadata);
  1951. m_right->highlight_in_editor(editor, shell, metadata);
  1952. }
  1953. HitTestResult Sequence::hit_test_position(size_t offset)
  1954. {
  1955. if (!position().contains(offset))
  1956. return {};
  1957. auto result = m_left->hit_test_position(offset);
  1958. if (result.matching_node) {
  1959. if (!result.closest_command_node)
  1960. result.closest_command_node = m_right;
  1961. return result;
  1962. }
  1963. result = m_right->hit_test_position(offset);
  1964. if (!result.closest_command_node)
  1965. result.closest_command_node = m_right;
  1966. return result;
  1967. }
  1968. Sequence::Sequence(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position separator_position)
  1969. : Node(move(position))
  1970. , m_left(move(left))
  1971. , m_right(move(right))
  1972. , m_separator_position(separator_position)
  1973. {
  1974. if (m_left->is_syntax_error())
  1975. set_is_syntax_error(m_left->syntax_error_node());
  1976. else if (m_right->is_syntax_error())
  1977. set_is_syntax_error(m_right->syntax_error_node());
  1978. }
  1979. Sequence::~Sequence()
  1980. {
  1981. }
  1982. void Subshell::dump(int level) const
  1983. {
  1984. Node::dump(level);
  1985. if (m_block)
  1986. m_block->dump(level + 1);
  1987. }
  1988. RefPtr<Value> Subshell::run(RefPtr<Shell> shell)
  1989. {
  1990. if (!m_block)
  1991. return create<ListValue>({});
  1992. return create<AST::CommandSequenceValue>(m_block->to_lazy_evaluated_commands(shell));
  1993. }
  1994. void Subshell::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1995. {
  1996. metadata.is_first_in_list = true;
  1997. if (m_block)
  1998. m_block->highlight_in_editor(editor, shell, metadata);
  1999. }
  2000. HitTestResult Subshell::hit_test_position(size_t offset)
  2001. {
  2002. if (!position().contains(offset))
  2003. return {};
  2004. if (m_block)
  2005. return m_block->hit_test_position(offset);
  2006. return {};
  2007. }
  2008. Subshell::Subshell(Position position, RefPtr<Node> block)
  2009. : Node(move(position))
  2010. , m_block(block)
  2011. {
  2012. if (m_block && m_block->is_syntax_error())
  2013. set_is_syntax_error(m_block->syntax_error_node());
  2014. }
  2015. Subshell::~Subshell()
  2016. {
  2017. }
  2018. void SimpleVariable::dump(int level) const
  2019. {
  2020. Node::dump(level);
  2021. print_indented(m_name, level + 1);
  2022. }
  2023. RefPtr<Value> SimpleVariable::run(RefPtr<Shell>)
  2024. {
  2025. return create<SimpleVariableValue>(m_name);
  2026. }
  2027. void SimpleVariable::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  2028. {
  2029. Line::Style style { Line::Style::Foreground(214, 112, 214) };
  2030. if (metadata.is_first_in_list)
  2031. style.unify_with({ Line::Style::Bold });
  2032. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  2033. }
  2034. HitTestResult SimpleVariable::hit_test_position(size_t offset)
  2035. {
  2036. if (!position().contains(offset))
  2037. return {};
  2038. return { this, this, nullptr };
  2039. }
  2040. Vector<Line::CompletionSuggestion> SimpleVariable::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  2041. {
  2042. auto matching_node = hit_test_result.matching_node;
  2043. if (!matching_node)
  2044. return {};
  2045. if (matching_node != this)
  2046. return {};
  2047. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  2048. if (corrected_offset > m_name.length() + 1)
  2049. return {};
  2050. return shell.complete_variable(m_name, corrected_offset);
  2051. }
  2052. SimpleVariable::SimpleVariable(Position position, String name)
  2053. : Node(move(position))
  2054. , m_name(move(name))
  2055. {
  2056. }
  2057. SimpleVariable::~SimpleVariable()
  2058. {
  2059. }
  2060. void SpecialVariable::dump(int level) const
  2061. {
  2062. Node::dump(level);
  2063. print_indented(String { &m_name, 1 }, level + 1);
  2064. }
  2065. RefPtr<Value> SpecialVariable::run(RefPtr<Shell>)
  2066. {
  2067. return create<SpecialVariableValue>(m_name);
  2068. }
  2069. void SpecialVariable::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  2070. {
  2071. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(214, 112, 214) });
  2072. }
  2073. Vector<Line::CompletionSuggestion> SpecialVariable::complete_for_editor(Shell&, size_t, const HitTestResult&)
  2074. {
  2075. return {};
  2076. }
  2077. HitTestResult SpecialVariable::hit_test_position(size_t offset)
  2078. {
  2079. if (!position().contains(offset))
  2080. return {};
  2081. return { this, this, nullptr };
  2082. }
  2083. SpecialVariable::SpecialVariable(Position position, char name)
  2084. : Node(move(position))
  2085. , m_name(name)
  2086. {
  2087. }
  2088. SpecialVariable::~SpecialVariable()
  2089. {
  2090. }
  2091. void Juxtaposition::dump(int level) const
  2092. {
  2093. Node::dump(level);
  2094. m_left->dump(level + 1);
  2095. m_right->dump(level + 1);
  2096. }
  2097. RefPtr<Value> Juxtaposition::run(RefPtr<Shell> shell)
  2098. {
  2099. auto left_value = m_left->run(shell)->resolve_without_cast(shell);
  2100. auto right_value = m_right->run(shell)->resolve_without_cast(shell);
  2101. auto left = left_value->resolve_as_list(shell);
  2102. auto right = right_value->resolve_as_list(shell);
  2103. if (left_value->is_string() && right_value->is_string()) {
  2104. ASSERT(left.size() == 1);
  2105. ASSERT(right.size() == 1);
  2106. StringBuilder builder;
  2107. builder.append(left[0]);
  2108. builder.append(right[0]);
  2109. return create<StringValue>(builder.to_string());
  2110. }
  2111. // Otherwise, treat them as lists and create a list product.
  2112. if (left.is_empty() || right.is_empty())
  2113. return create<ListValue>({});
  2114. Vector<String> result;
  2115. result.ensure_capacity(left.size() * right.size());
  2116. StringBuilder builder;
  2117. for (auto& left_element : left) {
  2118. for (auto& right_element : right) {
  2119. builder.append(left_element);
  2120. builder.append(right_element);
  2121. result.append(builder.to_string());
  2122. builder.clear();
  2123. }
  2124. }
  2125. return create<ListValue>(move(result));
  2126. }
  2127. void Juxtaposition::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2128. {
  2129. m_left->highlight_in_editor(editor, shell, metadata);
  2130. // '~/foo/bar' is special, we have to actually resolve the tilde
  2131. // since that resolution is a pure operation, we can just go ahead
  2132. // and do it to get the value :)
  2133. if (m_right->is_bareword() && m_left->is_tilde()) {
  2134. auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
  2135. auto bareword_value = m_right->run(shell)->resolve_as_list(shell)[0];
  2136. StringBuilder path_builder;
  2137. path_builder.append(tilde_value);
  2138. path_builder.append("/");
  2139. path_builder.append(bareword_value);
  2140. auto path = path_builder.to_string();
  2141. if (Core::File::exists(path)) {
  2142. auto realpath = shell.resolve_path(path);
  2143. auto url = URL::create_with_file_protocol(realpath);
  2144. url.set_host(shell.hostname);
  2145. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  2146. }
  2147. } else {
  2148. m_right->highlight_in_editor(editor, shell, metadata);
  2149. }
  2150. }
  2151. Vector<Line::CompletionSuggestion> Juxtaposition::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  2152. {
  2153. auto matching_node = hit_test_result.matching_node;
  2154. // '~/foo/bar' is special, we have to actually resolve the tilde
  2155. // then complete the bareword with that path prefix.
  2156. if (m_right->is_bareword() && m_left->is_tilde()) {
  2157. auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
  2158. auto corrected_offset = offset - matching_node->position().start_offset;
  2159. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  2160. if (corrected_offset > node->text().length())
  2161. return {};
  2162. auto text = node->text().substring(1, node->text().length() - 1);
  2163. return shell.complete_path(tilde_value, text, corrected_offset - 1);
  2164. }
  2165. return Node::complete_for_editor(shell, offset, hit_test_result);
  2166. }
  2167. HitTestResult Juxtaposition::hit_test_position(size_t offset)
  2168. {
  2169. if (!position().contains(offset))
  2170. return {};
  2171. auto result = m_left->hit_test_position(offset);
  2172. if (!result.closest_node_with_semantic_meaning)
  2173. result.closest_node_with_semantic_meaning = this;
  2174. if (result.matching_node)
  2175. return result;
  2176. result = m_right->hit_test_position(offset);
  2177. if (!result.closest_node_with_semantic_meaning)
  2178. result.closest_node_with_semantic_meaning = this;
  2179. return result;
  2180. }
  2181. Juxtaposition::Juxtaposition(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  2182. : Node(move(position))
  2183. , m_left(move(left))
  2184. , m_right(move(right))
  2185. {
  2186. if (m_left->is_syntax_error())
  2187. set_is_syntax_error(m_left->syntax_error_node());
  2188. else if (m_right->is_syntax_error())
  2189. set_is_syntax_error(m_right->syntax_error_node());
  2190. }
  2191. Juxtaposition::~Juxtaposition()
  2192. {
  2193. }
  2194. void StringLiteral::dump(int level) const
  2195. {
  2196. Node::dump(level);
  2197. print_indented(m_text, level + 1);
  2198. }
  2199. RefPtr<Value> StringLiteral::run(RefPtr<Shell>)
  2200. {
  2201. return create<StringValue>(m_text);
  2202. }
  2203. void StringLiteral::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  2204. {
  2205. if (m_text.is_empty())
  2206. return;
  2207. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  2208. if (metadata.is_first_in_list)
  2209. style.unify_with({ Line::Style::Bold });
  2210. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  2211. }
  2212. StringLiteral::StringLiteral(Position position, String text)
  2213. : Node(move(position))
  2214. , m_text(move(text))
  2215. {
  2216. }
  2217. StringLiteral::~StringLiteral()
  2218. {
  2219. }
  2220. void StringPartCompose::dump(int level) const
  2221. {
  2222. Node::dump(level);
  2223. m_left->dump(level + 1);
  2224. m_right->dump(level + 1);
  2225. }
  2226. RefPtr<Value> StringPartCompose::run(RefPtr<Shell> shell)
  2227. {
  2228. auto left = m_left->run(shell)->resolve_as_list(shell);
  2229. auto right = m_right->run(shell)->resolve_as_list(shell);
  2230. StringBuilder builder;
  2231. builder.join(" ", left);
  2232. builder.join(" ", right);
  2233. return create<StringValue>(builder.to_string());
  2234. }
  2235. void StringPartCompose::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2236. {
  2237. m_left->highlight_in_editor(editor, shell, metadata);
  2238. m_right->highlight_in_editor(editor, shell, metadata);
  2239. }
  2240. HitTestResult StringPartCompose::hit_test_position(size_t offset)
  2241. {
  2242. if (!position().contains(offset))
  2243. return {};
  2244. auto result = m_left->hit_test_position(offset);
  2245. if (result.matching_node)
  2246. return result;
  2247. return m_right->hit_test_position(offset);
  2248. }
  2249. StringPartCompose::StringPartCompose(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  2250. : Node(move(position))
  2251. , m_left(move(left))
  2252. , m_right(move(right))
  2253. {
  2254. if (m_left->is_syntax_error())
  2255. set_is_syntax_error(m_left->syntax_error_node());
  2256. else if (m_right->is_syntax_error())
  2257. set_is_syntax_error(m_right->syntax_error_node());
  2258. }
  2259. StringPartCompose::~StringPartCompose()
  2260. {
  2261. }
  2262. void SyntaxError::dump(int level) const
  2263. {
  2264. Node::dump(level);
  2265. print_indented("(Error text)", level + 1);
  2266. print_indented(m_syntax_error_text, level + 2);
  2267. print_indented("(Can be recovered from)", level + 1);
  2268. print_indented(String::formatted("{}", m_is_continuable), level + 2);
  2269. }
  2270. RefPtr<Value> SyntaxError::run(RefPtr<Shell> shell)
  2271. {
  2272. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, m_syntax_error_text, position());
  2273. return create<StringValue>("");
  2274. }
  2275. void SyntaxError::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  2276. {
  2277. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Bold });
  2278. }
  2279. SyntaxError::SyntaxError(Position position, String error, bool is_continuable)
  2280. : Node(move(position))
  2281. , m_syntax_error_text(move(error))
  2282. , m_is_continuable(is_continuable)
  2283. {
  2284. m_is_syntax_error = true;
  2285. }
  2286. const SyntaxError& SyntaxError::syntax_error_node() const
  2287. {
  2288. return *this;
  2289. }
  2290. SyntaxError::~SyntaxError()
  2291. {
  2292. }
  2293. void Tilde::dump(int level) const
  2294. {
  2295. Node::dump(level);
  2296. print_indented(m_username, level + 1);
  2297. }
  2298. RefPtr<Value> Tilde::run(RefPtr<Shell>)
  2299. {
  2300. return create<TildeValue>(m_username);
  2301. }
  2302. void Tilde::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
  2303. {
  2304. }
  2305. HitTestResult Tilde::hit_test_position(size_t offset)
  2306. {
  2307. if (!position().contains(offset))
  2308. return {};
  2309. return { this, this, nullptr };
  2310. }
  2311. Vector<Line::CompletionSuggestion> Tilde::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  2312. {
  2313. auto matching_node = hit_test_result.matching_node;
  2314. if (!matching_node)
  2315. return {};
  2316. if (matching_node != this)
  2317. return {};
  2318. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  2319. if (corrected_offset > m_username.length() + 1)
  2320. return {};
  2321. return shell.complete_user(m_username, corrected_offset);
  2322. }
  2323. String Tilde::text() const
  2324. {
  2325. StringBuilder builder;
  2326. builder.append('~');
  2327. builder.append(m_username);
  2328. return builder.to_string();
  2329. }
  2330. Tilde::Tilde(Position position, String username)
  2331. : Node(move(position))
  2332. , m_username(move(username))
  2333. {
  2334. }
  2335. Tilde::~Tilde()
  2336. {
  2337. }
  2338. void WriteAppendRedirection::dump(int level) const
  2339. {
  2340. Node::dump(level);
  2341. m_path->dump(level + 1);
  2342. print_indented(String::format("From %d", m_fd), level + 1);
  2343. }
  2344. RefPtr<Value> WriteAppendRedirection::run(RefPtr<Shell> shell)
  2345. {
  2346. Command command;
  2347. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2348. StringBuilder builder;
  2349. builder.join(" ", path_segments);
  2350. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::WriteAppend));
  2351. return create<CommandValue>(move(command));
  2352. }
  2353. WriteAppendRedirection::WriteAppendRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2354. : PathRedirectionNode(move(position), fd, move(path))
  2355. {
  2356. }
  2357. WriteAppendRedirection::~WriteAppendRedirection()
  2358. {
  2359. }
  2360. void WriteRedirection::dump(int level) const
  2361. {
  2362. Node::dump(level);
  2363. m_path->dump(level + 1);
  2364. print_indented(String::format("From %d", m_fd), level + 1);
  2365. }
  2366. RefPtr<Value> WriteRedirection::run(RefPtr<Shell> shell)
  2367. {
  2368. Command command;
  2369. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2370. StringBuilder builder;
  2371. builder.join(" ", path_segments);
  2372. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Write));
  2373. return create<CommandValue>(move(command));
  2374. }
  2375. WriteRedirection::WriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2376. : PathRedirectionNode(move(position), fd, move(path))
  2377. {
  2378. }
  2379. WriteRedirection::~WriteRedirection()
  2380. {
  2381. }
  2382. void VariableDeclarations::dump(int level) const
  2383. {
  2384. Node::dump(level);
  2385. for (auto& var : m_variables) {
  2386. print_indented("Set", level + 1);
  2387. var.name->dump(level + 2);
  2388. var.value->dump(level + 2);
  2389. }
  2390. }
  2391. RefPtr<Value> VariableDeclarations::run(RefPtr<Shell> shell)
  2392. {
  2393. for (auto& var : m_variables) {
  2394. auto name_value = var.name->run(shell)->resolve_as_list(shell);
  2395. ASSERT(name_value.size() == 1);
  2396. auto name = name_value[0];
  2397. auto value = var.value->run(shell);
  2398. shell->set_local_variable(name, value.release_nonnull());
  2399. }
  2400. return create<ListValue>({});
  2401. }
  2402. void VariableDeclarations::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2403. {
  2404. metadata.is_first_in_list = false;
  2405. for (auto& var : m_variables) {
  2406. var.name->highlight_in_editor(editor, shell, metadata);
  2407. // Highlight the '='.
  2408. editor.stylize({ var.name->position().end_offset - 1, var.name->position().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
  2409. var.value->highlight_in_editor(editor, shell, metadata);
  2410. }
  2411. }
  2412. HitTestResult VariableDeclarations::hit_test_position(size_t offset)
  2413. {
  2414. if (!position().contains(offset))
  2415. return {};
  2416. for (auto decl : m_variables) {
  2417. auto result = decl.value->hit_test_position(offset);
  2418. if (result.matching_node)
  2419. return result;
  2420. }
  2421. return { nullptr, nullptr, nullptr };
  2422. }
  2423. VariableDeclarations::VariableDeclarations(Position position, Vector<Variable> variables)
  2424. : Node(move(position))
  2425. , m_variables(move(variables))
  2426. {
  2427. for (auto& decl : m_variables) {
  2428. if (decl.name->is_syntax_error()) {
  2429. set_is_syntax_error(decl.name->syntax_error_node());
  2430. break;
  2431. }
  2432. if (decl.value->is_syntax_error()) {
  2433. set_is_syntax_error(decl.value->syntax_error_node());
  2434. break;
  2435. }
  2436. }
  2437. }
  2438. VariableDeclarations::~VariableDeclarations()
  2439. {
  2440. }
  2441. Value::~Value()
  2442. {
  2443. }
  2444. Vector<AST::Command> Value::resolve_as_commands(RefPtr<Shell> shell)
  2445. {
  2446. Command command;
  2447. command.argv = resolve_as_list(shell);
  2448. return { command };
  2449. }
  2450. ListValue::ListValue(Vector<String> values)
  2451. {
  2452. m_contained_values.ensure_capacity(values.size());
  2453. for (auto& str : values)
  2454. m_contained_values.append(adopt(*new StringValue(move(str))));
  2455. }
  2456. ListValue::~ListValue()
  2457. {
  2458. }
  2459. Vector<String> ListValue::resolve_as_list(RefPtr<Shell> shell)
  2460. {
  2461. Vector<String> values;
  2462. for (auto& value : m_contained_values)
  2463. values.append(value.resolve_as_list(shell));
  2464. return values;
  2465. }
  2466. NonnullRefPtr<Value> ListValue::resolve_without_cast(RefPtr<Shell> shell)
  2467. {
  2468. NonnullRefPtrVector<Value> values;
  2469. for (auto& value : m_contained_values)
  2470. values.append(value.resolve_without_cast(shell));
  2471. return create<ListValue>(move(values));
  2472. }
  2473. CommandValue::~CommandValue()
  2474. {
  2475. }
  2476. CommandSequenceValue::~CommandSequenceValue()
  2477. {
  2478. }
  2479. Vector<String> CommandSequenceValue::resolve_as_list(RefPtr<Shell>)
  2480. {
  2481. // TODO: Somehow raise an "error".
  2482. return {};
  2483. }
  2484. Vector<Command> CommandSequenceValue::resolve_as_commands(RefPtr<Shell>)
  2485. {
  2486. return m_contained_values;
  2487. }
  2488. Vector<String> CommandValue::resolve_as_list(RefPtr<Shell>)
  2489. {
  2490. // TODO: Somehow raise an "error".
  2491. return {};
  2492. }
  2493. Vector<Command> CommandValue::resolve_as_commands(RefPtr<Shell>)
  2494. {
  2495. return { m_command };
  2496. }
  2497. JobValue::~JobValue()
  2498. {
  2499. }
  2500. StringValue::~StringValue()
  2501. {
  2502. }
  2503. Vector<String> StringValue::resolve_as_list(RefPtr<Shell>)
  2504. {
  2505. if (is_list()) {
  2506. auto parts = StringView(m_string).split_view(m_split, m_keep_empty);
  2507. Vector<String> result;
  2508. result.ensure_capacity(parts.size());
  2509. for (auto& part : parts)
  2510. result.append(part);
  2511. return result;
  2512. }
  2513. return { m_string };
  2514. }
  2515. GlobValue::~GlobValue()
  2516. {
  2517. }
  2518. Vector<String> GlobValue::resolve_as_list(RefPtr<Shell> shell)
  2519. {
  2520. if (!shell)
  2521. return { m_glob };
  2522. auto results = shell->expand_globs(m_glob, shell->cwd);
  2523. if (results.is_empty())
  2524. shell->raise_error(Shell::ShellError::InvalidGlobError, "Glob did not match anything!", m_generation_position);
  2525. return results;
  2526. }
  2527. SimpleVariableValue::~SimpleVariableValue()
  2528. {
  2529. }
  2530. Vector<String> SimpleVariableValue::resolve_as_list(RefPtr<Shell> shell)
  2531. {
  2532. if (!shell)
  2533. return {};
  2534. if (auto value = resolve_without_cast(shell); value != this)
  2535. return value->resolve_as_list(shell);
  2536. char* env_value = getenv(m_name.characters());
  2537. if (env_value == nullptr)
  2538. return { "" };
  2539. Vector<String> res;
  2540. String str_env_value = String(env_value);
  2541. const auto& split_text = str_env_value.split_view(' ');
  2542. for (auto& part : split_text)
  2543. res.append(part);
  2544. return res;
  2545. }
  2546. NonnullRefPtr<Value> SimpleVariableValue::resolve_without_cast(RefPtr<Shell> shell)
  2547. {
  2548. ASSERT(shell);
  2549. if (auto value = shell->lookup_local_variable(m_name))
  2550. return value.release_nonnull();
  2551. return *this;
  2552. }
  2553. SpecialVariableValue::~SpecialVariableValue()
  2554. {
  2555. }
  2556. Vector<String> SpecialVariableValue::resolve_as_list(RefPtr<Shell> shell)
  2557. {
  2558. if (!shell)
  2559. return {};
  2560. switch (m_name) {
  2561. case '?':
  2562. return { String::number(shell->last_return_code) };
  2563. case '$':
  2564. return { String::number(getpid()) };
  2565. case '*':
  2566. if (auto argv = shell->lookup_local_variable("ARGV"))
  2567. return argv->resolve_as_list(shell);
  2568. return {};
  2569. case '#':
  2570. if (auto argv = shell->lookup_local_variable("ARGV")) {
  2571. if (argv->is_list()) {
  2572. auto list_argv = static_cast<AST::ListValue*>(argv.ptr());
  2573. return { String::number(list_argv->values().size()) };
  2574. }
  2575. return { "1" };
  2576. }
  2577. return { "0" };
  2578. default:
  2579. return { "" };
  2580. }
  2581. }
  2582. TildeValue::~TildeValue()
  2583. {
  2584. }
  2585. Vector<String> TildeValue::resolve_as_list(RefPtr<Shell> shell)
  2586. {
  2587. StringBuilder builder;
  2588. builder.append("~");
  2589. builder.append(m_username);
  2590. if (!shell)
  2591. return { builder.to_string() };
  2592. return { shell->expand_tilde(builder.to_string()) };
  2593. }
  2594. Result<NonnullRefPtr<Rewiring>, String> CloseRedirection::apply() const
  2595. {
  2596. return adopt(*new Rewiring(fd, fd, Rewiring::Close::ImmediatelyCloseNew));
  2597. }
  2598. CloseRedirection::~CloseRedirection()
  2599. {
  2600. }
  2601. Result<NonnullRefPtr<Rewiring>, String> PathRedirection::apply() const
  2602. {
  2603. auto check_fd_and_return = [my_fd = this->fd](int fd, const String& path) -> Result<NonnullRefPtr<Rewiring>, String> {
  2604. if (fd < 0) {
  2605. String error = strerror(errno);
  2606. dbgln("open() failed for '{}' with {}", path, error);
  2607. return error;
  2608. }
  2609. return adopt(*new Rewiring(fd, my_fd, Rewiring::Close::Old));
  2610. };
  2611. switch (direction) {
  2612. case AST::PathRedirection::WriteAppend:
  2613. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666), path);
  2614. case AST::PathRedirection::Write:
  2615. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666), path);
  2616. case AST::PathRedirection::Read:
  2617. return check_fd_and_return(open(path.characters(), O_RDONLY), path);
  2618. case AST::PathRedirection::ReadWrite:
  2619. return check_fd_and_return(open(path.characters(), O_RDWR | O_CREAT, 0666), path);
  2620. }
  2621. ASSERT_NOT_REACHED();
  2622. }
  2623. PathRedirection::~PathRedirection()
  2624. {
  2625. }
  2626. FdRedirection::~FdRedirection()
  2627. {
  2628. }
  2629. Redirection::~Redirection()
  2630. {
  2631. }
  2632. }