AST.cpp 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532
  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.extend(last_in_left.argv);
  123. command.argv.extend(first_in_right.argv);
  124. command.redirections.extend(last_in_left.redirections);
  125. command.redirections.extend(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.extend(left);
  132. commands.append(command);
  133. commands.extend(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(make_ref_counted<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 make_ref_counted<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 = make_ref_counted<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 = make_ref_counted<CommandValue>(command);
  388. } else {
  389. result = make_ref_counted<CommandSequenceValue>(move(joined_commands));
  390. }
  391. } else {
  392. NonnullRefPtrVector<Value> values;
  393. if (result->is_list_without_resolution()) {
  394. values.extend(static_cast<ListValue*>(result.ptr())->values());
  395. } else {
  396. for (auto& result : result->resolve_as_list(shell))
  397. values.append(make_ref_counted<StringValue>(result));
  398. }
  399. values.append(element_value);
  400. result = make_ref_counted<ListValue>(move(values));
  401. }
  402. }
  403. if (!result)
  404. return make_ref_counted<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 make_ref_counted<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 make_ref_counted<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.find('=').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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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(make_ref_counted<StringValue>(value));
  657. return make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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.extend(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 make_ref_counted<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(), make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<AST::ListValue>({});
  1191. auto editor = shell->editor();
  1192. if (!editor) {
  1193. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "No history available!", position());
  1194. return make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 make_ref_counted<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 = make_ref_counted<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 make_ref_counted<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. // Make sure that we're going to be running _something_.
  1303. auto has_one_command = false;
  1304. for (auto& command : commands) {
  1305. if (command.argv.is_empty() && !command.pipeline && command.next_chain.is_empty())
  1306. continue;
  1307. has_one_command = true;
  1308. break;
  1309. }
  1310. if (!has_one_command) {
  1311. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Cannot capture standard output when no command is being executed", m_position);
  1312. return;
  1313. }
  1314. int pipefd[2];
  1315. int rc = pipe(pipefd);
  1316. if (rc < 0) {
  1317. dbgln("Error: cannot pipe(): {}", strerror(errno));
  1318. return;
  1319. }
  1320. auto& last_in_commands = commands.last();
  1321. last_in_commands.redirections.prepend(FdRedirection::create(pipefd[1], STDOUT_FILENO, Rewiring::Close::Old));
  1322. last_in_commands.should_wait = false;
  1323. last_in_commands.should_notify_if_in_background = false;
  1324. last_in_commands.is_pipe_source = false;
  1325. Core::EventLoop loop;
  1326. auto notifier = Core::Notifier::construct(pipefd[0], Core::Notifier::Read);
  1327. DuplexMemoryStream stream;
  1328. enum {
  1329. Continue,
  1330. Break,
  1331. NothingLeft,
  1332. };
  1333. auto check_and_call = [&] {
  1334. auto ifs = shell->local_variable_or("IFS", "\n");
  1335. if (auto offset = stream.offset_of(ifs.bytes()); offset.has_value()) {
  1336. auto line_end = offset.value();
  1337. if (line_end == 0) {
  1338. auto rc = stream.discard_or_error(ifs.length());
  1339. VERIFY(rc);
  1340. if (shell->options.inline_exec_keep_empty_segments)
  1341. if (callback(make_ref_counted<StringValue>("")) == IterationDecision::Break) {
  1342. loop.quit(Break);
  1343. notifier->set_enabled(false);
  1344. return Break;
  1345. }
  1346. } else {
  1347. auto entry_result = ByteBuffer::create_uninitialized(line_end + ifs.length());
  1348. if (!entry_result.has_value()) {
  1349. loop.quit(Break);
  1350. notifier->set_enabled(false);
  1351. return Break;
  1352. }
  1353. auto entry = entry_result.release_value();
  1354. auto rc = stream.read_or_error(entry);
  1355. VERIFY(rc);
  1356. auto str = StringView(entry.data(), entry.size() - ifs.length());
  1357. if (callback(make_ref_counted<StringValue>(str)) == IterationDecision::Break) {
  1358. loop.quit(Break);
  1359. notifier->set_enabled(false);
  1360. return Break;
  1361. }
  1362. }
  1363. return Continue;
  1364. }
  1365. return NothingLeft;
  1366. };
  1367. notifier->on_ready_to_read = [&] {
  1368. constexpr static auto buffer_size = 16;
  1369. u8 buffer[buffer_size];
  1370. size_t remaining_size = buffer_size;
  1371. for (;;) {
  1372. notifier->set_event_mask(Core::Notifier::None);
  1373. bool should_enable_notifier = false;
  1374. ScopeGuard notifier_enabler { [&] {
  1375. if (should_enable_notifier)
  1376. notifier->set_event_mask(Core::Notifier::Read);
  1377. } };
  1378. if (check_and_call() == Break) {
  1379. loop.quit(Break);
  1380. return;
  1381. }
  1382. auto read_size = read(pipefd[0], buffer, remaining_size);
  1383. if (read_size < 0) {
  1384. int saved_errno = errno;
  1385. if (saved_errno == EINTR) {
  1386. should_enable_notifier = true;
  1387. continue;
  1388. }
  1389. if (saved_errno == 0)
  1390. continue;
  1391. dbgln("read() failed: {}", strerror(saved_errno));
  1392. break;
  1393. }
  1394. if (read_size == 0)
  1395. break;
  1396. should_enable_notifier = true;
  1397. stream.write({ buffer, (size_t)read_size });
  1398. }
  1399. loop.quit(NothingLeft);
  1400. };
  1401. auto jobs = shell->run_commands(commands);
  1402. ScopeGuard kill_jobs_if_around { [&] {
  1403. for (auto& job : jobs) {
  1404. if (job.is_running_in_background() && !job.exited() && !job.signaled()) {
  1405. job.set_should_announce_signal(false); // We're explicitly killing it here.
  1406. shell->kill_job(&job, SIGTERM);
  1407. }
  1408. }
  1409. } };
  1410. auto exit_reason = loop.exec();
  1411. notifier->on_ready_to_read = nullptr;
  1412. if (close(pipefd[0]) < 0) {
  1413. dbgln("close() failed: {}", strerror(errno));
  1414. }
  1415. if (exit_reason != Break && !stream.eof()) {
  1416. auto action = Continue;
  1417. do {
  1418. action = check_and_call();
  1419. if (action == Break)
  1420. return;
  1421. } while (action == Continue);
  1422. if (!stream.eof()) {
  1423. auto entry_result = ByteBuffer::create_uninitialized(stream.size());
  1424. if (!entry_result.has_value()) {
  1425. shell->raise_error(Shell::ShellError::OutOfMemory, {}, position());
  1426. return;
  1427. }
  1428. auto entry = entry_result.release_value();
  1429. auto rc = stream.read_or_error(entry);
  1430. VERIFY(rc);
  1431. callback(make_ref_counted<StringValue>(String::copy(entry)));
  1432. }
  1433. }
  1434. return;
  1435. }
  1436. auto jobs = shell->run_commands(commands);
  1437. if (!jobs.is_empty())
  1438. callback(make_ref_counted<JobValue>(&jobs.last()));
  1439. }
  1440. RefPtr<Value> Execute::run(RefPtr<Shell> shell)
  1441. {
  1442. if (m_command->would_execute())
  1443. return m_command->run(shell);
  1444. NonnullRefPtrVector<Value> values;
  1445. for_each_entry(shell, [&](auto value) {
  1446. values.append(*value);
  1447. return IterationDecision::Continue;
  1448. });
  1449. if (values.size() == 1 && values.first().is_job())
  1450. return values.first();
  1451. return make_ref_counted<ListValue>(move(values));
  1452. }
  1453. void Execute::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1454. {
  1455. if (m_capture_stdout)
  1456. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  1457. metadata.is_first_in_list = true;
  1458. m_command->highlight_in_editor(editor, shell, metadata);
  1459. }
  1460. HitTestResult Execute::hit_test_position(size_t offset) const
  1461. {
  1462. auto result = m_command->hit_test_position(offset);
  1463. if (!result.closest_node_with_semantic_meaning)
  1464. result.closest_node_with_semantic_meaning = this;
  1465. if (!result.closest_command_node)
  1466. result.closest_command_node = m_command;
  1467. return result;
  1468. }
  1469. Vector<Line::CompletionSuggestion> Execute::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1470. {
  1471. auto matching_node = hit_test_result.matching_node;
  1472. if (!matching_node || !matching_node->is_bareword())
  1473. return {};
  1474. auto corrected_offset = offset - matching_node->position().start_offset;
  1475. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  1476. if (corrected_offset > node->text().length())
  1477. return {};
  1478. return shell.complete_program_name(node->text(), corrected_offset);
  1479. }
  1480. Execute::Execute(Position position, NonnullRefPtr<Node> command, bool capture_stdout)
  1481. : Node(move(position))
  1482. , m_command(move(command))
  1483. , m_capture_stdout(capture_stdout)
  1484. {
  1485. if (m_command->is_syntax_error())
  1486. set_is_syntax_error(m_command->syntax_error_node());
  1487. }
  1488. Execute::~Execute()
  1489. {
  1490. }
  1491. void IfCond::dump(int level) const
  1492. {
  1493. Node::dump(level);
  1494. print_indented("Condition", ++level);
  1495. m_condition->dump(level + 1);
  1496. print_indented("True Branch", level);
  1497. if (m_true_branch)
  1498. m_true_branch->dump(level + 1);
  1499. else
  1500. print_indented("(empty)", level + 1);
  1501. print_indented("False Branch", level);
  1502. if (m_false_branch)
  1503. m_false_branch->dump(level + 1);
  1504. else
  1505. print_indented("(empty)", level + 1);
  1506. }
  1507. RefPtr<Value> IfCond::run(RefPtr<Shell> shell)
  1508. {
  1509. auto cond = m_condition->run(shell)->resolve_without_cast(shell);
  1510. // The condition could be a builtin, in which case it has already run and exited.
  1511. if (cond->is_job()) {
  1512. auto cond_job_value = static_cast<const JobValue*>(cond.ptr());
  1513. auto cond_job = cond_job_value->job();
  1514. shell->block_on_job(cond_job);
  1515. }
  1516. if (shell->last_return_code == 0) {
  1517. if (m_true_branch)
  1518. return m_true_branch->run(shell);
  1519. } else {
  1520. if (m_false_branch)
  1521. return m_false_branch->run(shell);
  1522. }
  1523. return make_ref_counted<ListValue>({});
  1524. }
  1525. void IfCond::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1526. {
  1527. metadata.is_first_in_list = true;
  1528. editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1529. if (m_else_position.has_value())
  1530. editor.stylize({ m_else_position.value().start_offset, m_else_position.value().start_offset + 4 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1531. m_condition->highlight_in_editor(editor, shell, metadata);
  1532. if (m_true_branch)
  1533. m_true_branch->highlight_in_editor(editor, shell, metadata);
  1534. if (m_false_branch)
  1535. m_false_branch->highlight_in_editor(editor, shell, metadata);
  1536. }
  1537. HitTestResult IfCond::hit_test_position(size_t offset) const
  1538. {
  1539. if (auto result = m_condition->hit_test_position(offset); result.matching_node)
  1540. return result;
  1541. if (m_true_branch) {
  1542. if (auto result = m_true_branch->hit_test_position(offset); result.matching_node)
  1543. return result;
  1544. }
  1545. if (m_false_branch) {
  1546. if (auto result = m_false_branch->hit_test_position(offset); result.matching_node)
  1547. return result;
  1548. }
  1549. return {};
  1550. }
  1551. IfCond::IfCond(Position position, Optional<Position> else_position, NonnullRefPtr<Node> condition, RefPtr<Node> true_branch, RefPtr<Node> false_branch)
  1552. : Node(move(position))
  1553. , m_condition(move(condition))
  1554. , m_true_branch(move(true_branch))
  1555. , m_false_branch(move(false_branch))
  1556. , m_else_position(move(else_position))
  1557. {
  1558. if (m_condition->is_syntax_error())
  1559. set_is_syntax_error(m_condition->syntax_error_node());
  1560. else if (m_true_branch && m_true_branch->is_syntax_error())
  1561. set_is_syntax_error(m_true_branch->syntax_error_node());
  1562. else if (m_false_branch && m_false_branch->is_syntax_error())
  1563. set_is_syntax_error(m_false_branch->syntax_error_node());
  1564. m_condition = make_ref_counted<AST::Execute>(m_condition->position(), m_condition);
  1565. if (m_true_branch) {
  1566. auto true_branch = m_true_branch.release_nonnull();
  1567. if (true_branch->is_execute())
  1568. m_true_branch = static_ptr_cast<AST::Execute>(true_branch)->command();
  1569. else
  1570. m_true_branch = move(true_branch);
  1571. }
  1572. if (m_false_branch) {
  1573. auto false_branch = m_false_branch.release_nonnull();
  1574. if (false_branch->is_execute())
  1575. m_false_branch = static_ptr_cast<AST::Execute>(false_branch)->command();
  1576. else
  1577. m_false_branch = move(false_branch);
  1578. }
  1579. }
  1580. IfCond::~IfCond()
  1581. {
  1582. }
  1583. void ImmediateExpression::dump(int level) const
  1584. {
  1585. Node::dump(level);
  1586. print_indented("(function)", level + 1);
  1587. print_indented(m_function.name, level + 2);
  1588. print_indented("(arguments)", level + 1);
  1589. for (auto& argument : arguments())
  1590. argument.dump(level + 2);
  1591. }
  1592. RefPtr<Value> ImmediateExpression::run(RefPtr<Shell> shell)
  1593. {
  1594. auto node = shell->run_immediate_function(m_function.name, *this, arguments());
  1595. if (node)
  1596. return node->run(shell);
  1597. return make_ref_counted<ListValue>({});
  1598. }
  1599. void ImmediateExpression::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1600. {
  1601. // '${' - FIXME: This could also be '$\\\n{'
  1602. editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  1603. // Function name
  1604. Line::Style function_style { Line::Style::Foreground(Line::Style::XtermColor::Red) };
  1605. if (shell.has_immediate_function(function_name()))
  1606. function_style = { Line::Style::Foreground(Line::Style::XtermColor::Green) };
  1607. editor.stylize({ m_function.position.start_offset, m_function.position.end_offset }, move(function_style));
  1608. // Arguments
  1609. for (auto& argument : m_arguments) {
  1610. metadata.is_first_in_list = false;
  1611. argument.highlight_in_editor(editor, shell, metadata);
  1612. }
  1613. // Closing brace
  1614. if (m_closing_brace_position.has_value())
  1615. editor.stylize({ m_closing_brace_position->start_offset, m_closing_brace_position->end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  1616. }
  1617. Vector<Line::CompletionSuggestion> ImmediateExpression::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1618. {
  1619. auto matching_node = hit_test_result.matching_node;
  1620. if (!matching_node || matching_node != this)
  1621. return {};
  1622. auto corrected_offset = offset - m_function.position.start_offset;
  1623. if (corrected_offset > m_function.name.length())
  1624. return {};
  1625. return shell.complete_immediate_function_name(m_function.name, corrected_offset);
  1626. }
  1627. HitTestResult ImmediateExpression::hit_test_position(size_t offset) const
  1628. {
  1629. if (m_function.position.contains(offset))
  1630. return { this, this, this };
  1631. for (auto& argument : m_arguments) {
  1632. if (auto result = argument.hit_test_position(offset); result.matching_node)
  1633. return result;
  1634. }
  1635. return {};
  1636. }
  1637. ImmediateExpression::ImmediateExpression(Position position, NameWithPosition function, NonnullRefPtrVector<AST::Node> arguments, Optional<Position> closing_brace_position)
  1638. : Node(move(position))
  1639. , m_arguments(move(arguments))
  1640. , m_function(move(function))
  1641. , m_closing_brace_position(move(closing_brace_position))
  1642. {
  1643. if (is_syntax_error())
  1644. return;
  1645. for (auto& argument : m_arguments) {
  1646. if (argument.is_syntax_error()) {
  1647. set_is_syntax_error(argument.syntax_error_node());
  1648. return;
  1649. }
  1650. }
  1651. }
  1652. ImmediateExpression::~ImmediateExpression()
  1653. {
  1654. }
  1655. void Join::dump(int level) const
  1656. {
  1657. Node::dump(level);
  1658. m_left->dump(level + 1);
  1659. m_right->dump(level + 1);
  1660. }
  1661. RefPtr<Value> Join::run(RefPtr<Shell> shell)
  1662. {
  1663. auto left = m_left->to_lazy_evaluated_commands(shell);
  1664. auto right = m_right->to_lazy_evaluated_commands(shell);
  1665. return make_ref_counted<CommandSequenceValue>(join_commands(move(left), move(right)));
  1666. }
  1667. void Join::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1668. {
  1669. m_left->highlight_in_editor(editor, shell, metadata);
  1670. if (m_left->is_list() || m_left->is_command())
  1671. metadata.is_first_in_list = false;
  1672. m_right->highlight_in_editor(editor, shell, metadata);
  1673. }
  1674. HitTestResult Join::hit_test_position(size_t offset) const
  1675. {
  1676. auto result = m_left->hit_test_position(offset);
  1677. if (result.matching_node)
  1678. return result;
  1679. return m_right->hit_test_position(offset);
  1680. }
  1681. RefPtr<Node> Join::leftmost_trivial_literal() const
  1682. {
  1683. if (auto value = m_left->leftmost_trivial_literal())
  1684. return value;
  1685. return m_right->leftmost_trivial_literal();
  1686. }
  1687. Join::Join(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  1688. : Node(move(position))
  1689. , m_left(move(left))
  1690. , m_right(move(right))
  1691. {
  1692. if (m_left->is_syntax_error())
  1693. set_is_syntax_error(m_left->syntax_error_node());
  1694. else if (m_right->is_syntax_error())
  1695. set_is_syntax_error(m_right->syntax_error_node());
  1696. }
  1697. Join::~Join()
  1698. {
  1699. }
  1700. void MatchExpr::dump(int level) const
  1701. {
  1702. Node::dump(level);
  1703. print_indented(String::formatted("(expression: {})", m_expr_name.characters()), level + 1);
  1704. m_matched_expr->dump(level + 2);
  1705. print_indented(String::formatted("(named: {})", m_expr_name.characters()), level + 1);
  1706. print_indented("(entries)", level + 1);
  1707. for (auto& entry : m_entries) {
  1708. StringBuilder builder;
  1709. builder.append("(match");
  1710. if (entry.match_names.has_value()) {
  1711. builder.append(" to names (");
  1712. bool first = true;
  1713. for (auto& name : entry.match_names.value()) {
  1714. if (!first)
  1715. builder.append(' ');
  1716. first = false;
  1717. builder.append(name);
  1718. }
  1719. builder.append("))");
  1720. } else {
  1721. builder.append(')');
  1722. }
  1723. print_indented(builder.string_view(), level + 2);
  1724. for (auto& node : entry.options)
  1725. node.dump(level + 3);
  1726. print_indented("(execute)", level + 2);
  1727. if (entry.body)
  1728. entry.body->dump(level + 3);
  1729. else
  1730. print_indented("(nothing)", level + 3);
  1731. }
  1732. }
  1733. RefPtr<Value> MatchExpr::run(RefPtr<Shell> shell)
  1734. {
  1735. auto value = m_matched_expr->run(shell)->resolve_without_cast(shell);
  1736. auto list = value->resolve_as_list(shell);
  1737. auto list_matches = [&](auto&& pattern, auto& spans) {
  1738. if (pattern.size() != list.size())
  1739. return false;
  1740. for (size_t i = 0; i < pattern.size(); ++i) {
  1741. Vector<AK::MaskSpan> mask_spans;
  1742. if (!list[i].matches(pattern[i], mask_spans))
  1743. return false;
  1744. for (auto& span : mask_spans)
  1745. spans.append(list[i].substring(span.start, span.length));
  1746. }
  1747. return true;
  1748. };
  1749. auto resolve_pattern = [&](auto& option) {
  1750. Vector<String> pattern;
  1751. if (option.is_glob()) {
  1752. pattern.append(static_cast<const Glob*>(&option)->text());
  1753. } else if (option.is_bareword()) {
  1754. pattern.append(static_cast<const BarewordLiteral*>(&option)->text());
  1755. } else {
  1756. auto list = option.run(shell);
  1757. option.for_each_entry(shell, [&](auto&& value) {
  1758. pattern.extend(value->resolve_as_list(nullptr)); // Note: 'nullptr' incurs special behavior,
  1759. // asking the node for a 'raw' value.
  1760. return IterationDecision::Continue;
  1761. });
  1762. }
  1763. return pattern;
  1764. };
  1765. auto frame = shell->push_frame(String::formatted("match ({})", this));
  1766. if (!m_expr_name.is_empty())
  1767. shell->set_local_variable(m_expr_name, value, true);
  1768. for (auto& entry : m_entries) {
  1769. for (auto& option : entry.options) {
  1770. Vector<String> spans;
  1771. if (list_matches(resolve_pattern(option), spans)) {
  1772. if (entry.body) {
  1773. if (entry.match_names.has_value()) {
  1774. size_t i = 0;
  1775. for (auto& name : entry.match_names.value()) {
  1776. if (spans.size() > i)
  1777. shell->set_local_variable(name, make_ref_counted<AST::StringValue>(spans[i]), true);
  1778. ++i;
  1779. }
  1780. }
  1781. return entry.body->run(shell);
  1782. } else {
  1783. return make_ref_counted<AST::ListValue>({});
  1784. }
  1785. }
  1786. }
  1787. }
  1788. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Non-exhaustive match rules!", position());
  1789. return make_ref_counted<AST::ListValue>({});
  1790. }
  1791. void MatchExpr::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1792. {
  1793. editor.stylize({ m_position.start_offset, m_position.start_offset + 5 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1794. if (m_as_position.has_value())
  1795. editor.stylize({ m_as_position.value().start_offset, m_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1796. metadata.is_first_in_list = false;
  1797. m_matched_expr->highlight_in_editor(editor, shell, metadata);
  1798. for (auto& entry : m_entries) {
  1799. metadata.is_first_in_list = false;
  1800. for (auto& option : entry.options)
  1801. option.highlight_in_editor(editor, shell, metadata);
  1802. metadata.is_first_in_list = true;
  1803. if (entry.body)
  1804. entry.body->highlight_in_editor(editor, shell, metadata);
  1805. for (auto& position : entry.pipe_positions)
  1806. editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1807. if (entry.match_as_position.has_value())
  1808. editor.stylize({ entry.match_as_position.value().start_offset, entry.match_as_position.value().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  1809. }
  1810. }
  1811. HitTestResult MatchExpr::hit_test_position(size_t offset) const
  1812. {
  1813. auto result = m_matched_expr->hit_test_position(offset);
  1814. if (result.matching_node)
  1815. return result;
  1816. for (auto& entry : m_entries) {
  1817. if (!entry.body)
  1818. continue;
  1819. auto result = entry.body->hit_test_position(offset);
  1820. if (result.matching_node)
  1821. return result;
  1822. }
  1823. return {};
  1824. }
  1825. MatchExpr::MatchExpr(Position position, NonnullRefPtr<Node> expr, String name, Optional<Position> as_position, Vector<MatchEntry> entries)
  1826. : Node(move(position))
  1827. , m_matched_expr(move(expr))
  1828. , m_expr_name(move(name))
  1829. , m_as_position(move(as_position))
  1830. , m_entries(move(entries))
  1831. {
  1832. if (m_matched_expr->is_syntax_error()) {
  1833. set_is_syntax_error(m_matched_expr->syntax_error_node());
  1834. } else {
  1835. for (auto& entry : m_entries) {
  1836. if (!entry.body)
  1837. continue;
  1838. if (entry.body->is_syntax_error()) {
  1839. set_is_syntax_error(entry.body->syntax_error_node());
  1840. break;
  1841. }
  1842. }
  1843. }
  1844. }
  1845. MatchExpr::~MatchExpr()
  1846. {
  1847. }
  1848. void Or::dump(int level) const
  1849. {
  1850. Node::dump(level);
  1851. m_left->dump(level + 1);
  1852. m_right->dump(level + 1);
  1853. }
  1854. RefPtr<Value> Or::run(RefPtr<Shell> shell)
  1855. {
  1856. auto commands = m_left->to_lazy_evaluated_commands(shell);
  1857. commands.last().next_chain.empend(*m_right, NodeWithAction::Or);
  1858. return make_ref_counted<CommandSequenceValue>(move(commands));
  1859. }
  1860. void Or::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1861. {
  1862. m_left->highlight_in_editor(editor, shell, metadata);
  1863. m_right->highlight_in_editor(editor, shell, metadata);
  1864. }
  1865. HitTestResult Or::hit_test_position(size_t offset) const
  1866. {
  1867. auto result = m_left->hit_test_position(offset);
  1868. if (result.matching_node) {
  1869. if (!result.closest_command_node)
  1870. result.closest_command_node = m_right;
  1871. return result;
  1872. }
  1873. result = m_right->hit_test_position(offset);
  1874. if (!result.closest_command_node)
  1875. result.closest_command_node = m_right;
  1876. return result;
  1877. }
  1878. Or::Or(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right, Position or_position)
  1879. : Node(move(position))
  1880. , m_left(move(left))
  1881. , m_right(move(right))
  1882. , m_or_position(or_position)
  1883. {
  1884. if (m_left->is_syntax_error())
  1885. set_is_syntax_error(m_left->syntax_error_node());
  1886. else if (m_right->is_syntax_error())
  1887. set_is_syntax_error(m_right->syntax_error_node());
  1888. }
  1889. Or::~Or()
  1890. {
  1891. }
  1892. void Pipe::dump(int level) const
  1893. {
  1894. Node::dump(level);
  1895. m_left->dump(level + 1);
  1896. m_right->dump(level + 1);
  1897. }
  1898. RefPtr<Value> Pipe::run(RefPtr<Shell> shell)
  1899. {
  1900. auto left = m_left->to_lazy_evaluated_commands(shell);
  1901. auto right = m_right->to_lazy_evaluated_commands(shell);
  1902. auto last_in_left = left.take_last();
  1903. auto first_in_right = right.take_first();
  1904. auto pipe_read_end = FdRedirection::create(-1, STDIN_FILENO, Rewiring::Close::Old);
  1905. auto pipe_write_end = FdRedirection::create(-1, STDOUT_FILENO, pipe_read_end, Rewiring::Close::RefreshOld);
  1906. auto insert_at_start_or_after_last_pipe = [&](auto& pipe, auto& command) {
  1907. size_t insert_index = 0;
  1908. auto& redirections = command.redirections;
  1909. for (ssize_t i = redirections.size() - 1; i >= 0; --i) {
  1910. auto& redirection = redirections[i];
  1911. if (!redirection.is_fd_redirection())
  1912. continue;
  1913. auto& fd_redirection = static_cast<FdRedirection&>(redirection);
  1914. if (fd_redirection.old_fd == -1) {
  1915. insert_index = i;
  1916. break;
  1917. }
  1918. }
  1919. redirections.insert(insert_index, pipe);
  1920. };
  1921. insert_at_start_or_after_last_pipe(pipe_read_end, first_in_right);
  1922. insert_at_start_or_after_last_pipe(pipe_write_end, last_in_left);
  1923. last_in_left.should_wait = false;
  1924. last_in_left.is_pipe_source = true;
  1925. if (first_in_right.pipeline) {
  1926. last_in_left.pipeline = first_in_right.pipeline;
  1927. } else {
  1928. auto pipeline = make_ref_counted<Pipeline>();
  1929. last_in_left.pipeline = pipeline;
  1930. first_in_right.pipeline = pipeline;
  1931. }
  1932. Vector<Command> commands;
  1933. commands.extend(left);
  1934. commands.append(last_in_left);
  1935. commands.append(first_in_right);
  1936. commands.extend(right);
  1937. return make_ref_counted<CommandSequenceValue>(move(commands));
  1938. }
  1939. void Pipe::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1940. {
  1941. m_left->highlight_in_editor(editor, shell, metadata);
  1942. m_right->highlight_in_editor(editor, shell, metadata);
  1943. }
  1944. HitTestResult Pipe::hit_test_position(size_t offset) const
  1945. {
  1946. auto result = m_left->hit_test_position(offset);
  1947. if (result.matching_node) {
  1948. if (!result.closest_command_node)
  1949. result.closest_command_node = m_right;
  1950. return result;
  1951. }
  1952. result = m_right->hit_test_position(offset);
  1953. if (!result.closest_command_node)
  1954. result.closest_command_node = m_right;
  1955. return result;
  1956. }
  1957. Pipe::Pipe(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  1958. : Node(move(position))
  1959. , m_left(move(left))
  1960. , m_right(move(right))
  1961. {
  1962. if (m_left->is_syntax_error())
  1963. set_is_syntax_error(m_left->syntax_error_node());
  1964. else if (m_right->is_syntax_error())
  1965. set_is_syntax_error(m_right->syntax_error_node());
  1966. }
  1967. Pipe::~Pipe()
  1968. {
  1969. }
  1970. PathRedirectionNode::PathRedirectionNode(Position position, int fd, NonnullRefPtr<Node> path)
  1971. : Node(move(position))
  1972. , m_fd(fd)
  1973. , m_path(move(path))
  1974. {
  1975. }
  1976. void PathRedirectionNode::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1977. {
  1978. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  1979. metadata.is_first_in_list = false;
  1980. m_path->highlight_in_editor(editor, shell, metadata);
  1981. if (m_path->is_bareword()) {
  1982. auto path_text = m_path->run(nullptr)->resolve_as_list(nullptr);
  1983. VERIFY(path_text.size() == 1);
  1984. // Apply a URL to the path.
  1985. auto& position = m_path->position();
  1986. auto& path = path_text[0];
  1987. if (!path.starts_with('/'))
  1988. path = String::formatted("{}/{}", shell.cwd, path);
  1989. auto url = URL::create_with_file_protocol(path);
  1990. url.set_host(shell.hostname);
  1991. editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  1992. }
  1993. }
  1994. HitTestResult PathRedirectionNode::hit_test_position(size_t offset) const
  1995. {
  1996. auto result = m_path->hit_test_position(offset);
  1997. if (!result.closest_node_with_semantic_meaning)
  1998. result.closest_node_with_semantic_meaning = this;
  1999. return result;
  2000. }
  2001. Vector<Line::CompletionSuggestion> PathRedirectionNode::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  2002. {
  2003. auto matching_node = hit_test_result.matching_node;
  2004. if (!matching_node || !matching_node->is_bareword())
  2005. return {};
  2006. auto corrected_offset = offset - matching_node->position().start_offset;
  2007. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  2008. if (corrected_offset > node->text().length())
  2009. return {};
  2010. return shell.complete_path("", node->text(), corrected_offset, Shell::ExecutableOnly::No);
  2011. }
  2012. PathRedirectionNode::~PathRedirectionNode()
  2013. {
  2014. }
  2015. void Range::dump(int level) const
  2016. {
  2017. Node::dump(level);
  2018. print_indented("(From)", level + 1);
  2019. m_start->dump(level + 2);
  2020. print_indented("(To)", level + 1);
  2021. m_end->dump(level + 2);
  2022. }
  2023. RefPtr<Value> Range::run(RefPtr<Shell> shell)
  2024. {
  2025. auto interpolate = [position = position()](RefPtr<Value> start, RefPtr<Value> end, RefPtr<Shell> shell) -> NonnullRefPtrVector<Value> {
  2026. NonnullRefPtrVector<Value> values;
  2027. if (start->is_string() && end->is_string()) {
  2028. auto start_str = start->resolve_as_list(shell)[0];
  2029. auto end_str = end->resolve_as_list(shell)[0];
  2030. Utf8View start_view { start_str }, end_view { end_str };
  2031. if (start_view.validate() && end_view.validate()) {
  2032. if (start_view.length() == 1 && end_view.length() == 1) {
  2033. // Interpolate between two code points.
  2034. auto start_code_point = *start_view.begin();
  2035. auto end_code_point = *end_view.begin();
  2036. auto step = start_code_point > end_code_point ? -1 : 1;
  2037. StringBuilder builder;
  2038. for (u32 code_point = start_code_point; code_point != end_code_point; code_point += step) {
  2039. builder.clear();
  2040. builder.append_code_point(code_point);
  2041. values.append(make_ref_counted<StringValue>(builder.to_string()));
  2042. }
  2043. // Append the ending code point too, most shells treat this as inclusive.
  2044. builder.clear();
  2045. builder.append_code_point(end_code_point);
  2046. values.append(make_ref_counted<StringValue>(builder.to_string()));
  2047. } else {
  2048. // Could be two numbers?
  2049. auto start_int = start_str.to_int();
  2050. auto end_int = end_str.to_int();
  2051. if (start_int.has_value() && end_int.has_value()) {
  2052. auto start = start_int.value();
  2053. auto end = end_int.value();
  2054. auto step = start > end ? -1 : 1;
  2055. for (int value = start; value != end; value += step)
  2056. values.append(make_ref_counted<StringValue>(String::number(value)));
  2057. // Append the range end too, most shells treat this as inclusive.
  2058. values.append(make_ref_counted<StringValue>(String::number(end)));
  2059. } else {
  2060. goto yield_start_end;
  2061. }
  2062. }
  2063. } else {
  2064. yield_start_end:;
  2065. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, String::formatted("Cannot interpolate between '{}' and '{}'!", start_str, end_str), position);
  2066. // We can't really interpolate between the two, so just yield both.
  2067. values.append(make_ref_counted<StringValue>(move(start_str)));
  2068. values.append(make_ref_counted<StringValue>(move(end_str)));
  2069. }
  2070. return values;
  2071. }
  2072. warnln("Shell: Cannot apply the requested interpolation");
  2073. return values;
  2074. };
  2075. auto start_value = m_start->run(shell);
  2076. auto end_value = m_end->run(shell);
  2077. if (!start_value || !end_value)
  2078. return make_ref_counted<ListValue>({});
  2079. return make_ref_counted<ListValue>(interpolate(*start_value, *end_value, shell));
  2080. }
  2081. void Range::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2082. {
  2083. m_start->highlight_in_editor(editor, shell, metadata);
  2084. // Highlight the '..'
  2085. editor.stylize({ m_start->position().end_offset, m_end->position().start_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  2086. metadata.is_first_in_list = false;
  2087. m_end->highlight_in_editor(editor, shell, metadata);
  2088. }
  2089. HitTestResult Range::hit_test_position(size_t offset) const
  2090. {
  2091. auto result = m_start->hit_test_position(offset);
  2092. if (result.matching_node) {
  2093. if (!result.closest_command_node)
  2094. result.closest_command_node = m_start;
  2095. return result;
  2096. }
  2097. result = m_end->hit_test_position(offset);
  2098. if (!result.closest_command_node)
  2099. result.closest_command_node = m_end;
  2100. return result;
  2101. }
  2102. Range::Range(Position position, NonnullRefPtr<Node> start, NonnullRefPtr<Node> end)
  2103. : Node(move(position))
  2104. , m_start(move(start))
  2105. , m_end(move(end))
  2106. {
  2107. if (m_start->is_syntax_error())
  2108. set_is_syntax_error(m_start->syntax_error_node());
  2109. else if (m_end->is_syntax_error())
  2110. set_is_syntax_error(m_end->syntax_error_node());
  2111. }
  2112. Range::~Range()
  2113. {
  2114. }
  2115. void ReadRedirection::dump(int level) const
  2116. {
  2117. Node::dump(level);
  2118. m_path->dump(level + 1);
  2119. print_indented(String::formatted("To {}", m_fd), level + 1);
  2120. }
  2121. RefPtr<Value> ReadRedirection::run(RefPtr<Shell> shell)
  2122. {
  2123. Command command;
  2124. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2125. StringBuilder builder;
  2126. builder.join(" ", path_segments);
  2127. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Read));
  2128. return make_ref_counted<CommandValue>(move(command));
  2129. }
  2130. ReadRedirection::ReadRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2131. : PathRedirectionNode(move(position), fd, move(path))
  2132. {
  2133. }
  2134. ReadRedirection::~ReadRedirection()
  2135. {
  2136. }
  2137. void ReadWriteRedirection::dump(int level) const
  2138. {
  2139. Node::dump(level);
  2140. m_path->dump(level + 1);
  2141. print_indented(String::formatted("To/From {}", m_fd), level + 1);
  2142. }
  2143. RefPtr<Value> ReadWriteRedirection::run(RefPtr<Shell> shell)
  2144. {
  2145. Command command;
  2146. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2147. StringBuilder builder;
  2148. builder.join(" ", path_segments);
  2149. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::ReadWrite));
  2150. return make_ref_counted<CommandValue>(move(command));
  2151. }
  2152. ReadWriteRedirection::ReadWriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2153. : PathRedirectionNode(move(position), fd, move(path))
  2154. {
  2155. }
  2156. ReadWriteRedirection::~ReadWriteRedirection()
  2157. {
  2158. }
  2159. void Sequence::dump(int level) const
  2160. {
  2161. Node::dump(level);
  2162. for (auto& entry : m_entries)
  2163. entry.dump(level + 1);
  2164. }
  2165. RefPtr<Value> Sequence::run(RefPtr<Shell> shell)
  2166. {
  2167. Vector<Command> all_commands;
  2168. Command* last_command_in_sequence = nullptr;
  2169. for (auto& entry : m_entries) {
  2170. if (!last_command_in_sequence) {
  2171. auto commands = entry.to_lazy_evaluated_commands(shell);
  2172. all_commands.extend(move(commands));
  2173. last_command_in_sequence = &all_commands.last();
  2174. continue;
  2175. }
  2176. if (last_command_in_sequence->should_wait) {
  2177. last_command_in_sequence->next_chain.append(NodeWithAction { entry, NodeWithAction::Sequence });
  2178. } else {
  2179. all_commands.extend(entry.to_lazy_evaluated_commands(shell));
  2180. last_command_in_sequence = &all_commands.last();
  2181. }
  2182. }
  2183. return make_ref_counted<CommandSequenceValue>(move(all_commands));
  2184. }
  2185. void Sequence::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2186. {
  2187. for (auto& entry : m_entries)
  2188. entry.highlight_in_editor(editor, shell, metadata);
  2189. }
  2190. HitTestResult Sequence::hit_test_position(size_t offset) const
  2191. {
  2192. for (auto& entry : m_entries) {
  2193. auto result = entry.hit_test_position(offset);
  2194. if (result.matching_node) {
  2195. if (!result.closest_command_node)
  2196. result.closest_command_node = entry;
  2197. return result;
  2198. }
  2199. }
  2200. return {};
  2201. }
  2202. Sequence::Sequence(Position position, NonnullRefPtrVector<Node> entries, Vector<Position> separator_positions)
  2203. : Node(move(position))
  2204. , m_entries(move(entries))
  2205. , m_separator_positions(separator_positions)
  2206. {
  2207. for (auto& entry : m_entries) {
  2208. if (entry.is_syntax_error()) {
  2209. set_is_syntax_error(entry.syntax_error_node());
  2210. break;
  2211. }
  2212. }
  2213. }
  2214. Sequence::~Sequence()
  2215. {
  2216. }
  2217. void Subshell::dump(int level) const
  2218. {
  2219. Node::dump(level);
  2220. if (m_block)
  2221. m_block->dump(level + 1);
  2222. }
  2223. RefPtr<Value> Subshell::run(RefPtr<Shell> shell)
  2224. {
  2225. if (!m_block)
  2226. return make_ref_counted<ListValue>({});
  2227. return make_ref_counted<AST::CommandSequenceValue>(m_block->to_lazy_evaluated_commands(shell));
  2228. }
  2229. void Subshell::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2230. {
  2231. metadata.is_first_in_list = true;
  2232. if (m_block)
  2233. m_block->highlight_in_editor(editor, shell, metadata);
  2234. }
  2235. HitTestResult Subshell::hit_test_position(size_t offset) const
  2236. {
  2237. if (m_block)
  2238. return m_block->hit_test_position(offset);
  2239. return {};
  2240. }
  2241. Subshell::Subshell(Position position, RefPtr<Node> block)
  2242. : Node(move(position))
  2243. , m_block(block)
  2244. {
  2245. if (m_block && m_block->is_syntax_error())
  2246. set_is_syntax_error(m_block->syntax_error_node());
  2247. }
  2248. Subshell::~Subshell()
  2249. {
  2250. }
  2251. void Slice::dump(int level) const
  2252. {
  2253. Node::dump(level);
  2254. m_selector->dump(level + 1);
  2255. }
  2256. RefPtr<Value> Slice::run(RefPtr<Shell> shell)
  2257. {
  2258. return m_selector->run(shell);
  2259. }
  2260. void Slice::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2261. {
  2262. m_selector->highlight_in_editor(editor, shell, metadata);
  2263. }
  2264. HitTestResult Slice::hit_test_position(size_t offset) const
  2265. {
  2266. return m_selector->hit_test_position(offset);
  2267. }
  2268. Vector<Line::CompletionSuggestion> Slice::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  2269. {
  2270. // TODO: Maybe intercept this, and suggest values in range?
  2271. return m_selector->complete_for_editor(shell, offset, hit_test_result);
  2272. }
  2273. Slice::Slice(Position position, NonnullRefPtr<AST::Node> selector)
  2274. : Node(move(position))
  2275. , m_selector(move(selector))
  2276. {
  2277. if (m_selector->is_syntax_error())
  2278. set_is_syntax_error(m_selector->syntax_error_node());
  2279. }
  2280. Slice::~Slice()
  2281. {
  2282. }
  2283. void SimpleVariable::dump(int level) const
  2284. {
  2285. Node::dump(level);
  2286. print_indented("(Name)", level + 1);
  2287. print_indented(m_name, level + 2);
  2288. print_indented("(Slice)", level + 1);
  2289. if (m_slice)
  2290. m_slice->dump(level + 2);
  2291. else
  2292. print_indented("(None)", level + 2);
  2293. }
  2294. RefPtr<Value> SimpleVariable::run(RefPtr<Shell>)
  2295. {
  2296. NonnullRefPtr<Value> value = make_ref_counted<SimpleVariableValue>(m_name);
  2297. if (m_slice)
  2298. value = value->with_slices(*m_slice);
  2299. return value;
  2300. }
  2301. void SimpleVariable::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2302. {
  2303. Line::Style style { Line::Style::Foreground(214, 112, 214) };
  2304. if (metadata.is_first_in_list)
  2305. style.unify_with({ Line::Style::Bold });
  2306. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  2307. if (m_slice)
  2308. m_slice->highlight_in_editor(editor, shell, metadata);
  2309. }
  2310. HitTestResult SimpleVariable::hit_test_position(size_t offset) const
  2311. {
  2312. if (m_slice && m_slice->position().contains(offset))
  2313. return m_slice->hit_test_position(offset);
  2314. return { this, this, nullptr };
  2315. }
  2316. Vector<Line::CompletionSuggestion> SimpleVariable::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  2317. {
  2318. auto matching_node = hit_test_result.matching_node;
  2319. if (!matching_node)
  2320. return {};
  2321. if (matching_node != this)
  2322. return {};
  2323. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  2324. if (corrected_offset > m_name.length() + 1)
  2325. return {};
  2326. return shell.complete_variable(m_name, corrected_offset);
  2327. }
  2328. SimpleVariable::SimpleVariable(Position position, String name)
  2329. : VariableNode(move(position))
  2330. , m_name(move(name))
  2331. {
  2332. }
  2333. SimpleVariable::~SimpleVariable()
  2334. {
  2335. }
  2336. void SpecialVariable::dump(int level) const
  2337. {
  2338. Node::dump(level);
  2339. print_indented("(Name)", level + 1);
  2340. print_indented(String { &m_name, 1 }, level + 1);
  2341. print_indented("(Slice)", level + 1);
  2342. if (m_slice)
  2343. m_slice->dump(level + 2);
  2344. else
  2345. print_indented("(None)", level + 2);
  2346. }
  2347. RefPtr<Value> SpecialVariable::run(RefPtr<Shell>)
  2348. {
  2349. NonnullRefPtr<Value> value = make_ref_counted<SpecialVariableValue>(m_name);
  2350. if (m_slice)
  2351. value = value->with_slices(*m_slice);
  2352. return value;
  2353. }
  2354. void SpecialVariable::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2355. {
  2356. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(214, 112, 214) });
  2357. if (m_slice)
  2358. m_slice->highlight_in_editor(editor, shell, metadata);
  2359. }
  2360. Vector<Line::CompletionSuggestion> SpecialVariable::complete_for_editor(Shell&, size_t, const HitTestResult&)
  2361. {
  2362. return {};
  2363. }
  2364. HitTestResult SpecialVariable::hit_test_position(size_t offset) const
  2365. {
  2366. if (m_slice && m_slice->position().contains(offset))
  2367. return m_slice->hit_test_position(offset);
  2368. return { this, this, nullptr };
  2369. }
  2370. SpecialVariable::SpecialVariable(Position position, char name)
  2371. : VariableNode(move(position))
  2372. , m_name(name)
  2373. {
  2374. }
  2375. SpecialVariable::~SpecialVariable()
  2376. {
  2377. }
  2378. void Juxtaposition::dump(int level) const
  2379. {
  2380. Node::dump(level);
  2381. m_left->dump(level + 1);
  2382. m_right->dump(level + 1);
  2383. }
  2384. RefPtr<Value> Juxtaposition::run(RefPtr<Shell> shell)
  2385. {
  2386. auto left_value = m_left->run(shell)->resolve_without_cast(shell);
  2387. auto right_value = m_right->run(shell)->resolve_without_cast(shell);
  2388. auto left = left_value->resolve_as_list(shell);
  2389. auto right = right_value->resolve_as_list(shell);
  2390. if (left_value->is_string() && right_value->is_string()) {
  2391. VERIFY(left.size() == 1);
  2392. VERIFY(right.size() == 1);
  2393. StringBuilder builder;
  2394. builder.append(left[0]);
  2395. builder.append(right[0]);
  2396. return make_ref_counted<StringValue>(builder.to_string());
  2397. }
  2398. // Otherwise, treat them as lists and create a list product.
  2399. if (left.is_empty() || right.is_empty())
  2400. return make_ref_counted<ListValue>({});
  2401. Vector<String> result;
  2402. result.ensure_capacity(left.size() * right.size());
  2403. StringBuilder builder;
  2404. for (auto& left_element : left) {
  2405. for (auto& right_element : right) {
  2406. builder.append(left_element);
  2407. builder.append(right_element);
  2408. result.append(builder.to_string());
  2409. builder.clear();
  2410. }
  2411. }
  2412. return make_ref_counted<ListValue>(move(result));
  2413. }
  2414. void Juxtaposition::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2415. {
  2416. m_left->highlight_in_editor(editor, shell, metadata);
  2417. // '~/foo/bar' is special, we have to actually resolve the tilde
  2418. // since that resolution is a pure operation, we can just go ahead
  2419. // and do it to get the value :)
  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 bareword_value = m_right->run(shell)->resolve_as_list(shell)[0];
  2423. StringBuilder path_builder;
  2424. path_builder.append(tilde_value);
  2425. path_builder.append("/");
  2426. path_builder.append(bareword_value);
  2427. auto path = path_builder.to_string();
  2428. if (Core::File::exists(path)) {
  2429. auto realpath = shell.resolve_path(path);
  2430. auto url = URL::create_with_file_protocol(realpath);
  2431. url.set_host(shell.hostname);
  2432. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  2433. }
  2434. } else {
  2435. m_right->highlight_in_editor(editor, shell, metadata);
  2436. }
  2437. }
  2438. Vector<Line::CompletionSuggestion> Juxtaposition::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  2439. {
  2440. auto matching_node = hit_test_result.matching_node;
  2441. // '~/foo/bar' is special, we have to actually resolve the tilde
  2442. // then complete the bareword with that path prefix.
  2443. if (m_right->is_bareword() && m_left->is_tilde()) {
  2444. auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
  2445. auto corrected_offset = offset - matching_node->position().start_offset;
  2446. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  2447. if (corrected_offset > node->text().length())
  2448. return {};
  2449. auto text = node->text().substring(1, node->text().length() - 1);
  2450. return shell.complete_path(tilde_value, text, corrected_offset - 1, Shell::ExecutableOnly::No);
  2451. }
  2452. return Node::complete_for_editor(shell, offset, hit_test_result);
  2453. }
  2454. HitTestResult Juxtaposition::hit_test_position(size_t offset) const
  2455. {
  2456. auto result = m_left->hit_test_position(offset);
  2457. if (!result.closest_node_with_semantic_meaning)
  2458. result.closest_node_with_semantic_meaning = this;
  2459. if (result.matching_node)
  2460. return result;
  2461. result = m_right->hit_test_position(offset);
  2462. if (!result.closest_node_with_semantic_meaning)
  2463. result.closest_node_with_semantic_meaning = this;
  2464. return result;
  2465. }
  2466. Juxtaposition::Juxtaposition(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  2467. : Node(move(position))
  2468. , m_left(move(left))
  2469. , m_right(move(right))
  2470. {
  2471. if (m_left->is_syntax_error())
  2472. set_is_syntax_error(m_left->syntax_error_node());
  2473. else if (m_right->is_syntax_error())
  2474. set_is_syntax_error(m_right->syntax_error_node());
  2475. }
  2476. Juxtaposition::~Juxtaposition()
  2477. {
  2478. }
  2479. void StringLiteral::dump(int level) const
  2480. {
  2481. Node::dump(level);
  2482. print_indented(m_text, level + 1);
  2483. }
  2484. RefPtr<Value> StringLiteral::run(RefPtr<Shell>)
  2485. {
  2486. return make_ref_counted<StringValue>(m_text);
  2487. }
  2488. void StringLiteral::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  2489. {
  2490. if (m_text.is_empty())
  2491. return;
  2492. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  2493. if (metadata.is_first_in_list)
  2494. style.unify_with({ Line::Style::Bold });
  2495. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  2496. }
  2497. StringLiteral::StringLiteral(Position position, String text)
  2498. : Node(move(position))
  2499. , m_text(move(text))
  2500. {
  2501. }
  2502. StringLiteral::~StringLiteral()
  2503. {
  2504. }
  2505. void StringPartCompose::dump(int level) const
  2506. {
  2507. Node::dump(level);
  2508. m_left->dump(level + 1);
  2509. m_right->dump(level + 1);
  2510. }
  2511. RefPtr<Value> StringPartCompose::run(RefPtr<Shell> shell)
  2512. {
  2513. auto left = m_left->run(shell)->resolve_as_list(shell);
  2514. auto right = m_right->run(shell)->resolve_as_list(shell);
  2515. StringBuilder builder;
  2516. builder.join(" ", left);
  2517. builder.join(" ", right);
  2518. return make_ref_counted<StringValue>(builder.to_string());
  2519. }
  2520. void StringPartCompose::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2521. {
  2522. m_left->highlight_in_editor(editor, shell, metadata);
  2523. m_right->highlight_in_editor(editor, shell, metadata);
  2524. }
  2525. HitTestResult StringPartCompose::hit_test_position(size_t offset) const
  2526. {
  2527. auto result = m_left->hit_test_position(offset);
  2528. if (result.matching_node)
  2529. return result;
  2530. return m_right->hit_test_position(offset);
  2531. }
  2532. StringPartCompose::StringPartCompose(Position position, NonnullRefPtr<Node> left, NonnullRefPtr<Node> right)
  2533. : Node(move(position))
  2534. , m_left(move(left))
  2535. , m_right(move(right))
  2536. {
  2537. if (m_left->is_syntax_error())
  2538. set_is_syntax_error(m_left->syntax_error_node());
  2539. else if (m_right->is_syntax_error())
  2540. set_is_syntax_error(m_right->syntax_error_node());
  2541. }
  2542. StringPartCompose::~StringPartCompose()
  2543. {
  2544. }
  2545. void SyntaxError::dump(int level) const
  2546. {
  2547. Node::dump(level);
  2548. print_indented("(Error text)", level + 1);
  2549. print_indented(m_syntax_error_text, level + 2);
  2550. print_indented("(Can be recovered from)", level + 1);
  2551. print_indented(String::formatted("{}", m_is_continuable), level + 2);
  2552. }
  2553. RefPtr<Value> SyntaxError::run(RefPtr<Shell> shell)
  2554. {
  2555. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, m_syntax_error_text, position());
  2556. return make_ref_counted<StringValue>("");
  2557. }
  2558. void SyntaxError::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  2559. {
  2560. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Bold });
  2561. }
  2562. SyntaxError::SyntaxError(Position position, String error, bool is_continuable)
  2563. : Node(move(position))
  2564. , m_syntax_error_text(move(error))
  2565. , m_is_continuable(is_continuable)
  2566. {
  2567. }
  2568. const SyntaxError& SyntaxError::syntax_error_node() const
  2569. {
  2570. return *this;
  2571. }
  2572. SyntaxError::~SyntaxError()
  2573. {
  2574. }
  2575. void SyntheticNode::dump(int level) const
  2576. {
  2577. Node::dump(level);
  2578. }
  2579. RefPtr<Value> SyntheticNode::run(RefPtr<Shell>)
  2580. {
  2581. return m_value;
  2582. }
  2583. void SyntheticNode::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
  2584. {
  2585. }
  2586. SyntheticNode::SyntheticNode(Position position, NonnullRefPtr<Value> value)
  2587. : Node(move(position))
  2588. , m_value(move(value))
  2589. {
  2590. }
  2591. void Tilde::dump(int level) const
  2592. {
  2593. Node::dump(level);
  2594. print_indented(m_username, level + 1);
  2595. }
  2596. RefPtr<Value> Tilde::run(RefPtr<Shell>)
  2597. {
  2598. return make_ref_counted<TildeValue>(m_username);
  2599. }
  2600. void Tilde::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
  2601. {
  2602. }
  2603. HitTestResult Tilde::hit_test_position(size_t offset) const
  2604. {
  2605. if (!position().contains(offset))
  2606. return {};
  2607. return { this, this, nullptr };
  2608. }
  2609. Vector<Line::CompletionSuggestion> Tilde::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  2610. {
  2611. auto matching_node = hit_test_result.matching_node;
  2612. if (!matching_node)
  2613. return {};
  2614. if (matching_node != this)
  2615. return {};
  2616. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  2617. if (corrected_offset > m_username.length() + 1)
  2618. return {};
  2619. return shell.complete_user(m_username, corrected_offset);
  2620. }
  2621. String Tilde::text() const
  2622. {
  2623. StringBuilder builder;
  2624. builder.append('~');
  2625. builder.append(m_username);
  2626. return builder.to_string();
  2627. }
  2628. Tilde::Tilde(Position position, String username)
  2629. : Node(move(position))
  2630. , m_username(move(username))
  2631. {
  2632. }
  2633. Tilde::~Tilde()
  2634. {
  2635. }
  2636. void WriteAppendRedirection::dump(int level) const
  2637. {
  2638. Node::dump(level);
  2639. m_path->dump(level + 1);
  2640. print_indented(String::formatted("From {}", m_fd), level + 1);
  2641. }
  2642. RefPtr<Value> WriteAppendRedirection::run(RefPtr<Shell> shell)
  2643. {
  2644. Command command;
  2645. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2646. StringBuilder builder;
  2647. builder.join(" ", path_segments);
  2648. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::WriteAppend));
  2649. return make_ref_counted<CommandValue>(move(command));
  2650. }
  2651. WriteAppendRedirection::WriteAppendRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2652. : PathRedirectionNode(move(position), fd, move(path))
  2653. {
  2654. }
  2655. WriteAppendRedirection::~WriteAppendRedirection()
  2656. {
  2657. }
  2658. void WriteRedirection::dump(int level) const
  2659. {
  2660. Node::dump(level);
  2661. m_path->dump(level + 1);
  2662. print_indented(String::formatted("From {}", m_fd), level + 1);
  2663. }
  2664. RefPtr<Value> WriteRedirection::run(RefPtr<Shell> shell)
  2665. {
  2666. Command command;
  2667. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  2668. StringBuilder builder;
  2669. builder.join(" ", path_segments);
  2670. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Write));
  2671. return make_ref_counted<CommandValue>(move(command));
  2672. }
  2673. WriteRedirection::WriteRedirection(Position position, int fd, NonnullRefPtr<Node> path)
  2674. : PathRedirectionNode(move(position), fd, move(path))
  2675. {
  2676. }
  2677. WriteRedirection::~WriteRedirection()
  2678. {
  2679. }
  2680. void VariableDeclarations::dump(int level) const
  2681. {
  2682. Node::dump(level);
  2683. for (auto& var : m_variables) {
  2684. print_indented("Set", level + 1);
  2685. var.name->dump(level + 2);
  2686. var.value->dump(level + 2);
  2687. }
  2688. }
  2689. RefPtr<Value> VariableDeclarations::run(RefPtr<Shell> shell)
  2690. {
  2691. for (auto& var : m_variables) {
  2692. auto name_value = var.name->run(shell)->resolve_as_list(shell);
  2693. VERIFY(name_value.size() == 1);
  2694. auto name = name_value[0];
  2695. auto value = var.value->run(shell);
  2696. shell->set_local_variable(name, value.release_nonnull());
  2697. }
  2698. return make_ref_counted<ListValue>({});
  2699. }
  2700. void VariableDeclarations::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  2701. {
  2702. metadata.is_first_in_list = false;
  2703. for (auto& var : m_variables) {
  2704. var.name->highlight_in_editor(editor, shell, metadata);
  2705. // Highlight the '='.
  2706. editor.stylize({ var.name->position().end_offset - 1, var.name->position().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
  2707. var.value->highlight_in_editor(editor, shell, metadata);
  2708. }
  2709. }
  2710. HitTestResult VariableDeclarations::hit_test_position(size_t offset) const
  2711. {
  2712. for (auto decl : m_variables) {
  2713. auto result = decl.value->hit_test_position(offset);
  2714. if (result.matching_node)
  2715. return result;
  2716. }
  2717. return { nullptr, nullptr, nullptr };
  2718. }
  2719. VariableDeclarations::VariableDeclarations(Position position, Vector<Variable> variables)
  2720. : Node(move(position))
  2721. , m_variables(move(variables))
  2722. {
  2723. for (auto& decl : m_variables) {
  2724. if (decl.name->is_syntax_error()) {
  2725. set_is_syntax_error(decl.name->syntax_error_node());
  2726. break;
  2727. }
  2728. if (decl.value->is_syntax_error()) {
  2729. set_is_syntax_error(decl.value->syntax_error_node());
  2730. break;
  2731. }
  2732. }
  2733. }
  2734. VariableDeclarations::~VariableDeclarations()
  2735. {
  2736. }
  2737. Value::~Value()
  2738. {
  2739. }
  2740. Vector<AST::Command> Value::resolve_as_commands(RefPtr<Shell> shell)
  2741. {
  2742. Command command;
  2743. command.argv = resolve_as_list(shell);
  2744. return { command };
  2745. }
  2746. ListValue::ListValue(Vector<String> values)
  2747. {
  2748. if (values.is_empty())
  2749. return;
  2750. m_contained_values.ensure_capacity(values.size());
  2751. for (auto& str : values)
  2752. m_contained_values.append(adopt_ref(*new StringValue(move(str))));
  2753. }
  2754. NonnullRefPtr<Value> Value::with_slices(NonnullRefPtr<Slice> slice) const&
  2755. {
  2756. auto value = clone();
  2757. value->m_slices.append(move(slice));
  2758. return value;
  2759. }
  2760. NonnullRefPtr<Value> Value::with_slices(NonnullRefPtrVector<Slice> slices) const&
  2761. {
  2762. auto value = clone();
  2763. value->m_slices.extend(move(slices));
  2764. return value;
  2765. }
  2766. ListValue::~ListValue()
  2767. {
  2768. }
  2769. Vector<String> ListValue::resolve_as_list(RefPtr<Shell> shell)
  2770. {
  2771. Vector<String> values;
  2772. for (auto& value : m_contained_values)
  2773. values.extend(value.resolve_as_list(shell));
  2774. return resolve_slices(shell, move(values), m_slices);
  2775. }
  2776. NonnullRefPtr<Value> ListValue::resolve_without_cast(RefPtr<Shell> shell)
  2777. {
  2778. NonnullRefPtrVector<Value> values;
  2779. for (auto& value : m_contained_values)
  2780. values.append(value.resolve_without_cast(shell));
  2781. NonnullRefPtr<Value> value = make_ref_counted<ListValue>(move(values));
  2782. if (!m_slices.is_empty())
  2783. value = value->with_slices(m_slices);
  2784. return value;
  2785. }
  2786. CommandValue::~CommandValue()
  2787. {
  2788. }
  2789. CommandSequenceValue::~CommandSequenceValue()
  2790. {
  2791. }
  2792. Vector<String> CommandSequenceValue::resolve_as_list(RefPtr<Shell> shell)
  2793. {
  2794. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Unexpected cast of a command sequence to a list");
  2795. return {};
  2796. }
  2797. Vector<Command> CommandSequenceValue::resolve_as_commands(RefPtr<Shell>)
  2798. {
  2799. return m_contained_values;
  2800. }
  2801. Vector<String> CommandValue::resolve_as_list(RefPtr<Shell> shell)
  2802. {
  2803. shell->raise_error(Shell::ShellError::EvaluatedSyntaxError, "Unexpected cast of a command to a list");
  2804. return {};
  2805. }
  2806. Vector<Command> CommandValue::resolve_as_commands(RefPtr<Shell>)
  2807. {
  2808. return { m_command };
  2809. }
  2810. JobValue::~JobValue()
  2811. {
  2812. }
  2813. StringValue::~StringValue()
  2814. {
  2815. }
  2816. Vector<String> StringValue::resolve_as_list(RefPtr<Shell> shell)
  2817. {
  2818. if (is_list()) {
  2819. auto parts = StringView(m_string).split_view(m_split, m_keep_empty);
  2820. Vector<String> result;
  2821. result.ensure_capacity(parts.size());
  2822. for (auto& part : parts)
  2823. result.append(part);
  2824. return resolve_slices(shell, move(result), m_slices);
  2825. }
  2826. return { resolve_slices(shell, String { m_string }, m_slices) };
  2827. }
  2828. NonnullRefPtr<Value> StringValue::resolve_without_cast(RefPtr<Shell> shell)
  2829. {
  2830. if (is_list())
  2831. return make_ref_counted<AST::ListValue>(resolve_as_list(shell)); // No need to reapply the slices.
  2832. return *this;
  2833. }
  2834. GlobValue::~GlobValue()
  2835. {
  2836. }
  2837. Vector<String> GlobValue::resolve_as_list(RefPtr<Shell> shell)
  2838. {
  2839. if (!shell)
  2840. return { resolve_slices(shell, String { m_glob }, m_slices) };
  2841. auto results = shell->expand_globs(m_glob, shell->cwd);
  2842. if (results.is_empty())
  2843. shell->raise_error(Shell::ShellError::InvalidGlobError, "Glob did not match anything!", m_generation_position);
  2844. return resolve_slices(shell, move(results), m_slices);
  2845. }
  2846. SimpleVariableValue::~SimpleVariableValue()
  2847. {
  2848. }
  2849. Vector<String> SimpleVariableValue::resolve_as_list(RefPtr<Shell> shell)
  2850. {
  2851. if (!shell)
  2852. return resolve_slices(shell, Vector<String> {}, m_slices);
  2853. if (auto value = resolve_without_cast(shell); value != this)
  2854. return value->resolve_as_list(shell);
  2855. char* env_value = getenv(m_name.characters());
  2856. if (env_value == nullptr)
  2857. return { resolve_slices(shell, "", m_slices) };
  2858. return { resolve_slices(shell, String { env_value }, m_slices) };
  2859. }
  2860. NonnullRefPtr<Value> SimpleVariableValue::resolve_without_cast(RefPtr<Shell> shell)
  2861. {
  2862. VERIFY(shell);
  2863. if (auto value = shell->lookup_local_variable(m_name)) {
  2864. auto result = value.release_nonnull();
  2865. // If a slice is applied, add it.
  2866. if (!m_slices.is_empty())
  2867. result = result->with_slices(m_slices);
  2868. return result;
  2869. }
  2870. return *this;
  2871. }
  2872. SpecialVariableValue::~SpecialVariableValue()
  2873. {
  2874. }
  2875. Vector<String> SpecialVariableValue::resolve_as_list(RefPtr<Shell> shell)
  2876. {
  2877. if (!shell)
  2878. return {};
  2879. switch (m_name) {
  2880. case '?':
  2881. return { resolve_slices(shell, String::number(shell->last_return_code), m_slices) };
  2882. case '$':
  2883. return { resolve_slices(shell, String::number(getpid()), m_slices) };
  2884. case '*':
  2885. if (auto argv = shell->lookup_local_variable("ARGV"))
  2886. return resolve_slices(shell, argv->resolve_as_list(shell), m_slices);
  2887. return resolve_slices(shell, Vector<String> {}, m_slices);
  2888. case '#':
  2889. if (auto argv = shell->lookup_local_variable("ARGV")) {
  2890. if (argv->is_list()) {
  2891. auto list_argv = static_cast<AST::ListValue*>(argv.ptr());
  2892. return { resolve_slices(shell, String::number(list_argv->values().size()), m_slices) };
  2893. }
  2894. return { resolve_slices(shell, "1", m_slices) };
  2895. }
  2896. return { resolve_slices(shell, "0", m_slices) };
  2897. default:
  2898. return { resolve_slices(shell, "", m_slices) };
  2899. }
  2900. }
  2901. TildeValue::~TildeValue()
  2902. {
  2903. }
  2904. Vector<String> TildeValue::resolve_as_list(RefPtr<Shell> shell)
  2905. {
  2906. StringBuilder builder;
  2907. builder.append("~");
  2908. builder.append(m_username);
  2909. if (!shell)
  2910. return { resolve_slices(shell, builder.to_string(), m_slices) };
  2911. return { resolve_slices(shell, shell->expand_tilde(builder.to_string()), m_slices) };
  2912. }
  2913. Result<NonnullRefPtr<Rewiring>, String> CloseRedirection::apply() const
  2914. {
  2915. return adopt_ref(*new Rewiring(fd, fd, Rewiring::Close::ImmediatelyCloseNew));
  2916. }
  2917. CloseRedirection::~CloseRedirection()
  2918. {
  2919. }
  2920. Result<NonnullRefPtr<Rewiring>, String> PathRedirection::apply() const
  2921. {
  2922. auto check_fd_and_return = [my_fd = this->fd](int fd, const String& path) -> Result<NonnullRefPtr<Rewiring>, String> {
  2923. if (fd < 0) {
  2924. String error = strerror(errno);
  2925. dbgln("open() failed for '{}' with {}", path, error);
  2926. return error;
  2927. }
  2928. return adopt_ref(*new Rewiring(fd, my_fd, Rewiring::Close::Old));
  2929. };
  2930. switch (direction) {
  2931. case AST::PathRedirection::WriteAppend:
  2932. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666), path);
  2933. case AST::PathRedirection::Write:
  2934. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666), path);
  2935. case AST::PathRedirection::Read:
  2936. return check_fd_and_return(open(path.characters(), O_RDONLY), path);
  2937. case AST::PathRedirection::ReadWrite:
  2938. return check_fd_and_return(open(path.characters(), O_RDWR | O_CREAT, 0666), path);
  2939. }
  2940. VERIFY_NOT_REACHED();
  2941. }
  2942. PathRedirection::~PathRedirection()
  2943. {
  2944. }
  2945. FdRedirection::~FdRedirection()
  2946. {
  2947. }
  2948. Redirection::~Redirection()
  2949. {
  2950. }
  2951. }