AST.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "AST.h"
  27. #include "Shell.h"
  28. #include <AK/MemoryStream.h>
  29. #include <AK/ScopeGuard.h>
  30. #include <AK/String.h>
  31. #include <AK/StringBuilder.h>
  32. #include <AK/URL.h>
  33. #include <LibCore/EventLoop.h>
  34. #include <LibCore/File.h>
  35. #include <signal.h>
  36. //#define EXECUTE_DEBUG
  37. namespace AST {
  38. template<typename T, typename... Args>
  39. static inline NonnullRefPtr<T> create(Args... args)
  40. {
  41. return adopt(*new T(args...));
  42. }
  43. template<typename T>
  44. static inline NonnullRefPtr<T> create(std::initializer_list<NonnullRefPtr<Value>> arg)
  45. {
  46. return adopt(*new T(arg));
  47. }
  48. static inline void print_indented(const String& str, int indent)
  49. {
  50. for (auto i = 0; i < indent; ++i)
  51. dbgprintf(" ");
  52. dbgprintf("%s\n", str.characters());
  53. }
  54. static inline Vector<Command> join_commands(Vector<Command> left, Vector<Command> right)
  55. {
  56. Command command;
  57. auto last_in_left = left.take_last();
  58. auto first_in_right = right.take_first();
  59. command.argv.append(last_in_left.argv);
  60. command.argv.append(first_in_right.argv);
  61. command.redirections.append(last_in_left.redirections);
  62. command.redirections.append(first_in_right.redirections);
  63. command.should_wait = first_in_right.should_wait && last_in_left.should_wait;
  64. command.is_pipe_source = first_in_right.is_pipe_source;
  65. command.should_notify_if_in_background = first_in_right.should_notify_if_in_background || last_in_left.should_notify_if_in_background;
  66. Vector<Command> commands;
  67. commands.append(left);
  68. commands.append(command);
  69. commands.append(right);
  70. return commands;
  71. }
  72. void Node::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(RefPtr<Value>)> callback)
  73. {
  74. auto value = run(shell)->resolve_without_cast(shell);
  75. if (value->is_job()) {
  76. callback(value);
  77. return;
  78. }
  79. if (value->is_list_without_resolution()) {
  80. auto list = value->resolve_without_cast(shell);
  81. for (auto& element : static_cast<ListValue*>(list.ptr())->values()) {
  82. if (callback(element) == IterationDecision::Break)
  83. break;
  84. }
  85. return;
  86. }
  87. auto list = value->resolve_as_list(shell);
  88. for (auto& element : list) {
  89. if (callback(create<StringValue>(move(element))) == IterationDecision::Break)
  90. break;
  91. }
  92. }
  93. Vector<Command> Node::to_lazy_evaluated_commands(RefPtr<Shell> shell)
  94. {
  95. if (would_execute()) {
  96. // Wrap the node in a "should immediately execute next" command.
  97. return {
  98. Command { {}, {}, true, false, true, true, {}, { NodeWithAction(*this, NodeWithAction::Sequence) } }
  99. };
  100. }
  101. return run(shell)->resolve_as_commands(shell);
  102. }
  103. void Node::dump(int level) const
  104. {
  105. print_indented(String::format("%s at %d:%d", class_name().characters(), m_position.start_offset, m_position.end_offset), level);
  106. }
  107. Node::Node(Position position)
  108. : m_position(position)
  109. {
  110. }
  111. Vector<Line::CompletionSuggestion> Node::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  112. {
  113. auto matching_node = hit_test_result.matching_node;
  114. if (matching_node) {
  115. if (matching_node->is_bareword()) {
  116. auto corrected_offset = offset - matching_node->position().start_offset;
  117. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  118. if (corrected_offset > node->text().length())
  119. return {};
  120. auto& text = node->text();
  121. // If the literal isn't an option, treat it as a path.
  122. if (!(text.starts_with("-") || text == "--" || text == "-"))
  123. return shell.complete_path("", text, corrected_offset);
  124. // If the literal is an option, we have to know the program name
  125. // should we have no way to get that, bail early.
  126. if (!hit_test_result.closest_command_node)
  127. return {};
  128. auto program_name_node = hit_test_result.closest_command_node->leftmost_trivial_literal();
  129. if (!program_name_node)
  130. return {};
  131. String program_name;
  132. if (program_name_node->is_bareword())
  133. program_name = static_cast<BarewordLiteral*>(program_name_node.ptr())->text();
  134. else
  135. program_name = static_cast<StringLiteral*>(program_name_node.ptr())->text();
  136. return shell.complete_option(program_name, text, corrected_offset);
  137. }
  138. return {};
  139. }
  140. auto result = hit_test_position(offset);
  141. if (!result.matching_node)
  142. return {};
  143. auto node = result.matching_node;
  144. if (node->is_bareword() || node != result.closest_node_with_semantic_meaning)
  145. node = result.closest_node_with_semantic_meaning;
  146. if (!node)
  147. return {};
  148. return node->complete_for_editor(shell, offset, result);
  149. }
  150. Vector<Line::CompletionSuggestion> Node::complete_for_editor(Shell& shell, size_t offset)
  151. {
  152. return Node::complete_for_editor(shell, offset, { nullptr, nullptr, nullptr });
  153. }
  154. Node::~Node()
  155. {
  156. }
  157. void And::dump(int level) const
  158. {
  159. Node::dump(level);
  160. m_left->dump(level + 1);
  161. m_right->dump(level + 1);
  162. }
  163. RefPtr<Value> And::run(RefPtr<Shell> shell)
  164. {
  165. auto commands = m_left->to_lazy_evaluated_commands(shell);
  166. commands.last().next_chain.append(NodeWithAction { *m_right, NodeWithAction::And });
  167. return create<CommandSequenceValue>(move(commands));
  168. }
  169. void And::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  170. {
  171. metadata.is_first_in_list = true;
  172. m_left->highlight_in_editor(editor, shell, metadata);
  173. m_right->highlight_in_editor(editor, shell, metadata);
  174. }
  175. HitTestResult And::hit_test_position(size_t offset)
  176. {
  177. if (!position().contains(offset))
  178. return {};
  179. auto result = m_left->hit_test_position(offset);
  180. if (result.matching_node) {
  181. if (!result.closest_command_node)
  182. result.closest_command_node = m_right;
  183. return result;
  184. }
  185. result = m_right->hit_test_position(offset);
  186. if (!result.closest_command_node)
  187. result.closest_command_node = m_right;
  188. return result;
  189. }
  190. And::And(Position position, RefPtr<Node> left, RefPtr<Node> right)
  191. : Node(move(position))
  192. , m_left(move(left))
  193. , m_right(move(right))
  194. {
  195. if (m_left->is_syntax_error())
  196. set_is_syntax_error(m_left->syntax_error_node());
  197. else if (m_right->is_syntax_error())
  198. set_is_syntax_error(m_right->syntax_error_node());
  199. }
  200. And::~And()
  201. {
  202. }
  203. void ListConcatenate::dump(int level) const
  204. {
  205. Node::dump(level);
  206. for (auto& element : m_list)
  207. element->dump(level + 1);
  208. }
  209. RefPtr<Value> ListConcatenate::run(RefPtr<Shell> shell)
  210. {
  211. RefPtr<Value> result = nullptr;
  212. for (auto& element : m_list) {
  213. if (!result) {
  214. result = create<ListValue>({ element->run(shell)->resolve_without_cast(shell) });
  215. continue;
  216. }
  217. auto element_value = element->run(shell)->resolve_without_cast(shell);
  218. if (result->is_command() || element_value->is_command()) {
  219. auto joined_commands = join_commands(result->resolve_as_commands(shell), element_value->resolve_as_commands(shell));
  220. if (joined_commands.size() == 1)
  221. result = create<CommandValue>(joined_commands[0]);
  222. else
  223. result = create<CommandSequenceValue>(move(joined_commands));
  224. } else {
  225. NonnullRefPtrVector<Value> values;
  226. if (result->is_list_without_resolution()) {
  227. values.append(static_cast<ListValue*>(result.ptr())->values());
  228. } else {
  229. for (auto& result : result->resolve_as_list(shell))
  230. values.append(create<StringValue>(result));
  231. }
  232. values.append(element_value);
  233. result = create<ListValue>(move(values));
  234. }
  235. }
  236. if (!result)
  237. return create<ListValue>({});
  238. return result;
  239. }
  240. void ListConcatenate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  241. {
  242. auto first = metadata.is_first_in_list;
  243. metadata.is_first_in_list = false;
  244. metadata.is_first_in_list = first;
  245. for (auto& element : m_list) {
  246. element->highlight_in_editor(editor, shell, metadata);
  247. metadata.is_first_in_list = false;
  248. }
  249. }
  250. HitTestResult ListConcatenate::hit_test_position(size_t offset)
  251. {
  252. if (!position().contains(offset))
  253. return {};
  254. bool first = true;
  255. for (auto& element : m_list) {
  256. auto result = element->hit_test_position(offset);
  257. if (!result.closest_node_with_semantic_meaning && !first)
  258. result.closest_node_with_semantic_meaning = this;
  259. if (result.matching_node)
  260. return result;
  261. first = false;
  262. }
  263. return {};
  264. }
  265. RefPtr<Node> ListConcatenate::leftmost_trivial_literal() const
  266. {
  267. if (m_list.is_empty())
  268. return nullptr;
  269. return m_list.first()->leftmost_trivial_literal();
  270. }
  271. ListConcatenate::ListConcatenate(Position position, Vector<RefPtr<Node>> list)
  272. : Node(move(position))
  273. , m_list(move(list))
  274. {
  275. for (auto& element : m_list) {
  276. if (element->is_syntax_error()) {
  277. set_is_syntax_error(element->syntax_error_node());
  278. break;
  279. }
  280. }
  281. }
  282. ListConcatenate::~ListConcatenate()
  283. {
  284. }
  285. void Background::dump(int level) const
  286. {
  287. Node::dump(level);
  288. m_command->dump(level + 1);
  289. }
  290. RefPtr<Value> Background::run(RefPtr<Shell> shell)
  291. {
  292. // FIXME: Currently this does not work correctly if `m_command.would_execute()',
  293. // as it runs the node, which means nodes likes And and Or will evaluate
  294. // all but their last subnode before yielding to this, causing a command
  295. // like `foo && bar&` to effectively be `foo && (bar&)`.
  296. auto commands = m_command->to_lazy_evaluated_commands(shell);
  297. for (auto& command : commands)
  298. command.should_wait = false;
  299. return create<CommandSequenceValue>(move(commands));
  300. }
  301. void Background::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  302. {
  303. m_command->highlight_in_editor(editor, shell, metadata);
  304. }
  305. HitTestResult Background::hit_test_position(size_t offset)
  306. {
  307. if (!position().contains(offset))
  308. return {};
  309. return m_command->hit_test_position(offset);
  310. }
  311. Background::Background(Position position, RefPtr<Node> command)
  312. : Node(move(position))
  313. , m_command(move(command))
  314. {
  315. if (m_command->is_syntax_error())
  316. set_is_syntax_error(m_command->syntax_error_node());
  317. }
  318. Background::~Background()
  319. {
  320. }
  321. void BarewordLiteral::dump(int level) const
  322. {
  323. Node::dump(level);
  324. print_indented(m_text, level + 1);
  325. }
  326. RefPtr<Value> BarewordLiteral::run(RefPtr<Shell>)
  327. {
  328. return create<StringValue>(m_text);
  329. }
  330. void BarewordLiteral::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  331. {
  332. if (metadata.is_first_in_list) {
  333. if (shell.is_runnable(m_text)) {
  334. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Bold });
  335. } else {
  336. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red) });
  337. }
  338. return;
  339. }
  340. if (m_text.starts_with('-')) {
  341. if (m_text == "--") {
  342. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  343. return;
  344. }
  345. if (m_text == "-")
  346. return;
  347. if (m_text.starts_with("--")) {
  348. auto index = m_text.index_of("=").value_or(m_text.length() - 1) + 1;
  349. editor.stylize({ m_position.start_offset, m_position.start_offset + index }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  350. } else {
  351. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  352. }
  353. }
  354. if (Core::File::exists(m_text)) {
  355. auto realpath = shell.resolve_path(m_text);
  356. auto url = URL::create_with_file_protocol(realpath);
  357. url.set_host(shell.hostname);
  358. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  359. }
  360. }
  361. BarewordLiteral::BarewordLiteral(Position position, String text)
  362. : Node(move(position))
  363. , m_text(move(text))
  364. {
  365. }
  366. BarewordLiteral::~BarewordLiteral()
  367. {
  368. }
  369. void CastToCommand::dump(int level) const
  370. {
  371. Node::dump(level);
  372. m_inner->dump(level + 1);
  373. }
  374. RefPtr<Value> CastToCommand::run(RefPtr<Shell> shell)
  375. {
  376. if (m_inner->is_command())
  377. return m_inner->run(shell);
  378. auto value = m_inner->run(shell)->resolve_without_cast(shell);
  379. if (value->is_command())
  380. return value;
  381. auto argv = value->resolve_as_list(shell);
  382. return create<CommandValue>(move(argv));
  383. }
  384. void CastToCommand::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  385. {
  386. m_inner->highlight_in_editor(editor, shell, metadata);
  387. }
  388. HitTestResult CastToCommand::hit_test_position(size_t offset)
  389. {
  390. if (!position().contains(offset))
  391. return {};
  392. auto result = m_inner->hit_test_position(offset);
  393. if (!result.closest_node_with_semantic_meaning)
  394. result.closest_node_with_semantic_meaning = this;
  395. return result;
  396. }
  397. Vector<Line::CompletionSuggestion> CastToCommand::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  398. {
  399. auto matching_node = hit_test_result.matching_node;
  400. if (!matching_node || !matching_node->is_bareword())
  401. return {};
  402. auto corrected_offset = offset - matching_node->position().start_offset;
  403. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  404. if (corrected_offset > node->text().length())
  405. return {};
  406. return shell.complete_program_name(node->text(), corrected_offset);
  407. }
  408. RefPtr<Node> CastToCommand::leftmost_trivial_literal() const
  409. {
  410. return m_inner->leftmost_trivial_literal();
  411. }
  412. CastToCommand::CastToCommand(Position position, RefPtr<Node> inner)
  413. : Node(move(position))
  414. , m_inner(move(inner))
  415. {
  416. if (m_inner->is_syntax_error())
  417. set_is_syntax_error(m_inner->syntax_error_node());
  418. }
  419. CastToCommand::~CastToCommand()
  420. {
  421. }
  422. void CastToList::dump(int level) const
  423. {
  424. Node::dump(level);
  425. if (m_inner)
  426. m_inner->dump(level + 1);
  427. else
  428. print_indented("(empty)", level + 1);
  429. }
  430. RefPtr<Value> CastToList::run(RefPtr<Shell> shell)
  431. {
  432. if (!m_inner)
  433. return create<ListValue>({});
  434. auto inner_value = m_inner->run(shell)->resolve_without_cast(shell);
  435. if (inner_value->is_command() || inner_value->is_list())
  436. return inner_value;
  437. auto values = inner_value->resolve_as_list(shell);
  438. NonnullRefPtrVector<Value> cast_values;
  439. for (auto& value : values)
  440. cast_values.append(create<StringValue>(value));
  441. return create<ListValue>(cast_values);
  442. }
  443. void CastToList::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  444. {
  445. if (m_inner)
  446. m_inner->highlight_in_editor(editor, shell, metadata);
  447. }
  448. HitTestResult CastToList::hit_test_position(size_t offset)
  449. {
  450. if (!position().contains(offset))
  451. return {};
  452. if (!m_inner)
  453. return {};
  454. return m_inner->hit_test_position(offset);
  455. }
  456. RefPtr<Node> CastToList::leftmost_trivial_literal() const
  457. {
  458. return m_inner->leftmost_trivial_literal();
  459. }
  460. CastToList::CastToList(Position position, RefPtr<Node> inner)
  461. : Node(move(position))
  462. , m_inner(move(inner))
  463. {
  464. if (m_inner && m_inner->is_syntax_error())
  465. set_is_syntax_error(m_inner->syntax_error_node());
  466. }
  467. CastToList::~CastToList()
  468. {
  469. }
  470. void CloseFdRedirection::dump(int level) const
  471. {
  472. Node::dump(level);
  473. print_indented(String::format("%d -> Close", m_fd), level);
  474. }
  475. RefPtr<Value> CloseFdRedirection::run(RefPtr<Shell>)
  476. {
  477. Command command;
  478. command.redirections.append(adopt(*new CloseRedirection(m_fd)));
  479. return create<CommandValue>(move(command));
  480. }
  481. void CloseFdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  482. {
  483. editor.stylize({ m_position.start_offset, m_position.end_offset - 1 }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  484. editor.stylize({ m_position.end_offset - 1, m_position.end_offset }, { Line::Style::Foreground(0xff, 0x7e, 0x00) }); // Amber
  485. }
  486. CloseFdRedirection::CloseFdRedirection(Position position, int fd)
  487. : Node(move(position))
  488. , m_fd(fd)
  489. {
  490. }
  491. CloseFdRedirection::~CloseFdRedirection()
  492. {
  493. }
  494. void CommandLiteral::dump(int level) const
  495. {
  496. Node::dump(level);
  497. print_indented("(Generated command literal)", level + 1);
  498. }
  499. RefPtr<Value> CommandLiteral::run(RefPtr<Shell>)
  500. {
  501. return create<CommandValue>(m_command);
  502. }
  503. CommandLiteral::CommandLiteral(Position position, Command command)
  504. : Node(move(position))
  505. , m_command(move(command))
  506. {
  507. }
  508. CommandLiteral::~CommandLiteral()
  509. {
  510. }
  511. void Comment::dump(int level) const
  512. {
  513. Node::dump(level);
  514. print_indented(m_text, level + 1);
  515. }
  516. RefPtr<Value> Comment::run(RefPtr<Shell>)
  517. {
  518. return create<ListValue>({});
  519. }
  520. void Comment::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  521. {
  522. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(150, 150, 150) }); // Light gray
  523. }
  524. Comment::Comment(Position position, String text)
  525. : Node(move(position))
  526. , m_text(move(text))
  527. {
  528. }
  529. Comment::~Comment()
  530. {
  531. }
  532. void DoubleQuotedString::dump(int level) const
  533. {
  534. Node::dump(level);
  535. m_inner->dump(level + 1);
  536. }
  537. RefPtr<Value> DoubleQuotedString::run(RefPtr<Shell> shell)
  538. {
  539. StringBuilder builder;
  540. auto values = m_inner->run(shell)->resolve_as_list(shell);
  541. builder.join("", values);
  542. return create<StringValue>(builder.to_string());
  543. }
  544. void DoubleQuotedString::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  545. {
  546. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  547. if (metadata.is_first_in_list)
  548. style.unify_with({ Line::Style::Bold });
  549. editor.stylize({ m_position.start_offset, m_position.end_offset }, style);
  550. metadata.is_first_in_list = false;
  551. m_inner->highlight_in_editor(editor, shell, metadata);
  552. }
  553. HitTestResult DoubleQuotedString::hit_test_position(size_t offset)
  554. {
  555. if (!position().contains(offset))
  556. return {};
  557. return m_inner->hit_test_position(offset);
  558. }
  559. DoubleQuotedString::DoubleQuotedString(Position position, RefPtr<Node> inner)
  560. : Node(move(position))
  561. , m_inner(move(inner))
  562. {
  563. if (m_inner->is_syntax_error())
  564. set_is_syntax_error(m_inner->syntax_error_node());
  565. }
  566. DoubleQuotedString::~DoubleQuotedString()
  567. {
  568. }
  569. void DynamicEvaluate::dump(int level) const
  570. {
  571. Node::dump(level);
  572. m_inner->dump(level + 1);
  573. }
  574. RefPtr<Value> DynamicEvaluate::run(RefPtr<Shell> shell)
  575. {
  576. auto result = m_inner->run(shell)->resolve_without_cast(shell);
  577. // Dynamic Evaluation behaves differently between strings and lists.
  578. // Strings are treated as variables, and Lists are treated as commands.
  579. if (result->is_string()) {
  580. auto name_part = result->resolve_as_list(shell);
  581. ASSERT(name_part.size() == 1);
  582. return create<SimpleVariableValue>(name_part[0]);
  583. }
  584. // If it's anything else, we're just gonna cast it to a list.
  585. auto list = result->resolve_as_list(shell);
  586. return create<CommandValue>(move(list));
  587. }
  588. void DynamicEvaluate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  589. {
  590. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  591. m_inner->highlight_in_editor(editor, shell, metadata);
  592. }
  593. HitTestResult DynamicEvaluate::hit_test_position(size_t offset)
  594. {
  595. if (!position().contains(offset))
  596. return {};
  597. return m_inner->hit_test_position(offset);
  598. }
  599. DynamicEvaluate::DynamicEvaluate(Position position, RefPtr<Node> inner)
  600. : Node(move(position))
  601. , m_inner(move(inner))
  602. {
  603. if (m_inner->is_syntax_error())
  604. set_is_syntax_error(m_inner->syntax_error_node());
  605. }
  606. DynamicEvaluate::~DynamicEvaluate()
  607. {
  608. }
  609. void Fd2FdRedirection::dump(int level) const
  610. {
  611. Node::dump(level);
  612. print_indented(String::format("%d -> %d", source_fd, dest_fd), level);
  613. }
  614. RefPtr<Value> Fd2FdRedirection::run(RefPtr<Shell>)
  615. {
  616. Command command;
  617. command.redirections.append(FdRedirection::create(source_fd, dest_fd, Rewiring::Close::None));
  618. return create<CommandValue>(move(command));
  619. }
  620. void Fd2FdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  621. {
  622. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  623. }
  624. Fd2FdRedirection::Fd2FdRedirection(Position position, int src, int dst)
  625. : Node(move(position))
  626. , source_fd(src)
  627. , dest_fd(dst)
  628. {
  629. }
  630. Fd2FdRedirection::~Fd2FdRedirection()
  631. {
  632. }
  633. void ForLoop::dump(int level) const
  634. {
  635. Node::dump(level);
  636. print_indented(String::format("%s in\n", m_variable_name.characters()), level + 1);
  637. m_iterated_expression->dump(level + 2);
  638. print_indented("Running", level + 1);
  639. if (m_block)
  640. m_block->dump(level + 2);
  641. else
  642. print_indented("(null)", level + 2);
  643. }
  644. RefPtr<Value> ForLoop::run(RefPtr<Shell> shell)
  645. {
  646. if (!m_block)
  647. return create<ListValue>({});
  648. size_t consecutive_interruptions = 0;
  649. m_iterated_expression->for_each_entry(shell, [&](auto value) {
  650. if (consecutive_interruptions == 2)
  651. return IterationDecision::Break;
  652. RefPtr<Value> block_value;
  653. {
  654. auto frame = shell->push_frame();
  655. shell->set_local_variable(m_variable_name, value);
  656. block_value = m_block->run(shell);
  657. }
  658. if (block_value->is_job()) {
  659. auto job = static_cast<JobValue*>(block_value.ptr())->job();
  660. if (!job || job->is_running_in_background())
  661. return IterationDecision::Continue;
  662. shell->block_on_job(job);
  663. if (job->signaled()) {
  664. if (job->termination_signal() == SIGINT)
  665. ++consecutive_interruptions;
  666. else
  667. return IterationDecision::Break;
  668. } else {
  669. consecutive_interruptions = 0;
  670. }
  671. }
  672. return IterationDecision::Continue;
  673. });
  674. return create<ListValue>({});
  675. }
  676. void ForLoop::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  677. {
  678. editor.stylize({ m_position.start_offset, m_position.start_offset + 3 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  679. if (m_in_kw_position.has_value())
  680. editor.stylize({ m_in_kw_position.value(), m_in_kw_position.value() + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  681. metadata.is_first_in_list = false;
  682. m_iterated_expression->highlight_in_editor(editor, shell, metadata);
  683. metadata.is_first_in_list = true;
  684. if (m_block)
  685. m_block->highlight_in_editor(editor, shell, metadata);
  686. }
  687. HitTestResult ForLoop::hit_test_position(size_t offset)
  688. {
  689. if (!position().contains(offset))
  690. return {};
  691. if (auto result = m_iterated_expression->hit_test_position(offset); result.matching_node)
  692. return result;
  693. return m_block->hit_test_position(offset);
  694. }
  695. ForLoop::ForLoop(Position position, String variable_name, RefPtr<AST::Node> iterated_expr, RefPtr<AST::Node> block, Optional<size_t> in_kw_position)
  696. : Node(move(position))
  697. , m_variable_name(move(variable_name))
  698. , m_iterated_expression(move(iterated_expr))
  699. , m_block(move(block))
  700. , m_in_kw_position(move(in_kw_position))
  701. {
  702. if (m_iterated_expression->is_syntax_error())
  703. set_is_syntax_error(m_iterated_expression->syntax_error_node());
  704. else if (m_block && m_block->is_syntax_error())
  705. set_is_syntax_error(m_block->syntax_error_node());
  706. }
  707. ForLoop::~ForLoop()
  708. {
  709. }
  710. void Glob::dump(int level) const
  711. {
  712. Node::dump(level);
  713. print_indented(m_text, level + 1);
  714. }
  715. RefPtr<Value> Glob::run(RefPtr<Shell>)
  716. {
  717. return create<GlobValue>(m_text);
  718. }
  719. void Glob::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  720. {
  721. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Cyan) };
  722. if (metadata.is_first_in_list)
  723. style.unify_with({ Line::Style::Bold });
  724. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  725. }
  726. Glob::Glob(Position position, String text)
  727. : Node(move(position))
  728. , m_text(move(text))
  729. {
  730. }
  731. Glob::~Glob()
  732. {
  733. }
  734. void Execute::dump(int level) const
  735. {
  736. Node::dump(level);
  737. if (m_capture_stdout)
  738. print_indented("(Capturing stdout)", level + 1);
  739. m_command->dump(level + 1);
  740. }
  741. void Execute::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(RefPtr<Value>)> callback)
  742. {
  743. if (m_command->would_execute())
  744. return m_command->for_each_entry(shell, move(callback));
  745. auto commands = shell->expand_aliases(m_command->run(shell)->resolve_as_commands(shell));
  746. if (m_capture_stdout) {
  747. int pipefd[2];
  748. int rc = pipe(pipefd);
  749. if (rc < 0) {
  750. dbg() << "Error: cannot pipe(): " << strerror(errno);
  751. return;
  752. }
  753. auto& last_in_commands = commands.last();
  754. last_in_commands.redirections.prepend(FdRedirection::create(STDOUT_FILENO, pipefd[1], Rewiring::Close::Destination));
  755. last_in_commands.should_wait = false;
  756. last_in_commands.should_notify_if_in_background = false;
  757. last_in_commands.is_pipe_source = false;
  758. Core::EventLoop loop;
  759. auto notifier = Core::Notifier::construct(pipefd[0], Core::Notifier::Read);
  760. DuplexMemoryStream stream;
  761. enum {
  762. Continue,
  763. Break,
  764. NothingLeft,
  765. };
  766. auto check_and_call = [&] {
  767. auto ifs = shell->local_variable_or("IFS", "\n");
  768. if (auto offset = stream.offset_of(ifs.bytes()); offset.has_value()) {
  769. auto line_end = offset.value();
  770. if (line_end == 0) {
  771. auto rc = stream.discard_or_error(ifs.length());
  772. ASSERT(rc);
  773. if (shell->options.inline_exec_keep_empty_segments)
  774. if (callback(create<StringValue>("")) == IterationDecision::Break) {
  775. loop.quit(Break);
  776. notifier->set_enabled(false);
  777. return Break;
  778. }
  779. } else {
  780. auto entry = ByteBuffer::create_uninitialized(line_end + ifs.length());
  781. auto rc = stream.read_or_error(entry);
  782. ASSERT(rc);
  783. auto str = StringView(entry.data(), entry.size() - ifs.length());
  784. if (callback(create<StringValue>(str)) == IterationDecision::Break) {
  785. loop.quit(Break);
  786. notifier->set_enabled(false);
  787. return Break;
  788. }
  789. }
  790. return Continue;
  791. }
  792. return NothingLeft;
  793. };
  794. notifier->on_ready_to_read = [&] {
  795. constexpr static auto buffer_size = 16;
  796. u8 buffer[buffer_size];
  797. size_t remaining_size = buffer_size;
  798. for (;;) {
  799. notifier->set_event_mask(Core::Notifier::None);
  800. bool should_enable_notifier = false;
  801. ScopeGuard notifier_enabler { [&] {
  802. if (should_enable_notifier)
  803. notifier->set_event_mask(Core::Notifier::Read);
  804. } };
  805. if (check_and_call() == Break)
  806. return;
  807. auto read_size = read(pipefd[0], buffer, remaining_size);
  808. if (read_size < 0) {
  809. int saved_errno = errno;
  810. if (saved_errno == EINTR) {
  811. should_enable_notifier = true;
  812. continue;
  813. }
  814. if (saved_errno == 0)
  815. continue;
  816. dbg() << "read() failed: " << strerror(saved_errno);
  817. break;
  818. }
  819. if (read_size == 0)
  820. break;
  821. should_enable_notifier = true;
  822. stream.write({ buffer, (size_t)read_size });
  823. }
  824. loop.quit(Break);
  825. };
  826. shell->run_commands(commands);
  827. loop.exec();
  828. notifier->on_ready_to_read = nullptr;
  829. if (close(pipefd[0]) < 0) {
  830. dbg() << "close() failed: " << strerror(errno);
  831. }
  832. if (!stream.eof()) {
  833. auto action = Continue;
  834. do {
  835. action = check_and_call();
  836. if (action == Break)
  837. return;
  838. } while (action == Continue);
  839. if (!stream.eof()) {
  840. auto entry = ByteBuffer::create_uninitialized(stream.remaining());
  841. auto rc = stream.read_or_error(entry);
  842. ASSERT(rc);
  843. callback(create<StringValue>(String::copy(entry)));
  844. }
  845. }
  846. return;
  847. }
  848. auto jobs = shell->run_commands(commands);
  849. if (!jobs.is_empty())
  850. callback(create<JobValue>(&jobs.last()));
  851. }
  852. RefPtr<Value> Execute::run(RefPtr<Shell> shell)
  853. {
  854. if (m_command->would_execute())
  855. return m_command->run(shell);
  856. NonnullRefPtrVector<Value> values;
  857. for_each_entry(shell, [&](auto value) {
  858. values.append(*value);
  859. return IterationDecision::Continue;
  860. });
  861. if (values.size() == 1 && values.first().is_job())
  862. return values.first();
  863. return create<ListValue>(move(values));
  864. }
  865. void Execute::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  866. {
  867. if (m_capture_stdout)
  868. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  869. metadata.is_first_in_list = true;
  870. m_command->highlight_in_editor(editor, shell, metadata);
  871. }
  872. HitTestResult Execute::hit_test_position(size_t offset)
  873. {
  874. if (!position().contains(offset))
  875. return {};
  876. auto result = m_command->hit_test_position(offset);
  877. if (!result.closest_node_with_semantic_meaning)
  878. result.closest_node_with_semantic_meaning = this;
  879. if (!result.closest_command_node)
  880. result.closest_command_node = m_command;
  881. return result;
  882. }
  883. Vector<Line::CompletionSuggestion> Execute::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  884. {
  885. auto matching_node = hit_test_result.matching_node;
  886. if (!matching_node || !matching_node->is_bareword())
  887. return {};
  888. auto corrected_offset = offset - matching_node->position().start_offset;
  889. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  890. if (corrected_offset > node->text().length())
  891. return {};
  892. return shell.complete_program_name(node->text(), corrected_offset);
  893. }
  894. Execute::Execute(Position position, RefPtr<Node> command, bool capture_stdout)
  895. : Node(move(position))
  896. , m_command(move(command))
  897. , m_capture_stdout(capture_stdout)
  898. {
  899. if (m_command->is_syntax_error())
  900. set_is_syntax_error(m_command->syntax_error_node());
  901. }
  902. Execute::~Execute()
  903. {
  904. }
  905. void IfCond::dump(int level) const
  906. {
  907. Node::dump(level);
  908. print_indented("Condition", ++level);
  909. m_condition->dump(level + 1);
  910. print_indented("True Branch", level);
  911. if (m_true_branch)
  912. m_true_branch->dump(level + 1);
  913. else
  914. print_indented("(empty)", level + 1);
  915. print_indented("False Branch", level);
  916. if (m_false_branch)
  917. m_false_branch->dump(level + 1);
  918. else
  919. print_indented("(empty)", level + 1);
  920. }
  921. RefPtr<Value> IfCond::run(RefPtr<Shell> shell)
  922. {
  923. auto cond = m_condition->run(shell)->resolve_without_cast(shell);
  924. ASSERT(cond->is_job());
  925. auto cond_job_value = static_cast<const JobValue*>(cond.ptr());
  926. auto cond_job = cond_job_value->job();
  927. shell->block_on_job(cond_job);
  928. if (cond_job->signaled())
  929. return create<ListValue>({}); // Exit early.
  930. if (shell->last_return_code == 0) {
  931. if (m_true_branch)
  932. return m_true_branch->run(shell);
  933. } else {
  934. if (m_false_branch)
  935. return m_false_branch->run(shell);
  936. }
  937. return create<ListValue>({});
  938. }
  939. void IfCond::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  940. {
  941. metadata.is_first_in_list = true;
  942. editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  943. if (m_else_position.has_value())
  944. editor.stylize({ m_else_position.value().start_offset, m_else_position.value().start_offset + 4 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  945. m_condition->highlight_in_editor(editor, shell, metadata);
  946. if (m_true_branch)
  947. m_true_branch->highlight_in_editor(editor, shell, metadata);
  948. if (m_false_branch)
  949. m_false_branch->highlight_in_editor(editor, shell, metadata);
  950. }
  951. HitTestResult IfCond::hit_test_position(size_t offset)
  952. {
  953. if (!position().contains(offset))
  954. return {};
  955. if (auto result = m_condition->hit_test_position(offset); result.matching_node)
  956. return result;
  957. if (m_true_branch) {
  958. if (auto result = m_true_branch->hit_test_position(offset); result.matching_node)
  959. return result;
  960. }
  961. if (m_false_branch) {
  962. if (auto result = m_false_branch->hit_test_position(offset); result.matching_node)
  963. return result;
  964. }
  965. return {};
  966. }
  967. IfCond::IfCond(Position position, Optional<Position> else_position, RefPtr<Node> condition, RefPtr<Node> true_branch, RefPtr<Node> false_branch)
  968. : Node(move(position))
  969. , m_condition(move(condition))
  970. , m_true_branch(move(true_branch))
  971. , m_false_branch(move(false_branch))
  972. , m_else_position(move(else_position))
  973. {
  974. if (m_condition->is_syntax_error())
  975. set_is_syntax_error(m_condition->syntax_error_node());
  976. else if (m_true_branch && m_true_branch->is_syntax_error())
  977. set_is_syntax_error(m_true_branch->syntax_error_node());
  978. else if (m_false_branch && m_false_branch->is_syntax_error())
  979. set_is_syntax_error(m_false_branch->syntax_error_node());
  980. m_condition = create<AST::Execute>(m_condition->position(), m_condition);
  981. if (m_true_branch)
  982. m_true_branch = create<AST::Execute>(m_true_branch->position(), m_true_branch);
  983. if (m_false_branch)
  984. m_false_branch = create<AST::Execute>(m_false_branch->position(), m_false_branch);
  985. }
  986. IfCond::~IfCond()
  987. {
  988. }
  989. void Join::dump(int level) const
  990. {
  991. Node::dump(level);
  992. m_left->dump(level + 1);
  993. m_right->dump(level + 1);
  994. }
  995. RefPtr<Value> Join::run(RefPtr<Shell> shell)
  996. {
  997. auto left = m_left->to_lazy_evaluated_commands(shell);
  998. auto right = m_right->to_lazy_evaluated_commands(shell);
  999. return create<CommandSequenceValue>(join_commands(move(left), move(right)));
  1000. }
  1001. void Join::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1002. {
  1003. m_left->highlight_in_editor(editor, shell, metadata);
  1004. if (m_left->is_list() || m_left->is_command())
  1005. metadata.is_first_in_list = false;
  1006. m_right->highlight_in_editor(editor, shell, metadata);
  1007. }
  1008. HitTestResult Join::hit_test_position(size_t offset)
  1009. {
  1010. if (!position().contains(offset))
  1011. return {};
  1012. auto result = m_left->hit_test_position(offset);
  1013. if (result.matching_node)
  1014. return result;
  1015. return m_right->hit_test_position(offset);
  1016. }
  1017. RefPtr<Node> Join::leftmost_trivial_literal() const
  1018. {
  1019. if (auto value = m_left->leftmost_trivial_literal())
  1020. return value;
  1021. return m_right->leftmost_trivial_literal();
  1022. }
  1023. Join::Join(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1024. : Node(move(position))
  1025. , m_left(move(left))
  1026. , m_right(move(right))
  1027. {
  1028. if (m_left->is_syntax_error())
  1029. set_is_syntax_error(m_left->syntax_error_node());
  1030. else if (m_right->is_syntax_error())
  1031. set_is_syntax_error(m_right->syntax_error_node());
  1032. }
  1033. Join::~Join()
  1034. {
  1035. }
  1036. void Or::dump(int level) const
  1037. {
  1038. Node::dump(level);
  1039. m_left->dump(level + 1);
  1040. m_right->dump(level + 1);
  1041. }
  1042. RefPtr<Value> Or::run(RefPtr<Shell> shell)
  1043. {
  1044. auto commands = m_left->to_lazy_evaluated_commands(shell);
  1045. commands.last().next_chain.empend(*m_right, NodeWithAction::Or);
  1046. return create<CommandSequenceValue>(move(commands));
  1047. }
  1048. void Or::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1049. {
  1050. m_left->highlight_in_editor(editor, shell, metadata);
  1051. m_right->highlight_in_editor(editor, shell, metadata);
  1052. }
  1053. HitTestResult Or::hit_test_position(size_t offset)
  1054. {
  1055. if (!position().contains(offset))
  1056. return {};
  1057. auto result = m_left->hit_test_position(offset);
  1058. if (result.matching_node) {
  1059. if (!result.closest_command_node)
  1060. result.closest_command_node = m_right;
  1061. return result;
  1062. }
  1063. result = m_right->hit_test_position(offset);
  1064. if (!result.closest_command_node)
  1065. result.closest_command_node = m_right;
  1066. return result;
  1067. }
  1068. Or::Or(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1069. : Node(move(position))
  1070. , m_left(move(left))
  1071. , m_right(move(right))
  1072. {
  1073. if (m_left->is_syntax_error())
  1074. set_is_syntax_error(m_left->syntax_error_node());
  1075. else if (m_right->is_syntax_error())
  1076. set_is_syntax_error(m_right->syntax_error_node());
  1077. }
  1078. Or::~Or()
  1079. {
  1080. }
  1081. void Pipe::dump(int level) const
  1082. {
  1083. Node::dump(level);
  1084. m_left->dump(level + 1);
  1085. m_right->dump(level + 1);
  1086. }
  1087. RefPtr<Value> Pipe::run(RefPtr<Shell> shell)
  1088. {
  1089. auto left = m_left->to_lazy_evaluated_commands(shell);
  1090. auto right = m_right->to_lazy_evaluated_commands(shell);
  1091. auto last_in_left = left.take_last();
  1092. auto first_in_right = right.take_first();
  1093. auto pipe_read_end = FdRedirection::create(STDIN_FILENO, -1, Rewiring::Close::Destination);
  1094. auto pipe_write_end = FdRedirection::create(STDOUT_FILENO, -1, pipe_read_end, Rewiring::Close::RefreshDestination);
  1095. first_in_right.redirections.append(pipe_read_end);
  1096. last_in_left.redirections.append(pipe_write_end);
  1097. last_in_left.should_wait = false;
  1098. last_in_left.is_pipe_source = true;
  1099. if (first_in_right.pipeline) {
  1100. last_in_left.pipeline = first_in_right.pipeline;
  1101. } else {
  1102. auto pipeline = adopt(*new Pipeline);
  1103. last_in_left.pipeline = pipeline;
  1104. first_in_right.pipeline = pipeline;
  1105. }
  1106. Vector<Command> commands;
  1107. commands.append(left);
  1108. commands.append(last_in_left);
  1109. commands.append(first_in_right);
  1110. commands.append(right);
  1111. return create<CommandSequenceValue>(move(commands));
  1112. }
  1113. void Pipe::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1114. {
  1115. m_left->highlight_in_editor(editor, shell, metadata);
  1116. m_right->highlight_in_editor(editor, shell, metadata);
  1117. }
  1118. HitTestResult Pipe::hit_test_position(size_t offset)
  1119. {
  1120. if (!position().contains(offset))
  1121. return {};
  1122. auto result = m_left->hit_test_position(offset);
  1123. if (result.matching_node)
  1124. return result;
  1125. return m_right->hit_test_position(offset);
  1126. }
  1127. Pipe::Pipe(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1128. : Node(move(position))
  1129. , m_left(move(left))
  1130. , m_right(move(right))
  1131. {
  1132. if (m_left->is_syntax_error())
  1133. set_is_syntax_error(m_left->syntax_error_node());
  1134. else if (m_right->is_syntax_error())
  1135. set_is_syntax_error(m_right->syntax_error_node());
  1136. }
  1137. Pipe::~Pipe()
  1138. {
  1139. }
  1140. PathRedirectionNode::PathRedirectionNode(Position position, int fd, RefPtr<Node> path)
  1141. : Node(move(position))
  1142. , m_fd(fd)
  1143. , m_path(move(path))
  1144. {
  1145. }
  1146. void PathRedirectionNode::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1147. {
  1148. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  1149. metadata.is_first_in_list = false;
  1150. m_path->highlight_in_editor(editor, shell, metadata);
  1151. if (m_path->is_bareword()) {
  1152. auto path_text = m_path->run(nullptr)->resolve_as_list(nullptr);
  1153. ASSERT(path_text.size() == 1);
  1154. // Apply a URL to the path.
  1155. auto& position = m_path->position();
  1156. auto& path = path_text[0];
  1157. if (!path.starts_with('/'))
  1158. path = String::format("%s/%s", shell.cwd.characters(), path.characters());
  1159. auto url = URL::create_with_file_protocol(path);
  1160. url.set_host(shell.hostname);
  1161. editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  1162. }
  1163. }
  1164. HitTestResult PathRedirectionNode::hit_test_position(size_t offset)
  1165. {
  1166. if (!position().contains(offset))
  1167. return {};
  1168. auto result = m_path->hit_test_position(offset);
  1169. if (!result.closest_node_with_semantic_meaning)
  1170. result.closest_node_with_semantic_meaning = this;
  1171. return result;
  1172. }
  1173. Vector<Line::CompletionSuggestion> PathRedirectionNode::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1174. {
  1175. auto matching_node = hit_test_result.matching_node;
  1176. if (!matching_node || !matching_node->is_bareword())
  1177. return {};
  1178. auto corrected_offset = offset - matching_node->position().start_offset;
  1179. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  1180. if (corrected_offset > node->text().length())
  1181. return {};
  1182. return shell.complete_path("", node->text(), corrected_offset);
  1183. }
  1184. PathRedirectionNode::~PathRedirectionNode()
  1185. {
  1186. }
  1187. void ReadRedirection::dump(int level) const
  1188. {
  1189. Node::dump(level);
  1190. m_path->dump(level + 1);
  1191. print_indented(String::format("To %d", m_fd), level + 1);
  1192. }
  1193. RefPtr<Value> ReadRedirection::run(RefPtr<Shell> shell)
  1194. {
  1195. Command command;
  1196. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1197. StringBuilder builder;
  1198. builder.join(" ", path_segments);
  1199. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Read));
  1200. return create<CommandValue>(move(command));
  1201. }
  1202. ReadRedirection::ReadRedirection(Position position, int fd, RefPtr<Node> path)
  1203. : PathRedirectionNode(move(position), fd, move(path))
  1204. {
  1205. }
  1206. ReadRedirection::~ReadRedirection()
  1207. {
  1208. }
  1209. void ReadWriteRedirection::dump(int level) const
  1210. {
  1211. Node::dump(level);
  1212. m_path->dump(level + 1);
  1213. print_indented(String::format("To/From %d", m_fd), level + 1);
  1214. }
  1215. RefPtr<Value> ReadWriteRedirection::run(RefPtr<Shell> shell)
  1216. {
  1217. Command command;
  1218. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1219. StringBuilder builder;
  1220. builder.join(" ", path_segments);
  1221. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::ReadWrite));
  1222. return create<CommandValue>(move(command));
  1223. }
  1224. ReadWriteRedirection::ReadWriteRedirection(Position position, int fd, RefPtr<Node> path)
  1225. : PathRedirectionNode(move(position), fd, move(path))
  1226. {
  1227. }
  1228. ReadWriteRedirection::~ReadWriteRedirection()
  1229. {
  1230. }
  1231. void Sequence::dump(int level) const
  1232. {
  1233. Node::dump(level);
  1234. m_left->dump(level + 1);
  1235. m_right->dump(level + 1);
  1236. }
  1237. RefPtr<Value> Sequence::run(RefPtr<Shell> shell)
  1238. {
  1239. // If we are to return a job, block on the left one then return the right one.
  1240. if (would_execute()) {
  1241. RefPtr<AST::Node> execute_node = create<AST::Execute>(m_left->position(), m_left);
  1242. auto left_value = execute_node->run(shell);
  1243. // Some nodes are inherently empty, such as Comments and For loops without bodies,
  1244. // it is not an error for the value not to be a job.
  1245. if (left_value && left_value->is_job())
  1246. shell->block_on_job(static_cast<JobValue*>(left_value.ptr())->job());
  1247. if (m_right->would_execute())
  1248. return m_right->run(shell);
  1249. execute_node = create<AST::Execute>(m_right->position(), m_right);
  1250. return execute_node->run(shell);
  1251. }
  1252. auto left = m_left->to_lazy_evaluated_commands(shell);
  1253. // This could happen if a comment is next to a command.
  1254. if (left.size() == 1) {
  1255. auto& command = left.first();
  1256. if (command.argv.is_empty() && command.redirections.is_empty())
  1257. return m_right->run(shell);
  1258. }
  1259. if (left.last().should_wait)
  1260. left.last().next_chain.append(NodeWithAction { *m_right, NodeWithAction::Sequence });
  1261. else
  1262. left.append(m_right->to_lazy_evaluated_commands(shell));
  1263. return create<CommandSequenceValue>(move(left));
  1264. }
  1265. void Sequence::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1266. {
  1267. m_left->highlight_in_editor(editor, shell, metadata);
  1268. m_right->highlight_in_editor(editor, shell, metadata);
  1269. }
  1270. HitTestResult Sequence::hit_test_position(size_t offset)
  1271. {
  1272. if (!position().contains(offset))
  1273. return {};
  1274. auto result = m_left->hit_test_position(offset);
  1275. if (result.matching_node)
  1276. return result;
  1277. return m_right->hit_test_position(offset);
  1278. }
  1279. Sequence::Sequence(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1280. : Node(move(position))
  1281. , m_left(move(left))
  1282. , m_right(move(right))
  1283. {
  1284. if (m_left->is_syntax_error())
  1285. set_is_syntax_error(m_left->syntax_error_node());
  1286. else if (m_right->is_syntax_error())
  1287. set_is_syntax_error(m_right->syntax_error_node());
  1288. }
  1289. Sequence::~Sequence()
  1290. {
  1291. }
  1292. void SimpleVariable::dump(int level) const
  1293. {
  1294. Node::dump(level);
  1295. print_indented(m_name, level + 1);
  1296. }
  1297. RefPtr<Value> SimpleVariable::run(RefPtr<Shell>)
  1298. {
  1299. return create<SimpleVariableValue>(m_name);
  1300. }
  1301. void SimpleVariable::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  1302. {
  1303. Line::Style style { Line::Style::Foreground(214, 112, 214) };
  1304. if (metadata.is_first_in_list)
  1305. style.unify_with({ Line::Style::Bold });
  1306. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  1307. }
  1308. HitTestResult SimpleVariable::hit_test_position(size_t offset)
  1309. {
  1310. if (!position().contains(offset))
  1311. return {};
  1312. return { this, this, nullptr };
  1313. }
  1314. Vector<Line::CompletionSuggestion> SimpleVariable::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1315. {
  1316. auto matching_node = hit_test_result.matching_node;
  1317. if (!matching_node)
  1318. return {};
  1319. if (matching_node != this)
  1320. return {};
  1321. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  1322. if (corrected_offset > m_name.length() + 1)
  1323. return {};
  1324. return shell.complete_variable(m_name, corrected_offset);
  1325. }
  1326. SimpleVariable::SimpleVariable(Position position, String name)
  1327. : Node(move(position))
  1328. , m_name(move(name))
  1329. {
  1330. }
  1331. SimpleVariable::~SimpleVariable()
  1332. {
  1333. }
  1334. void SpecialVariable::dump(int level) const
  1335. {
  1336. Node::dump(level);
  1337. print_indented(String { &m_name, 1 }, level + 1);
  1338. }
  1339. RefPtr<Value> SpecialVariable::run(RefPtr<Shell>)
  1340. {
  1341. return create<SpecialVariableValue>(m_name);
  1342. }
  1343. void SpecialVariable::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  1344. {
  1345. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(214, 112, 214) });
  1346. }
  1347. Vector<Line::CompletionSuggestion> SpecialVariable::complete_for_editor(Shell&, size_t, const HitTestResult&)
  1348. {
  1349. return {};
  1350. }
  1351. HitTestResult SpecialVariable::hit_test_position(size_t offset)
  1352. {
  1353. if (!position().contains(offset))
  1354. return {};
  1355. return { this, this, nullptr };
  1356. }
  1357. SpecialVariable::SpecialVariable(Position position, char name)
  1358. : Node(move(position))
  1359. , m_name(name)
  1360. {
  1361. }
  1362. SpecialVariable::~SpecialVariable()
  1363. {
  1364. }
  1365. void Juxtaposition::dump(int level) const
  1366. {
  1367. Node::dump(level);
  1368. m_left->dump(level + 1);
  1369. m_right->dump(level + 1);
  1370. }
  1371. RefPtr<Value> Juxtaposition::run(RefPtr<Shell> shell)
  1372. {
  1373. auto left_value = m_left->run(shell)->resolve_without_cast(shell);
  1374. auto right_value = m_right->run(shell)->resolve_without_cast(shell);
  1375. auto left = left_value->resolve_as_list(shell);
  1376. auto right = right_value->resolve_as_list(shell);
  1377. if (left_value->is_string() && right_value->is_string()) {
  1378. ASSERT(left.size() == 1);
  1379. ASSERT(right.size() == 1);
  1380. StringBuilder builder;
  1381. builder.append(left[0]);
  1382. builder.append(right[0]);
  1383. return create<StringValue>(builder.to_string());
  1384. }
  1385. // Otherwise, treat them as lists and create a list product.
  1386. if (left.is_empty() || right.is_empty())
  1387. return create<ListValue>({});
  1388. Vector<String> result;
  1389. result.ensure_capacity(left.size() * right.size());
  1390. StringBuilder builder;
  1391. for (auto& left_element : left) {
  1392. for (auto& right_element : right) {
  1393. builder.append(left_element);
  1394. builder.append(right_element);
  1395. result.append(builder.to_string());
  1396. builder.clear();
  1397. }
  1398. }
  1399. return create<ListValue>(move(result));
  1400. }
  1401. void Juxtaposition::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1402. {
  1403. m_left->highlight_in_editor(editor, shell, metadata);
  1404. // '~/foo/bar' is special, we have to actually resolve the tilde
  1405. // since that resolution is a pure operation, we can just go ahead
  1406. // and do it to get the value :)
  1407. if (m_right->is_bareword() && m_left->is_tilde()) {
  1408. auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
  1409. auto bareword_value = m_right->run(shell)->resolve_as_list(shell)[0];
  1410. StringBuilder path_builder;
  1411. path_builder.append(tilde_value);
  1412. path_builder.append("/");
  1413. path_builder.append(bareword_value);
  1414. auto path = path_builder.to_string();
  1415. if (Core::File::exists(path)) {
  1416. auto realpath = shell.resolve_path(path);
  1417. auto url = URL::create_with_file_protocol(realpath);
  1418. url.set_host(shell.hostname);
  1419. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  1420. }
  1421. } else {
  1422. m_right->highlight_in_editor(editor, shell, metadata);
  1423. }
  1424. }
  1425. Vector<Line::CompletionSuggestion> Juxtaposition::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1426. {
  1427. auto matching_node = hit_test_result.matching_node;
  1428. // '~/foo/bar' is special, we have to actually resolve the tilde
  1429. // then complete the bareword with that path prefix.
  1430. if (m_right->is_bareword() && m_left->is_tilde()) {
  1431. auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
  1432. auto corrected_offset = offset - matching_node->position().start_offset;
  1433. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  1434. if (corrected_offset > node->text().length())
  1435. return {};
  1436. auto text = node->text().substring(1, node->text().length() - 1);
  1437. return shell.complete_path(tilde_value, text, corrected_offset - 1);
  1438. }
  1439. return Node::complete_for_editor(shell, offset, hit_test_result);
  1440. }
  1441. HitTestResult Juxtaposition::hit_test_position(size_t offset)
  1442. {
  1443. if (!position().contains(offset))
  1444. return {};
  1445. auto result = m_left->hit_test_position(offset);
  1446. if (!result.closest_node_with_semantic_meaning)
  1447. result.closest_node_with_semantic_meaning = this;
  1448. if (result.matching_node)
  1449. return result;
  1450. result = m_right->hit_test_position(offset);
  1451. if (!result.closest_node_with_semantic_meaning)
  1452. result.closest_node_with_semantic_meaning = this;
  1453. return result;
  1454. }
  1455. Juxtaposition::Juxtaposition(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1456. : Node(move(position))
  1457. , m_left(move(left))
  1458. , m_right(move(right))
  1459. {
  1460. if (m_left->is_syntax_error())
  1461. set_is_syntax_error(m_left->syntax_error_node());
  1462. else if (m_right->is_syntax_error())
  1463. set_is_syntax_error(m_right->syntax_error_node());
  1464. }
  1465. Juxtaposition::~Juxtaposition()
  1466. {
  1467. }
  1468. void StringLiteral::dump(int level) const
  1469. {
  1470. Node::dump(level);
  1471. print_indented(m_text, level + 1);
  1472. }
  1473. RefPtr<Value> StringLiteral::run(RefPtr<Shell>)
  1474. {
  1475. return create<StringValue>(m_text);
  1476. }
  1477. void StringLiteral::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  1478. {
  1479. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  1480. if (metadata.is_first_in_list)
  1481. style.unify_with({ Line::Style::Bold });
  1482. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  1483. }
  1484. StringLiteral::StringLiteral(Position position, String text)
  1485. : Node(move(position))
  1486. , m_text(move(text))
  1487. {
  1488. }
  1489. StringLiteral::~StringLiteral()
  1490. {
  1491. }
  1492. void StringPartCompose::dump(int level) const
  1493. {
  1494. Node::dump(level);
  1495. m_left->dump(level + 1);
  1496. m_right->dump(level + 1);
  1497. }
  1498. RefPtr<Value> StringPartCompose::run(RefPtr<Shell> shell)
  1499. {
  1500. auto left = m_left->run(shell)->resolve_as_list(shell);
  1501. auto right = m_right->run(shell)->resolve_as_list(shell);
  1502. StringBuilder builder;
  1503. builder.join(" ", left);
  1504. builder.join(" ", right);
  1505. return create<StringValue>(builder.to_string());
  1506. }
  1507. void StringPartCompose::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1508. {
  1509. m_left->highlight_in_editor(editor, shell, metadata);
  1510. m_right->highlight_in_editor(editor, shell, metadata);
  1511. }
  1512. HitTestResult StringPartCompose::hit_test_position(size_t offset)
  1513. {
  1514. if (!position().contains(offset))
  1515. return {};
  1516. auto result = m_left->hit_test_position(offset);
  1517. if (result.matching_node)
  1518. return result;
  1519. return m_right->hit_test_position(offset);
  1520. }
  1521. StringPartCompose::StringPartCompose(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1522. : Node(move(position))
  1523. , m_left(move(left))
  1524. , m_right(move(right))
  1525. {
  1526. if (m_left->is_syntax_error())
  1527. set_is_syntax_error(m_left->syntax_error_node());
  1528. else if (m_right->is_syntax_error())
  1529. set_is_syntax_error(m_right->syntax_error_node());
  1530. }
  1531. StringPartCompose::~StringPartCompose()
  1532. {
  1533. }
  1534. void SyntaxError::dump(int level) const
  1535. {
  1536. Node::dump(level);
  1537. }
  1538. RefPtr<Value> SyntaxError::run(RefPtr<Shell>)
  1539. {
  1540. dbg() << "SYNTAX ERROR AAAA";
  1541. return create<StringValue>("");
  1542. }
  1543. void SyntaxError::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  1544. {
  1545. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Bold });
  1546. }
  1547. SyntaxError::SyntaxError(Position position, String error)
  1548. : Node(move(position))
  1549. , m_syntax_error_text(move(error))
  1550. {
  1551. m_is_syntax_error = true;
  1552. }
  1553. const SyntaxError& SyntaxError::syntax_error_node() const
  1554. {
  1555. return *this;
  1556. }
  1557. SyntaxError::~SyntaxError()
  1558. {
  1559. }
  1560. void Tilde::dump(int level) const
  1561. {
  1562. Node::dump(level);
  1563. print_indented(m_username, level + 1);
  1564. }
  1565. RefPtr<Value> Tilde::run(RefPtr<Shell>)
  1566. {
  1567. return create<TildeValue>(m_username);
  1568. }
  1569. void Tilde::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
  1570. {
  1571. }
  1572. HitTestResult Tilde::hit_test_position(size_t offset)
  1573. {
  1574. if (!position().contains(offset))
  1575. return {};
  1576. return { this, this, nullptr };
  1577. }
  1578. Vector<Line::CompletionSuggestion> Tilde::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1579. {
  1580. auto matching_node = hit_test_result.matching_node;
  1581. if (!matching_node)
  1582. return {};
  1583. if (matching_node != this)
  1584. return {};
  1585. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  1586. if (corrected_offset > m_username.length() + 1)
  1587. return {};
  1588. return shell.complete_user(m_username, corrected_offset);
  1589. }
  1590. String Tilde::text() const
  1591. {
  1592. StringBuilder builder;
  1593. builder.append('~');
  1594. builder.append(m_username);
  1595. return builder.to_string();
  1596. }
  1597. Tilde::Tilde(Position position, String username)
  1598. : Node(move(position))
  1599. , m_username(move(username))
  1600. {
  1601. }
  1602. Tilde::~Tilde()
  1603. {
  1604. }
  1605. void WriteAppendRedirection::dump(int level) const
  1606. {
  1607. Node::dump(level);
  1608. m_path->dump(level + 1);
  1609. print_indented(String::format("From %d", m_fd), level + 1);
  1610. }
  1611. RefPtr<Value> WriteAppendRedirection::run(RefPtr<Shell> shell)
  1612. {
  1613. Command command;
  1614. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1615. StringBuilder builder;
  1616. builder.join(" ", path_segments);
  1617. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::WriteAppend));
  1618. return create<CommandValue>(move(command));
  1619. }
  1620. WriteAppendRedirection::WriteAppendRedirection(Position position, int fd, RefPtr<Node> path)
  1621. : PathRedirectionNode(move(position), fd, move(path))
  1622. {
  1623. }
  1624. WriteAppendRedirection::~WriteAppendRedirection()
  1625. {
  1626. }
  1627. void WriteRedirection::dump(int level) const
  1628. {
  1629. Node::dump(level);
  1630. m_path->dump(level + 1);
  1631. print_indented(String::format("From %d", m_fd), level + 1);
  1632. }
  1633. RefPtr<Value> WriteRedirection::run(RefPtr<Shell> shell)
  1634. {
  1635. Command command;
  1636. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1637. StringBuilder builder;
  1638. builder.join(" ", path_segments);
  1639. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Write));
  1640. return create<CommandValue>(move(command));
  1641. }
  1642. WriteRedirection::WriteRedirection(Position position, int fd, RefPtr<Node> path)
  1643. : PathRedirectionNode(move(position), fd, move(path))
  1644. {
  1645. }
  1646. WriteRedirection::~WriteRedirection()
  1647. {
  1648. }
  1649. void VariableDeclarations::dump(int level) const
  1650. {
  1651. Node::dump(level);
  1652. for (auto& var : m_variables) {
  1653. print_indented("Set", level + 1);
  1654. var.name->dump(level + 2);
  1655. var.value->dump(level + 2);
  1656. }
  1657. }
  1658. RefPtr<Value> VariableDeclarations::run(RefPtr<Shell> shell)
  1659. {
  1660. for (auto& var : m_variables) {
  1661. auto name_value = var.name->run(shell)->resolve_as_list(shell);
  1662. ASSERT(name_value.size() == 1);
  1663. auto name = name_value[0];
  1664. auto value = var.value->run(shell);
  1665. if (value->is_list()) {
  1666. auto parts = value->resolve_as_list(shell);
  1667. shell->set_local_variable(name, adopt(*new ListValue(move(parts))));
  1668. } else if (value->is_command()) {
  1669. shell->set_local_variable(name, value);
  1670. } else {
  1671. auto part = value->resolve_as_list(shell);
  1672. shell->set_local_variable(name, adopt(*new StringValue(part[0])));
  1673. }
  1674. }
  1675. return create<ListValue>({});
  1676. }
  1677. void VariableDeclarations::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1678. {
  1679. metadata.is_first_in_list = false;
  1680. for (auto& var : m_variables) {
  1681. var.name->highlight_in_editor(editor, shell, metadata);
  1682. // Highlight the '='.
  1683. editor.stylize({ var.name->position().end_offset - 1, var.name->position().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
  1684. var.value->highlight_in_editor(editor, shell, metadata);
  1685. }
  1686. }
  1687. HitTestResult VariableDeclarations::hit_test_position(size_t offset)
  1688. {
  1689. if (!position().contains(offset))
  1690. return {};
  1691. for (auto decl : m_variables) {
  1692. auto result = decl.value->hit_test_position(offset);
  1693. if (result.matching_node)
  1694. return result;
  1695. }
  1696. return { nullptr, nullptr, nullptr };
  1697. }
  1698. VariableDeclarations::VariableDeclarations(Position position, Vector<Variable> variables)
  1699. : Node(move(position))
  1700. , m_variables(move(variables))
  1701. {
  1702. for (auto& decl : m_variables) {
  1703. if (decl.name->is_syntax_error()) {
  1704. set_is_syntax_error(decl.name->syntax_error_node());
  1705. break;
  1706. }
  1707. if (decl.value->is_syntax_error()) {
  1708. set_is_syntax_error(decl.value->syntax_error_node());
  1709. break;
  1710. }
  1711. }
  1712. }
  1713. VariableDeclarations::~VariableDeclarations()
  1714. {
  1715. }
  1716. Value::~Value()
  1717. {
  1718. }
  1719. Vector<AST::Command> Value::resolve_as_commands(RefPtr<Shell> shell)
  1720. {
  1721. Command command;
  1722. command.argv = resolve_as_list(shell);
  1723. return { command };
  1724. }
  1725. ListValue::ListValue(Vector<String> values)
  1726. {
  1727. m_contained_values.ensure_capacity(values.size());
  1728. for (auto& str : values)
  1729. m_contained_values.append(adopt(*new StringValue(move(str))));
  1730. }
  1731. ListValue::~ListValue()
  1732. {
  1733. }
  1734. Vector<String> ListValue::resolve_as_list(RefPtr<Shell> shell)
  1735. {
  1736. Vector<String> values;
  1737. for (auto& value : m_contained_values)
  1738. values.append(value.resolve_as_list(shell));
  1739. return values;
  1740. }
  1741. NonnullRefPtr<Value> ListValue::resolve_without_cast(RefPtr<Shell> shell)
  1742. {
  1743. NonnullRefPtrVector<Value> values;
  1744. for (auto& value : m_contained_values)
  1745. values.append(value.resolve_without_cast(shell));
  1746. return create<ListValue>(move(values));
  1747. }
  1748. CommandValue::~CommandValue()
  1749. {
  1750. }
  1751. CommandSequenceValue::~CommandSequenceValue()
  1752. {
  1753. }
  1754. Vector<String> CommandSequenceValue::resolve_as_list(RefPtr<Shell>)
  1755. {
  1756. // TODO: Somehow raise an "error".
  1757. return {};
  1758. }
  1759. Vector<Command> CommandSequenceValue::resolve_as_commands(RefPtr<Shell>)
  1760. {
  1761. return m_contained_values;
  1762. }
  1763. Vector<String> CommandValue::resolve_as_list(RefPtr<Shell>)
  1764. {
  1765. // TODO: Somehow raise an "error".
  1766. return {};
  1767. }
  1768. Vector<Command> CommandValue::resolve_as_commands(RefPtr<Shell>)
  1769. {
  1770. return { m_command };
  1771. }
  1772. JobValue::~JobValue()
  1773. {
  1774. }
  1775. StringValue::~StringValue()
  1776. {
  1777. }
  1778. Vector<String> StringValue::resolve_as_list(RefPtr<Shell>)
  1779. {
  1780. if (is_list()) {
  1781. auto parts = StringView(m_string).split_view(m_split, m_keep_empty);
  1782. Vector<String> result;
  1783. result.ensure_capacity(parts.size());
  1784. for (auto& part : parts)
  1785. result.append(part);
  1786. return result;
  1787. }
  1788. return { m_string };
  1789. }
  1790. GlobValue::~GlobValue()
  1791. {
  1792. }
  1793. Vector<String> GlobValue::resolve_as_list(RefPtr<Shell> shell)
  1794. {
  1795. return shell->expand_globs(m_glob, shell->cwd);
  1796. }
  1797. SimpleVariableValue::~SimpleVariableValue()
  1798. {
  1799. }
  1800. Vector<String> SimpleVariableValue::resolve_as_list(RefPtr<Shell> shell)
  1801. {
  1802. if (auto value = resolve_without_cast(shell); value != this)
  1803. return value->resolve_as_list(shell);
  1804. char* env_value = getenv(m_name.characters());
  1805. if (env_value == nullptr)
  1806. return { "" };
  1807. Vector<String> res;
  1808. String str_env_value = String(env_value);
  1809. const auto& split_text = str_env_value.split_view(' ');
  1810. for (auto& part : split_text)
  1811. res.append(part);
  1812. return res;
  1813. }
  1814. NonnullRefPtr<Value> SimpleVariableValue::resolve_without_cast(RefPtr<Shell> shell)
  1815. {
  1816. if (auto value = shell->lookup_local_variable(m_name))
  1817. return value.release_nonnull();
  1818. return *this;
  1819. }
  1820. SpecialVariableValue::~SpecialVariableValue()
  1821. {
  1822. }
  1823. Vector<String> SpecialVariableValue::resolve_as_list(RefPtr<Shell> shell)
  1824. {
  1825. switch (m_name) {
  1826. case '?':
  1827. return { String::number(shell->last_return_code) };
  1828. case '$':
  1829. return { String::number(getpid()) };
  1830. case '*':
  1831. if (auto argv = shell->lookup_local_variable("ARGV"))
  1832. return argv->resolve_as_list(shell);
  1833. return {};
  1834. case '#':
  1835. if (auto argv = shell->lookup_local_variable("ARGV")) {
  1836. if (argv->is_list()) {
  1837. auto list_argv = static_cast<AST::ListValue*>(argv.ptr());
  1838. return { String::number(list_argv->values().size()) };
  1839. }
  1840. return { "1" };
  1841. }
  1842. return { "0" };
  1843. default:
  1844. return { "" };
  1845. }
  1846. }
  1847. TildeValue::~TildeValue()
  1848. {
  1849. }
  1850. Vector<String> TildeValue::resolve_as_list(RefPtr<Shell> shell)
  1851. {
  1852. StringBuilder builder;
  1853. builder.append("~");
  1854. builder.append(m_username);
  1855. return { shell->expand_tilde(builder.to_string()) };
  1856. }
  1857. Result<NonnullRefPtr<Rewiring>, String> CloseRedirection::apply() const
  1858. {
  1859. return adopt(*new Rewiring(fd, fd, Rewiring::Close::ImmediatelyCloseDestination));
  1860. }
  1861. CloseRedirection::~CloseRedirection()
  1862. {
  1863. }
  1864. Result<NonnullRefPtr<Rewiring>, String> PathRedirection::apply() const
  1865. {
  1866. auto check_fd_and_return = [my_fd = this->fd](int fd, const String& path) -> Result<NonnullRefPtr<Rewiring>, String> {
  1867. if (fd < 0) {
  1868. String error = strerror(errno);
  1869. dbg() << "open() failed for '" << path << "' with " << error;
  1870. return error;
  1871. }
  1872. return adopt(*new Rewiring(my_fd, fd, Rewiring::Close::Destination));
  1873. };
  1874. switch (direction) {
  1875. case AST::PathRedirection::WriteAppend:
  1876. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666), path);
  1877. case AST::PathRedirection::Write:
  1878. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666), path);
  1879. case AST::PathRedirection::Read:
  1880. return check_fd_and_return(open(path.characters(), O_RDONLY), path);
  1881. case AST::PathRedirection::ReadWrite:
  1882. return check_fd_and_return(open(path.characters(), O_RDWR | O_CREAT, 0666), path);
  1883. }
  1884. ASSERT_NOT_REACHED();
  1885. }
  1886. PathRedirection::~PathRedirection()
  1887. {
  1888. }
  1889. FdRedirection::~FdRedirection()
  1890. {
  1891. }
  1892. Redirection::~Redirection()
  1893. {
  1894. }
  1895. }