AST.cpp 107 KB

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