AST.cpp 95 KB

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