AST.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  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. auto commands = m_command->to_lazy_evaluated_commands(shell);
  293. for (auto& command : commands)
  294. command.should_wait = false;
  295. return create<CommandSequenceValue>(move(commands));
  296. }
  297. void Background::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  298. {
  299. m_command->highlight_in_editor(editor, shell, metadata);
  300. }
  301. HitTestResult Background::hit_test_position(size_t offset)
  302. {
  303. if (!position().contains(offset))
  304. return {};
  305. return m_command->hit_test_position(offset);
  306. }
  307. Background::Background(Position position, RefPtr<Node> command)
  308. : Node(move(position))
  309. , m_command(move(command))
  310. {
  311. if (m_command->is_syntax_error())
  312. set_is_syntax_error(m_command->syntax_error_node());
  313. }
  314. Background::~Background()
  315. {
  316. }
  317. void BarewordLiteral::dump(int level) const
  318. {
  319. Node::dump(level);
  320. print_indented(m_text, level + 1);
  321. }
  322. RefPtr<Value> BarewordLiteral::run(RefPtr<Shell>)
  323. {
  324. return create<StringValue>(m_text);
  325. }
  326. void BarewordLiteral::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  327. {
  328. if (metadata.is_first_in_list) {
  329. if (shell.is_runnable(m_text)) {
  330. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Bold });
  331. } else {
  332. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red) });
  333. }
  334. return;
  335. }
  336. if (m_text.starts_with('-')) {
  337. if (m_text == "--") {
  338. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  339. return;
  340. }
  341. if (m_text == "-")
  342. return;
  343. if (m_text.starts_with("--")) {
  344. auto index = m_text.index_of("=").value_or(m_text.length() - 1) + 1;
  345. editor.stylize({ m_position.start_offset, m_position.start_offset + index }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  346. } else {
  347. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan) });
  348. }
  349. }
  350. if (Core::File::exists(m_text)) {
  351. auto realpath = shell.resolve_path(m_text);
  352. auto url = URL::create_with_file_protocol(realpath);
  353. url.set_host(shell.hostname);
  354. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  355. }
  356. }
  357. BarewordLiteral::BarewordLiteral(Position position, String text)
  358. : Node(move(position))
  359. , m_text(move(text))
  360. {
  361. }
  362. BarewordLiteral::~BarewordLiteral()
  363. {
  364. }
  365. void CastToCommand::dump(int level) const
  366. {
  367. Node::dump(level);
  368. m_inner->dump(level + 1);
  369. }
  370. RefPtr<Value> CastToCommand::run(RefPtr<Shell> shell)
  371. {
  372. if (m_inner->is_command())
  373. return m_inner->run(shell);
  374. auto value = m_inner->run(shell)->resolve_without_cast(shell);
  375. if (value->is_command())
  376. return value;
  377. auto argv = value->resolve_as_list(shell);
  378. return create<CommandValue>(move(argv));
  379. }
  380. void CastToCommand::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  381. {
  382. m_inner->highlight_in_editor(editor, shell, metadata);
  383. }
  384. HitTestResult CastToCommand::hit_test_position(size_t offset)
  385. {
  386. if (!position().contains(offset))
  387. return {};
  388. auto result = m_inner->hit_test_position(offset);
  389. if (!result.closest_node_with_semantic_meaning)
  390. result.closest_node_with_semantic_meaning = this;
  391. return result;
  392. }
  393. Vector<Line::CompletionSuggestion> CastToCommand::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  394. {
  395. auto matching_node = hit_test_result.matching_node;
  396. if (!matching_node || !matching_node->is_bareword())
  397. return {};
  398. auto corrected_offset = offset - matching_node->position().start_offset;
  399. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  400. if (corrected_offset > node->text().length())
  401. return {};
  402. return shell.complete_program_name(node->text(), corrected_offset);
  403. }
  404. RefPtr<Node> CastToCommand::leftmost_trivial_literal() const
  405. {
  406. return m_inner->leftmost_trivial_literal();
  407. }
  408. CastToCommand::CastToCommand(Position position, RefPtr<Node> inner)
  409. : Node(move(position))
  410. , m_inner(move(inner))
  411. {
  412. if (m_inner->is_syntax_error())
  413. set_is_syntax_error(m_inner->syntax_error_node());
  414. }
  415. CastToCommand::~CastToCommand()
  416. {
  417. }
  418. void CastToList::dump(int level) const
  419. {
  420. Node::dump(level);
  421. if (m_inner)
  422. m_inner->dump(level + 1);
  423. else
  424. print_indented("(empty)", level + 1);
  425. }
  426. RefPtr<Value> CastToList::run(RefPtr<Shell> shell)
  427. {
  428. if (!m_inner)
  429. return create<ListValue>({});
  430. auto inner_value = m_inner->run(shell)->resolve_without_cast(shell);
  431. if (inner_value->is_command() || inner_value->is_list())
  432. return inner_value;
  433. auto values = inner_value->resolve_as_list(shell);
  434. NonnullRefPtrVector<Value> cast_values;
  435. for (auto& value : values)
  436. cast_values.append(create<StringValue>(value));
  437. return create<ListValue>(cast_values);
  438. }
  439. void CastToList::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  440. {
  441. if (m_inner)
  442. m_inner->highlight_in_editor(editor, shell, metadata);
  443. }
  444. HitTestResult CastToList::hit_test_position(size_t offset)
  445. {
  446. if (!position().contains(offset))
  447. return {};
  448. if (!m_inner)
  449. return {};
  450. return m_inner->hit_test_position(offset);
  451. }
  452. RefPtr<Node> CastToList::leftmost_trivial_literal() const
  453. {
  454. return m_inner->leftmost_trivial_literal();
  455. }
  456. CastToList::CastToList(Position position, RefPtr<Node> inner)
  457. : Node(move(position))
  458. , m_inner(move(inner))
  459. {
  460. if (m_inner && m_inner->is_syntax_error())
  461. set_is_syntax_error(m_inner->syntax_error_node());
  462. }
  463. CastToList::~CastToList()
  464. {
  465. }
  466. void CloseFdRedirection::dump(int level) const
  467. {
  468. Node::dump(level);
  469. print_indented(String::format("%d -> Close", m_fd), level);
  470. }
  471. RefPtr<Value> CloseFdRedirection::run(RefPtr<Shell>)
  472. {
  473. Command command;
  474. command.redirections.append(adopt(*new CloseRedirection(m_fd)));
  475. return create<CommandValue>(move(command));
  476. }
  477. void CloseFdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  478. {
  479. editor.stylize({ m_position.start_offset, m_position.end_offset - 1 }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  480. editor.stylize({ m_position.end_offset - 1, m_position.end_offset }, { Line::Style::Foreground(0xff, 0x7e, 0x00) }); // Amber
  481. }
  482. CloseFdRedirection::CloseFdRedirection(Position position, int fd)
  483. : Node(move(position))
  484. , m_fd(fd)
  485. {
  486. }
  487. CloseFdRedirection::~CloseFdRedirection()
  488. {
  489. }
  490. void CommandLiteral::dump(int level) const
  491. {
  492. Node::dump(level);
  493. print_indented("(Generated command literal)", level + 1);
  494. }
  495. RefPtr<Value> CommandLiteral::run(RefPtr<Shell>)
  496. {
  497. return create<CommandValue>(m_command);
  498. }
  499. CommandLiteral::CommandLiteral(Position position, Command command)
  500. : Node(move(position))
  501. , m_command(move(command))
  502. {
  503. }
  504. CommandLiteral::~CommandLiteral()
  505. {
  506. }
  507. void Comment::dump(int level) const
  508. {
  509. Node::dump(level);
  510. print_indented(m_text, level + 1);
  511. }
  512. RefPtr<Value> Comment::run(RefPtr<Shell>)
  513. {
  514. return create<ListValue>({});
  515. }
  516. void Comment::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  517. {
  518. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(150, 150, 150) }); // Light gray
  519. }
  520. Comment::Comment(Position position, String text)
  521. : Node(move(position))
  522. , m_text(move(text))
  523. {
  524. }
  525. Comment::~Comment()
  526. {
  527. }
  528. void DoubleQuotedString::dump(int level) const
  529. {
  530. Node::dump(level);
  531. m_inner->dump(level + 1);
  532. }
  533. RefPtr<Value> DoubleQuotedString::run(RefPtr<Shell> shell)
  534. {
  535. StringBuilder builder;
  536. auto values = m_inner->run(shell)->resolve_as_list(shell);
  537. builder.join("", values);
  538. return create<StringValue>(builder.to_string());
  539. }
  540. void DoubleQuotedString::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  541. {
  542. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  543. if (metadata.is_first_in_list)
  544. style.unify_with({ Line::Style::Bold });
  545. editor.stylize({ m_position.start_offset, m_position.end_offset }, style);
  546. metadata.is_first_in_list = false;
  547. m_inner->highlight_in_editor(editor, shell, metadata);
  548. }
  549. HitTestResult DoubleQuotedString::hit_test_position(size_t offset)
  550. {
  551. if (!position().contains(offset))
  552. return {};
  553. return m_inner->hit_test_position(offset);
  554. }
  555. DoubleQuotedString::DoubleQuotedString(Position position, RefPtr<Node> inner)
  556. : Node(move(position))
  557. , m_inner(move(inner))
  558. {
  559. if (m_inner->is_syntax_error())
  560. set_is_syntax_error(m_inner->syntax_error_node());
  561. }
  562. DoubleQuotedString::~DoubleQuotedString()
  563. {
  564. }
  565. void DynamicEvaluate::dump(int level) const
  566. {
  567. Node::dump(level);
  568. m_inner->dump(level + 1);
  569. }
  570. RefPtr<Value> DynamicEvaluate::run(RefPtr<Shell> shell)
  571. {
  572. auto result = m_inner->run(shell)->resolve_without_cast(shell);
  573. // Dynamic Evaluation behaves differently between strings and lists.
  574. // Strings are treated as variables, and Lists are treated as commands.
  575. if (result->is_string()) {
  576. auto name_part = result->resolve_as_list(shell);
  577. ASSERT(name_part.size() == 1);
  578. return create<SimpleVariableValue>(name_part[0]);
  579. }
  580. // If it's anything else, we're just gonna cast it to a list.
  581. auto list = result->resolve_as_list(shell);
  582. return create<CommandValue>(move(list));
  583. }
  584. void DynamicEvaluate::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  585. {
  586. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  587. m_inner->highlight_in_editor(editor, shell, metadata);
  588. }
  589. HitTestResult DynamicEvaluate::hit_test_position(size_t offset)
  590. {
  591. if (!position().contains(offset))
  592. return {};
  593. return m_inner->hit_test_position(offset);
  594. }
  595. DynamicEvaluate::DynamicEvaluate(Position position, RefPtr<Node> inner)
  596. : Node(move(position))
  597. , m_inner(move(inner))
  598. {
  599. if (m_inner->is_syntax_error())
  600. set_is_syntax_error(m_inner->syntax_error_node());
  601. }
  602. DynamicEvaluate::~DynamicEvaluate()
  603. {
  604. }
  605. void Fd2FdRedirection::dump(int level) const
  606. {
  607. Node::dump(level);
  608. print_indented(String::format("%d -> %d", source_fd, dest_fd), level);
  609. }
  610. RefPtr<Value> Fd2FdRedirection::run(RefPtr<Shell>)
  611. {
  612. Command command;
  613. command.redirections.append(FdRedirection::create(source_fd, dest_fd, Rewiring::Close::None));
  614. return create<CommandValue>(move(command));
  615. }
  616. void Fd2FdRedirection::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  617. {
  618. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  619. }
  620. Fd2FdRedirection::Fd2FdRedirection(Position position, int src, int dst)
  621. : Node(move(position))
  622. , source_fd(src)
  623. , dest_fd(dst)
  624. {
  625. }
  626. Fd2FdRedirection::~Fd2FdRedirection()
  627. {
  628. }
  629. void FunctionDeclaration::dump(int level) const
  630. {
  631. Node::dump(level);
  632. print_indented(String::format("(name: %s)\n", m_name.name.characters()), level + 1);
  633. print_indented("(argument namess)", level + 1);
  634. for (auto& arg : m_arguments)
  635. print_indented(String::format("(name: %s)\n", arg.name.characters()), level + 2);
  636. print_indented("(body)", level + 1);
  637. if (m_block)
  638. m_block->dump(level + 2);
  639. else
  640. print_indented("(null)", level + 2);
  641. }
  642. RefPtr<Value> FunctionDeclaration::run(RefPtr<Shell> shell)
  643. {
  644. Vector<String> args;
  645. for (auto& arg : m_arguments)
  646. args.append(arg.name);
  647. shell->define_function(m_name.name, move(args), m_block);
  648. return create<ListValue>({});
  649. }
  650. void FunctionDeclaration::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  651. {
  652. editor.stylize({ m_name.position.start_offset, m_name.position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
  653. for (auto& arg : m_arguments)
  654. editor.stylize({ arg.position.start_offset, arg.position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Italic });
  655. metadata.is_first_in_list = true;
  656. if (m_block)
  657. m_block->highlight_in_editor(editor, shell, metadata);
  658. }
  659. HitTestResult FunctionDeclaration::hit_test_position(size_t offset)
  660. {
  661. if (!position().contains(offset))
  662. return {};
  663. return m_block->hit_test_position(offset);
  664. }
  665. FunctionDeclaration::FunctionDeclaration(Position position, NameWithPosition name, Vector<NameWithPosition> arguments, RefPtr<AST::Node> body)
  666. : Node(move(position))
  667. , m_name(move(name))
  668. , m_arguments(arguments)
  669. , m_block(move(body))
  670. {
  671. if (m_block && m_block->is_syntax_error())
  672. set_is_syntax_error(m_block->syntax_error_node());
  673. }
  674. FunctionDeclaration::~FunctionDeclaration()
  675. {
  676. }
  677. void ForLoop::dump(int level) const
  678. {
  679. Node::dump(level);
  680. print_indented(String::format("%s in\n", m_variable_name.characters()), level + 1);
  681. m_iterated_expression->dump(level + 2);
  682. print_indented("Running", level + 1);
  683. if (m_block)
  684. m_block->dump(level + 2);
  685. else
  686. print_indented("(null)", level + 2);
  687. }
  688. RefPtr<Value> ForLoop::run(RefPtr<Shell> shell)
  689. {
  690. if (!m_block)
  691. return create<ListValue>({});
  692. size_t consecutive_interruptions = 0;
  693. m_iterated_expression->for_each_entry(shell, [&](auto value) {
  694. if (consecutive_interruptions == 2)
  695. return IterationDecision::Break;
  696. RefPtr<Value> block_value;
  697. {
  698. auto frame = shell->push_frame();
  699. shell->set_local_variable(m_variable_name, value);
  700. block_value = m_block->run(shell);
  701. }
  702. if (block_value->is_job()) {
  703. auto job = static_cast<JobValue*>(block_value.ptr())->job();
  704. if (!job || job->is_running_in_background())
  705. return IterationDecision::Continue;
  706. shell->block_on_job(job);
  707. if (job->signaled()) {
  708. if (job->termination_signal() == SIGINT)
  709. ++consecutive_interruptions;
  710. else
  711. return IterationDecision::Break;
  712. } else {
  713. consecutive_interruptions = 0;
  714. }
  715. }
  716. return IterationDecision::Continue;
  717. });
  718. return create<ListValue>({});
  719. }
  720. void ForLoop::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  721. {
  722. editor.stylize({ m_position.start_offset, m_position.start_offset + 3 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  723. if (m_in_kw_position.has_value())
  724. editor.stylize({ m_in_kw_position.value(), m_in_kw_position.value() + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  725. metadata.is_first_in_list = false;
  726. m_iterated_expression->highlight_in_editor(editor, shell, metadata);
  727. metadata.is_first_in_list = true;
  728. if (m_block)
  729. m_block->highlight_in_editor(editor, shell, metadata);
  730. }
  731. HitTestResult ForLoop::hit_test_position(size_t offset)
  732. {
  733. if (!position().contains(offset))
  734. return {};
  735. if (auto result = m_iterated_expression->hit_test_position(offset); result.matching_node)
  736. return result;
  737. return m_block->hit_test_position(offset);
  738. }
  739. ForLoop::ForLoop(Position position, String variable_name, RefPtr<AST::Node> iterated_expr, RefPtr<AST::Node> block, Optional<size_t> in_kw_position)
  740. : Node(move(position))
  741. , m_variable_name(move(variable_name))
  742. , m_iterated_expression(move(iterated_expr))
  743. , m_block(move(block))
  744. , m_in_kw_position(move(in_kw_position))
  745. {
  746. if (m_iterated_expression->is_syntax_error())
  747. set_is_syntax_error(m_iterated_expression->syntax_error_node());
  748. else if (m_block && m_block->is_syntax_error())
  749. set_is_syntax_error(m_block->syntax_error_node());
  750. }
  751. ForLoop::~ForLoop()
  752. {
  753. }
  754. void Glob::dump(int level) const
  755. {
  756. Node::dump(level);
  757. print_indented(m_text, level + 1);
  758. }
  759. RefPtr<Value> Glob::run(RefPtr<Shell>)
  760. {
  761. return create<GlobValue>(m_text);
  762. }
  763. void Glob::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  764. {
  765. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Cyan) };
  766. if (metadata.is_first_in_list)
  767. style.unify_with({ Line::Style::Bold });
  768. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  769. }
  770. Glob::Glob(Position position, String text)
  771. : Node(move(position))
  772. , m_text(move(text))
  773. {
  774. }
  775. Glob::~Glob()
  776. {
  777. }
  778. void Execute::dump(int level) const
  779. {
  780. Node::dump(level);
  781. if (m_capture_stdout)
  782. print_indented("(Capturing stdout)", level + 1);
  783. m_command->dump(level + 1);
  784. }
  785. void Execute::for_each_entry(RefPtr<Shell> shell, Function<IterationDecision(RefPtr<Value>)> callback)
  786. {
  787. if (m_command->would_execute())
  788. return m_command->for_each_entry(shell, move(callback));
  789. auto commands = shell->expand_aliases(m_command->run(shell)->resolve_as_commands(shell));
  790. if (m_capture_stdout) {
  791. int pipefd[2];
  792. int rc = pipe(pipefd);
  793. if (rc < 0) {
  794. dbg() << "Error: cannot pipe(): " << strerror(errno);
  795. return;
  796. }
  797. auto& last_in_commands = commands.last();
  798. last_in_commands.redirections.prepend(FdRedirection::create(STDOUT_FILENO, pipefd[1], Rewiring::Close::Destination));
  799. last_in_commands.should_wait = false;
  800. last_in_commands.should_notify_if_in_background = false;
  801. last_in_commands.is_pipe_source = false;
  802. Core::EventLoop loop;
  803. auto notifier = Core::Notifier::construct(pipefd[0], Core::Notifier::Read);
  804. DuplexMemoryStream stream;
  805. enum {
  806. Continue,
  807. Break,
  808. NothingLeft,
  809. };
  810. auto check_and_call = [&] {
  811. auto ifs = shell->local_variable_or("IFS", "\n");
  812. if (auto offset = stream.offset_of(ifs.bytes()); offset.has_value()) {
  813. auto line_end = offset.value();
  814. if (line_end == 0) {
  815. auto rc = stream.discard_or_error(ifs.length());
  816. ASSERT(rc);
  817. if (shell->options.inline_exec_keep_empty_segments)
  818. if (callback(create<StringValue>("")) == IterationDecision::Break) {
  819. loop.quit(Break);
  820. notifier->set_enabled(false);
  821. return Break;
  822. }
  823. } else {
  824. auto entry = ByteBuffer::create_uninitialized(line_end + ifs.length());
  825. auto rc = stream.read_or_error(entry);
  826. ASSERT(rc);
  827. auto str = StringView(entry.data(), entry.size() - ifs.length());
  828. if (callback(create<StringValue>(str)) == IterationDecision::Break) {
  829. loop.quit(Break);
  830. notifier->set_enabled(false);
  831. return Break;
  832. }
  833. }
  834. return Continue;
  835. }
  836. return NothingLeft;
  837. };
  838. notifier->on_ready_to_read = [&] {
  839. constexpr static auto buffer_size = 16;
  840. u8 buffer[buffer_size];
  841. size_t remaining_size = buffer_size;
  842. for (;;) {
  843. notifier->set_event_mask(Core::Notifier::None);
  844. bool should_enable_notifier = false;
  845. ScopeGuard notifier_enabler { [&] {
  846. if (should_enable_notifier)
  847. notifier->set_event_mask(Core::Notifier::Read);
  848. } };
  849. if (check_and_call() == Break)
  850. return;
  851. auto read_size = read(pipefd[0], buffer, remaining_size);
  852. if (read_size < 0) {
  853. int saved_errno = errno;
  854. if (saved_errno == EINTR) {
  855. should_enable_notifier = true;
  856. continue;
  857. }
  858. if (saved_errno == 0)
  859. continue;
  860. dbg() << "read() failed: " << strerror(saved_errno);
  861. break;
  862. }
  863. if (read_size == 0)
  864. break;
  865. should_enable_notifier = true;
  866. stream.write({ buffer, (size_t)read_size });
  867. }
  868. loop.quit(Break);
  869. };
  870. shell->run_commands(commands);
  871. loop.exec();
  872. notifier->on_ready_to_read = nullptr;
  873. if (close(pipefd[0]) < 0) {
  874. dbg() << "close() failed: " << strerror(errno);
  875. }
  876. if (!stream.eof()) {
  877. auto action = Continue;
  878. do {
  879. action = check_and_call();
  880. if (action == Break)
  881. return;
  882. } while (action == Continue);
  883. if (!stream.eof()) {
  884. auto entry = ByteBuffer::create_uninitialized(stream.remaining());
  885. auto rc = stream.read_or_error(entry);
  886. ASSERT(rc);
  887. callback(create<StringValue>(String::copy(entry)));
  888. }
  889. }
  890. return;
  891. }
  892. auto jobs = shell->run_commands(commands);
  893. if (!jobs.is_empty())
  894. callback(create<JobValue>(&jobs.last()));
  895. }
  896. RefPtr<Value> Execute::run(RefPtr<Shell> shell)
  897. {
  898. if (m_command->would_execute())
  899. return m_command->run(shell);
  900. NonnullRefPtrVector<Value> values;
  901. for_each_entry(shell, [&](auto value) {
  902. values.append(*value);
  903. return IterationDecision::Continue;
  904. });
  905. if (values.size() == 1 && values.first().is_job())
  906. return values.first();
  907. return create<ListValue>(move(values));
  908. }
  909. void Execute::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  910. {
  911. if (m_capture_stdout)
  912. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Green) });
  913. metadata.is_first_in_list = true;
  914. m_command->highlight_in_editor(editor, shell, metadata);
  915. }
  916. HitTestResult Execute::hit_test_position(size_t offset)
  917. {
  918. if (!position().contains(offset))
  919. return {};
  920. auto result = m_command->hit_test_position(offset);
  921. if (!result.closest_node_with_semantic_meaning)
  922. result.closest_node_with_semantic_meaning = this;
  923. if (!result.closest_command_node)
  924. result.closest_command_node = m_command;
  925. return result;
  926. }
  927. Vector<Line::CompletionSuggestion> Execute::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  928. {
  929. auto matching_node = hit_test_result.matching_node;
  930. if (!matching_node || !matching_node->is_bareword())
  931. return {};
  932. auto corrected_offset = offset - matching_node->position().start_offset;
  933. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  934. if (corrected_offset > node->text().length())
  935. return {};
  936. return shell.complete_program_name(node->text(), corrected_offset);
  937. }
  938. Execute::Execute(Position position, RefPtr<Node> command, bool capture_stdout)
  939. : Node(move(position))
  940. , m_command(move(command))
  941. , m_capture_stdout(capture_stdout)
  942. {
  943. if (m_command->is_syntax_error())
  944. set_is_syntax_error(m_command->syntax_error_node());
  945. }
  946. Execute::~Execute()
  947. {
  948. }
  949. void IfCond::dump(int level) const
  950. {
  951. Node::dump(level);
  952. print_indented("Condition", ++level);
  953. m_condition->dump(level + 1);
  954. print_indented("True Branch", level);
  955. if (m_true_branch)
  956. m_true_branch->dump(level + 1);
  957. else
  958. print_indented("(empty)", level + 1);
  959. print_indented("False Branch", level);
  960. if (m_false_branch)
  961. m_false_branch->dump(level + 1);
  962. else
  963. print_indented("(empty)", level + 1);
  964. }
  965. RefPtr<Value> IfCond::run(RefPtr<Shell> shell)
  966. {
  967. auto cond = m_condition->run(shell)->resolve_without_cast(shell);
  968. ASSERT(cond->is_job());
  969. auto cond_job_value = static_cast<const JobValue*>(cond.ptr());
  970. auto cond_job = cond_job_value->job();
  971. shell->block_on_job(cond_job);
  972. if (cond_job->signaled())
  973. return create<ListValue>({}); // Exit early.
  974. if (shell->last_return_code == 0) {
  975. if (m_true_branch)
  976. return m_true_branch->run(shell);
  977. } else {
  978. if (m_false_branch)
  979. return m_false_branch->run(shell);
  980. }
  981. return create<ListValue>({});
  982. }
  983. void IfCond::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  984. {
  985. metadata.is_first_in_list = true;
  986. editor.stylize({ m_position.start_offset, m_position.start_offset + 2 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  987. if (m_else_position.has_value())
  988. editor.stylize({ m_else_position.value().start_offset, m_else_position.value().start_offset + 4 }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow) });
  989. m_condition->highlight_in_editor(editor, shell, metadata);
  990. if (m_true_branch)
  991. m_true_branch->highlight_in_editor(editor, shell, metadata);
  992. if (m_false_branch)
  993. m_false_branch->highlight_in_editor(editor, shell, metadata);
  994. }
  995. HitTestResult IfCond::hit_test_position(size_t offset)
  996. {
  997. if (!position().contains(offset))
  998. return {};
  999. if (auto result = m_condition->hit_test_position(offset); result.matching_node)
  1000. return result;
  1001. if (m_true_branch) {
  1002. if (auto result = m_true_branch->hit_test_position(offset); result.matching_node)
  1003. return result;
  1004. }
  1005. if (m_false_branch) {
  1006. if (auto result = m_false_branch->hit_test_position(offset); result.matching_node)
  1007. return result;
  1008. }
  1009. return {};
  1010. }
  1011. IfCond::IfCond(Position position, Optional<Position> else_position, RefPtr<Node> condition, RefPtr<Node> true_branch, RefPtr<Node> false_branch)
  1012. : Node(move(position))
  1013. , m_condition(move(condition))
  1014. , m_true_branch(move(true_branch))
  1015. , m_false_branch(move(false_branch))
  1016. , m_else_position(move(else_position))
  1017. {
  1018. if (m_condition->is_syntax_error())
  1019. set_is_syntax_error(m_condition->syntax_error_node());
  1020. else if (m_true_branch && m_true_branch->is_syntax_error())
  1021. set_is_syntax_error(m_true_branch->syntax_error_node());
  1022. else if (m_false_branch && m_false_branch->is_syntax_error())
  1023. set_is_syntax_error(m_false_branch->syntax_error_node());
  1024. m_condition = create<AST::Execute>(m_condition->position(), m_condition);
  1025. if (m_true_branch)
  1026. m_true_branch = create<AST::Execute>(m_true_branch->position(), m_true_branch);
  1027. if (m_false_branch)
  1028. m_false_branch = create<AST::Execute>(m_false_branch->position(), m_false_branch);
  1029. }
  1030. IfCond::~IfCond()
  1031. {
  1032. }
  1033. void Join::dump(int level) const
  1034. {
  1035. Node::dump(level);
  1036. m_left->dump(level + 1);
  1037. m_right->dump(level + 1);
  1038. }
  1039. RefPtr<Value> Join::run(RefPtr<Shell> shell)
  1040. {
  1041. auto left = m_left->to_lazy_evaluated_commands(shell);
  1042. auto right = m_right->to_lazy_evaluated_commands(shell);
  1043. return create<CommandSequenceValue>(join_commands(move(left), move(right)));
  1044. }
  1045. void Join::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1046. {
  1047. m_left->highlight_in_editor(editor, shell, metadata);
  1048. if (m_left->is_list() || m_left->is_command())
  1049. metadata.is_first_in_list = false;
  1050. m_right->highlight_in_editor(editor, shell, metadata);
  1051. }
  1052. HitTestResult Join::hit_test_position(size_t offset)
  1053. {
  1054. if (!position().contains(offset))
  1055. return {};
  1056. auto result = m_left->hit_test_position(offset);
  1057. if (result.matching_node)
  1058. return result;
  1059. return m_right->hit_test_position(offset);
  1060. }
  1061. RefPtr<Node> Join::leftmost_trivial_literal() const
  1062. {
  1063. if (auto value = m_left->leftmost_trivial_literal())
  1064. return value;
  1065. return m_right->leftmost_trivial_literal();
  1066. }
  1067. Join::Join(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1068. : Node(move(position))
  1069. , m_left(move(left))
  1070. , m_right(move(right))
  1071. {
  1072. if (m_left->is_syntax_error())
  1073. set_is_syntax_error(m_left->syntax_error_node());
  1074. else if (m_right->is_syntax_error())
  1075. set_is_syntax_error(m_right->syntax_error_node());
  1076. }
  1077. Join::~Join()
  1078. {
  1079. }
  1080. void Or::dump(int level) const
  1081. {
  1082. Node::dump(level);
  1083. m_left->dump(level + 1);
  1084. m_right->dump(level + 1);
  1085. }
  1086. RefPtr<Value> Or::run(RefPtr<Shell> shell)
  1087. {
  1088. auto commands = m_left->to_lazy_evaluated_commands(shell);
  1089. commands.last().next_chain.empend(*m_right, NodeWithAction::Or);
  1090. return create<CommandSequenceValue>(move(commands));
  1091. }
  1092. void Or::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1093. {
  1094. m_left->highlight_in_editor(editor, shell, metadata);
  1095. m_right->highlight_in_editor(editor, shell, metadata);
  1096. }
  1097. HitTestResult Or::hit_test_position(size_t offset)
  1098. {
  1099. if (!position().contains(offset))
  1100. return {};
  1101. auto result = m_left->hit_test_position(offset);
  1102. if (result.matching_node) {
  1103. if (!result.closest_command_node)
  1104. result.closest_command_node = m_right;
  1105. return result;
  1106. }
  1107. result = m_right->hit_test_position(offset);
  1108. if (!result.closest_command_node)
  1109. result.closest_command_node = m_right;
  1110. return result;
  1111. }
  1112. Or::Or(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1113. : Node(move(position))
  1114. , m_left(move(left))
  1115. , m_right(move(right))
  1116. {
  1117. if (m_left->is_syntax_error())
  1118. set_is_syntax_error(m_left->syntax_error_node());
  1119. else if (m_right->is_syntax_error())
  1120. set_is_syntax_error(m_right->syntax_error_node());
  1121. }
  1122. Or::~Or()
  1123. {
  1124. }
  1125. void Pipe::dump(int level) const
  1126. {
  1127. Node::dump(level);
  1128. m_left->dump(level + 1);
  1129. m_right->dump(level + 1);
  1130. }
  1131. RefPtr<Value> Pipe::run(RefPtr<Shell> shell)
  1132. {
  1133. auto left = m_left->to_lazy_evaluated_commands(shell);
  1134. auto right = m_right->to_lazy_evaluated_commands(shell);
  1135. auto last_in_left = left.take_last();
  1136. auto first_in_right = right.take_first();
  1137. auto pipe_read_end = FdRedirection::create(STDIN_FILENO, -1, Rewiring::Close::Destination);
  1138. auto pipe_write_end = FdRedirection::create(STDOUT_FILENO, -1, pipe_read_end, Rewiring::Close::RefreshDestination);
  1139. first_in_right.redirections.append(pipe_read_end);
  1140. last_in_left.redirections.append(pipe_write_end);
  1141. last_in_left.should_wait = false;
  1142. last_in_left.is_pipe_source = true;
  1143. if (first_in_right.pipeline) {
  1144. last_in_left.pipeline = first_in_right.pipeline;
  1145. } else {
  1146. auto pipeline = adopt(*new Pipeline);
  1147. last_in_left.pipeline = pipeline;
  1148. first_in_right.pipeline = pipeline;
  1149. }
  1150. Vector<Command> commands;
  1151. commands.append(left);
  1152. commands.append(last_in_left);
  1153. commands.append(first_in_right);
  1154. commands.append(right);
  1155. return create<CommandSequenceValue>(move(commands));
  1156. }
  1157. void Pipe::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1158. {
  1159. m_left->highlight_in_editor(editor, shell, metadata);
  1160. m_right->highlight_in_editor(editor, shell, metadata);
  1161. }
  1162. HitTestResult Pipe::hit_test_position(size_t offset)
  1163. {
  1164. if (!position().contains(offset))
  1165. return {};
  1166. auto result = m_left->hit_test_position(offset);
  1167. if (result.matching_node)
  1168. return result;
  1169. return m_right->hit_test_position(offset);
  1170. }
  1171. Pipe::Pipe(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1172. : Node(move(position))
  1173. , m_left(move(left))
  1174. , m_right(move(right))
  1175. {
  1176. if (m_left->is_syntax_error())
  1177. set_is_syntax_error(m_left->syntax_error_node());
  1178. else if (m_right->is_syntax_error())
  1179. set_is_syntax_error(m_right->syntax_error_node());
  1180. }
  1181. Pipe::~Pipe()
  1182. {
  1183. }
  1184. PathRedirectionNode::PathRedirectionNode(Position position, int fd, RefPtr<Node> path)
  1185. : Node(move(position))
  1186. , m_fd(fd)
  1187. , m_path(move(path))
  1188. {
  1189. }
  1190. void PathRedirectionNode::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1191. {
  1192. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(0x87, 0x9b, 0xcd) }); // 25% Darkened Periwinkle
  1193. metadata.is_first_in_list = false;
  1194. m_path->highlight_in_editor(editor, shell, metadata);
  1195. if (m_path->is_bareword()) {
  1196. auto path_text = m_path->run(nullptr)->resolve_as_list(nullptr);
  1197. ASSERT(path_text.size() == 1);
  1198. // Apply a URL to the path.
  1199. auto& position = m_path->position();
  1200. auto& path = path_text[0];
  1201. if (!path.starts_with('/'))
  1202. path = String::format("%s/%s", shell.cwd.characters(), path.characters());
  1203. auto url = URL::create_with_file_protocol(path);
  1204. url.set_host(shell.hostname);
  1205. editor.stylize({ position.start_offset, position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  1206. }
  1207. }
  1208. HitTestResult PathRedirectionNode::hit_test_position(size_t offset)
  1209. {
  1210. if (!position().contains(offset))
  1211. return {};
  1212. auto result = m_path->hit_test_position(offset);
  1213. if (!result.closest_node_with_semantic_meaning)
  1214. result.closest_node_with_semantic_meaning = this;
  1215. return result;
  1216. }
  1217. Vector<Line::CompletionSuggestion> PathRedirectionNode::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1218. {
  1219. auto matching_node = hit_test_result.matching_node;
  1220. if (!matching_node || !matching_node->is_bareword())
  1221. return {};
  1222. auto corrected_offset = offset - matching_node->position().start_offset;
  1223. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  1224. if (corrected_offset > node->text().length())
  1225. return {};
  1226. return shell.complete_path("", node->text(), corrected_offset);
  1227. }
  1228. PathRedirectionNode::~PathRedirectionNode()
  1229. {
  1230. }
  1231. void ReadRedirection::dump(int level) const
  1232. {
  1233. Node::dump(level);
  1234. m_path->dump(level + 1);
  1235. print_indented(String::format("To %d", m_fd), level + 1);
  1236. }
  1237. RefPtr<Value> ReadRedirection::run(RefPtr<Shell> shell)
  1238. {
  1239. Command command;
  1240. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1241. StringBuilder builder;
  1242. builder.join(" ", path_segments);
  1243. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Read));
  1244. return create<CommandValue>(move(command));
  1245. }
  1246. ReadRedirection::ReadRedirection(Position position, int fd, RefPtr<Node> path)
  1247. : PathRedirectionNode(move(position), fd, move(path))
  1248. {
  1249. }
  1250. ReadRedirection::~ReadRedirection()
  1251. {
  1252. }
  1253. void ReadWriteRedirection::dump(int level) const
  1254. {
  1255. Node::dump(level);
  1256. m_path->dump(level + 1);
  1257. print_indented(String::format("To/From %d", m_fd), level + 1);
  1258. }
  1259. RefPtr<Value> ReadWriteRedirection::run(RefPtr<Shell> shell)
  1260. {
  1261. Command command;
  1262. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1263. StringBuilder builder;
  1264. builder.join(" ", path_segments);
  1265. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::ReadWrite));
  1266. return create<CommandValue>(move(command));
  1267. }
  1268. ReadWriteRedirection::ReadWriteRedirection(Position position, int fd, RefPtr<Node> path)
  1269. : PathRedirectionNode(move(position), fd, move(path))
  1270. {
  1271. }
  1272. ReadWriteRedirection::~ReadWriteRedirection()
  1273. {
  1274. }
  1275. void Sequence::dump(int level) const
  1276. {
  1277. Node::dump(level);
  1278. m_left->dump(level + 1);
  1279. m_right->dump(level + 1);
  1280. }
  1281. RefPtr<Value> Sequence::run(RefPtr<Shell> shell)
  1282. {
  1283. // If we are to return a job, block on the left one then return the right one.
  1284. if (would_execute()) {
  1285. RefPtr<AST::Node> execute_node = create<AST::Execute>(m_left->position(), m_left);
  1286. auto left_value = execute_node->run(shell);
  1287. // Some nodes are inherently empty, such as Comments and For loops without bodies,
  1288. // it is not an error for the value not to be a job.
  1289. if (left_value && left_value->is_job())
  1290. shell->block_on_job(static_cast<JobValue*>(left_value.ptr())->job());
  1291. if (m_right->would_execute())
  1292. return m_right->run(shell);
  1293. execute_node = create<AST::Execute>(m_right->position(), m_right);
  1294. return execute_node->run(shell);
  1295. }
  1296. auto left = m_left->to_lazy_evaluated_commands(shell);
  1297. // This could happen if a comment is next to a command.
  1298. if (left.size() == 1) {
  1299. auto& command = left.first();
  1300. if (command.argv.is_empty() && command.redirections.is_empty())
  1301. return m_right->run(shell);
  1302. }
  1303. if (left.last().should_wait)
  1304. left.last().next_chain.append(NodeWithAction { *m_right, NodeWithAction::Sequence });
  1305. else
  1306. left.append(m_right->to_lazy_evaluated_commands(shell));
  1307. return create<CommandSequenceValue>(move(left));
  1308. }
  1309. void Sequence::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1310. {
  1311. m_left->highlight_in_editor(editor, shell, metadata);
  1312. m_right->highlight_in_editor(editor, shell, metadata);
  1313. }
  1314. HitTestResult Sequence::hit_test_position(size_t offset)
  1315. {
  1316. if (!position().contains(offset))
  1317. return {};
  1318. auto result = m_left->hit_test_position(offset);
  1319. if (result.matching_node)
  1320. return result;
  1321. return m_right->hit_test_position(offset);
  1322. }
  1323. Sequence::Sequence(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1324. : Node(move(position))
  1325. , m_left(move(left))
  1326. , m_right(move(right))
  1327. {
  1328. if (m_left->is_syntax_error())
  1329. set_is_syntax_error(m_left->syntax_error_node());
  1330. else if (m_right->is_syntax_error())
  1331. set_is_syntax_error(m_right->syntax_error_node());
  1332. }
  1333. Sequence::~Sequence()
  1334. {
  1335. }
  1336. void Subshell::dump(int level) const
  1337. {
  1338. Node::dump(level);
  1339. if (m_block)
  1340. m_block->dump(level + 1);
  1341. }
  1342. RefPtr<Value> Subshell::run(RefPtr<Shell> shell)
  1343. {
  1344. if (!m_block)
  1345. return create<ListValue>({});
  1346. return m_block->run(shell);
  1347. }
  1348. void Subshell::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1349. {
  1350. metadata.is_first_in_list = true;
  1351. if (m_block)
  1352. m_block->highlight_in_editor(editor, shell, metadata);
  1353. }
  1354. HitTestResult Subshell::hit_test_position(size_t offset)
  1355. {
  1356. if (!position().contains(offset))
  1357. return {};
  1358. if (m_block)
  1359. return m_block->hit_test_position(offset);
  1360. return {};
  1361. }
  1362. Subshell::Subshell(Position position, RefPtr<Node> block)
  1363. : Node(move(position))
  1364. , m_block(block)
  1365. {
  1366. if (m_block && m_block->is_syntax_error())
  1367. set_is_syntax_error(m_block->syntax_error_node());
  1368. }
  1369. Subshell::~Subshell()
  1370. {
  1371. }
  1372. void SimpleVariable::dump(int level) const
  1373. {
  1374. Node::dump(level);
  1375. print_indented(m_name, level + 1);
  1376. }
  1377. RefPtr<Value> SimpleVariable::run(RefPtr<Shell>)
  1378. {
  1379. return create<SimpleVariableValue>(m_name);
  1380. }
  1381. void SimpleVariable::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  1382. {
  1383. Line::Style style { Line::Style::Foreground(214, 112, 214) };
  1384. if (metadata.is_first_in_list)
  1385. style.unify_with({ Line::Style::Bold });
  1386. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  1387. }
  1388. HitTestResult SimpleVariable::hit_test_position(size_t offset)
  1389. {
  1390. if (!position().contains(offset))
  1391. return {};
  1392. return { this, this, nullptr };
  1393. }
  1394. Vector<Line::CompletionSuggestion> SimpleVariable::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1395. {
  1396. auto matching_node = hit_test_result.matching_node;
  1397. if (!matching_node)
  1398. return {};
  1399. if (matching_node != this)
  1400. return {};
  1401. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  1402. if (corrected_offset > m_name.length() + 1)
  1403. return {};
  1404. return shell.complete_variable(m_name, corrected_offset);
  1405. }
  1406. SimpleVariable::SimpleVariable(Position position, String name)
  1407. : Node(move(position))
  1408. , m_name(move(name))
  1409. {
  1410. }
  1411. SimpleVariable::~SimpleVariable()
  1412. {
  1413. }
  1414. void SpecialVariable::dump(int level) const
  1415. {
  1416. Node::dump(level);
  1417. print_indented(String { &m_name, 1 }, level + 1);
  1418. }
  1419. RefPtr<Value> SpecialVariable::run(RefPtr<Shell>)
  1420. {
  1421. return create<SpecialVariableValue>(m_name);
  1422. }
  1423. void SpecialVariable::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  1424. {
  1425. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(214, 112, 214) });
  1426. }
  1427. Vector<Line::CompletionSuggestion> SpecialVariable::complete_for_editor(Shell&, size_t, const HitTestResult&)
  1428. {
  1429. return {};
  1430. }
  1431. HitTestResult SpecialVariable::hit_test_position(size_t offset)
  1432. {
  1433. if (!position().contains(offset))
  1434. return {};
  1435. return { this, this, nullptr };
  1436. }
  1437. SpecialVariable::SpecialVariable(Position position, char name)
  1438. : Node(move(position))
  1439. , m_name(name)
  1440. {
  1441. }
  1442. SpecialVariable::~SpecialVariable()
  1443. {
  1444. }
  1445. void Juxtaposition::dump(int level) const
  1446. {
  1447. Node::dump(level);
  1448. m_left->dump(level + 1);
  1449. m_right->dump(level + 1);
  1450. }
  1451. RefPtr<Value> Juxtaposition::run(RefPtr<Shell> shell)
  1452. {
  1453. auto left_value = m_left->run(shell)->resolve_without_cast(shell);
  1454. auto right_value = m_right->run(shell)->resolve_without_cast(shell);
  1455. auto left = left_value->resolve_as_list(shell);
  1456. auto right = right_value->resolve_as_list(shell);
  1457. if (left_value->is_string() && right_value->is_string()) {
  1458. ASSERT(left.size() == 1);
  1459. ASSERT(right.size() == 1);
  1460. StringBuilder builder;
  1461. builder.append(left[0]);
  1462. builder.append(right[0]);
  1463. return create<StringValue>(builder.to_string());
  1464. }
  1465. // Otherwise, treat them as lists and create a list product.
  1466. if (left.is_empty() || right.is_empty())
  1467. return create<ListValue>({});
  1468. Vector<String> result;
  1469. result.ensure_capacity(left.size() * right.size());
  1470. StringBuilder builder;
  1471. for (auto& left_element : left) {
  1472. for (auto& right_element : right) {
  1473. builder.append(left_element);
  1474. builder.append(right_element);
  1475. result.append(builder.to_string());
  1476. builder.clear();
  1477. }
  1478. }
  1479. return create<ListValue>(move(result));
  1480. }
  1481. void Juxtaposition::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1482. {
  1483. m_left->highlight_in_editor(editor, shell, metadata);
  1484. // '~/foo/bar' is special, we have to actually resolve the tilde
  1485. // since that resolution is a pure operation, we can just go ahead
  1486. // and do it to get the value :)
  1487. if (m_right->is_bareword() && m_left->is_tilde()) {
  1488. auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
  1489. auto bareword_value = m_right->run(shell)->resolve_as_list(shell)[0];
  1490. StringBuilder path_builder;
  1491. path_builder.append(tilde_value);
  1492. path_builder.append("/");
  1493. path_builder.append(bareword_value);
  1494. auto path = path_builder.to_string();
  1495. if (Core::File::exists(path)) {
  1496. auto realpath = shell.resolve_path(path);
  1497. auto url = URL::create_with_file_protocol(realpath);
  1498. url.set_host(shell.hostname);
  1499. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Hyperlink(url.to_string()) });
  1500. }
  1501. } else {
  1502. m_right->highlight_in_editor(editor, shell, metadata);
  1503. }
  1504. }
  1505. Vector<Line::CompletionSuggestion> Juxtaposition::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1506. {
  1507. auto matching_node = hit_test_result.matching_node;
  1508. // '~/foo/bar' is special, we have to actually resolve the tilde
  1509. // then complete the bareword with that path prefix.
  1510. if (m_right->is_bareword() && m_left->is_tilde()) {
  1511. auto tilde_value = m_left->run(shell)->resolve_as_list(shell)[0];
  1512. auto corrected_offset = offset - matching_node->position().start_offset;
  1513. auto* node = static_cast<BarewordLiteral*>(matching_node.ptr());
  1514. if (corrected_offset > node->text().length())
  1515. return {};
  1516. auto text = node->text().substring(1, node->text().length() - 1);
  1517. return shell.complete_path(tilde_value, text, corrected_offset - 1);
  1518. }
  1519. return Node::complete_for_editor(shell, offset, hit_test_result);
  1520. }
  1521. HitTestResult Juxtaposition::hit_test_position(size_t offset)
  1522. {
  1523. if (!position().contains(offset))
  1524. return {};
  1525. auto result = m_left->hit_test_position(offset);
  1526. if (!result.closest_node_with_semantic_meaning)
  1527. result.closest_node_with_semantic_meaning = this;
  1528. if (result.matching_node)
  1529. return result;
  1530. result = m_right->hit_test_position(offset);
  1531. if (!result.closest_node_with_semantic_meaning)
  1532. result.closest_node_with_semantic_meaning = this;
  1533. return result;
  1534. }
  1535. Juxtaposition::Juxtaposition(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1536. : Node(move(position))
  1537. , m_left(move(left))
  1538. , m_right(move(right))
  1539. {
  1540. if (m_left->is_syntax_error())
  1541. set_is_syntax_error(m_left->syntax_error_node());
  1542. else if (m_right->is_syntax_error())
  1543. set_is_syntax_error(m_right->syntax_error_node());
  1544. }
  1545. Juxtaposition::~Juxtaposition()
  1546. {
  1547. }
  1548. void StringLiteral::dump(int level) const
  1549. {
  1550. Node::dump(level);
  1551. print_indented(m_text, level + 1);
  1552. }
  1553. RefPtr<Value> StringLiteral::run(RefPtr<Shell>)
  1554. {
  1555. return create<StringValue>(m_text);
  1556. }
  1557. void StringLiteral::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata metadata)
  1558. {
  1559. Line::Style style { Line::Style::Foreground(Line::Style::XtermColor::Yellow) };
  1560. if (metadata.is_first_in_list)
  1561. style.unify_with({ Line::Style::Bold });
  1562. editor.stylize({ m_position.start_offset, m_position.end_offset }, move(style));
  1563. }
  1564. StringLiteral::StringLiteral(Position position, String text)
  1565. : Node(move(position))
  1566. , m_text(move(text))
  1567. {
  1568. }
  1569. StringLiteral::~StringLiteral()
  1570. {
  1571. }
  1572. void StringPartCompose::dump(int level) const
  1573. {
  1574. Node::dump(level);
  1575. m_left->dump(level + 1);
  1576. m_right->dump(level + 1);
  1577. }
  1578. RefPtr<Value> StringPartCompose::run(RefPtr<Shell> shell)
  1579. {
  1580. auto left = m_left->run(shell)->resolve_as_list(shell);
  1581. auto right = m_right->run(shell)->resolve_as_list(shell);
  1582. StringBuilder builder;
  1583. builder.join(" ", left);
  1584. builder.join(" ", right);
  1585. return create<StringValue>(builder.to_string());
  1586. }
  1587. void StringPartCompose::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1588. {
  1589. m_left->highlight_in_editor(editor, shell, metadata);
  1590. m_right->highlight_in_editor(editor, shell, metadata);
  1591. }
  1592. HitTestResult StringPartCompose::hit_test_position(size_t offset)
  1593. {
  1594. if (!position().contains(offset))
  1595. return {};
  1596. auto result = m_left->hit_test_position(offset);
  1597. if (result.matching_node)
  1598. return result;
  1599. return m_right->hit_test_position(offset);
  1600. }
  1601. StringPartCompose::StringPartCompose(Position position, RefPtr<Node> left, RefPtr<Node> right)
  1602. : Node(move(position))
  1603. , m_left(move(left))
  1604. , m_right(move(right))
  1605. {
  1606. if (m_left->is_syntax_error())
  1607. set_is_syntax_error(m_left->syntax_error_node());
  1608. else if (m_right->is_syntax_error())
  1609. set_is_syntax_error(m_right->syntax_error_node());
  1610. }
  1611. StringPartCompose::~StringPartCompose()
  1612. {
  1613. }
  1614. void SyntaxError::dump(int level) const
  1615. {
  1616. Node::dump(level);
  1617. }
  1618. RefPtr<Value> SyntaxError::run(RefPtr<Shell>)
  1619. {
  1620. dbg() << "SYNTAX ERROR AAAA";
  1621. return create<StringValue>("");
  1622. }
  1623. void SyntaxError::highlight_in_editor(Line::Editor& editor, Shell&, HighlightMetadata)
  1624. {
  1625. editor.stylize({ m_position.start_offset, m_position.end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Bold });
  1626. }
  1627. SyntaxError::SyntaxError(Position position, String error)
  1628. : Node(move(position))
  1629. , m_syntax_error_text(move(error))
  1630. {
  1631. m_is_syntax_error = true;
  1632. }
  1633. const SyntaxError& SyntaxError::syntax_error_node() const
  1634. {
  1635. return *this;
  1636. }
  1637. SyntaxError::~SyntaxError()
  1638. {
  1639. }
  1640. void Tilde::dump(int level) const
  1641. {
  1642. Node::dump(level);
  1643. print_indented(m_username, level + 1);
  1644. }
  1645. RefPtr<Value> Tilde::run(RefPtr<Shell>)
  1646. {
  1647. return create<TildeValue>(m_username);
  1648. }
  1649. void Tilde::highlight_in_editor(Line::Editor&, Shell&, HighlightMetadata)
  1650. {
  1651. }
  1652. HitTestResult Tilde::hit_test_position(size_t offset)
  1653. {
  1654. if (!position().contains(offset))
  1655. return {};
  1656. return { this, this, nullptr };
  1657. }
  1658. Vector<Line::CompletionSuggestion> Tilde::complete_for_editor(Shell& shell, size_t offset, const HitTestResult& hit_test_result)
  1659. {
  1660. auto matching_node = hit_test_result.matching_node;
  1661. if (!matching_node)
  1662. return {};
  1663. if (matching_node != this)
  1664. return {};
  1665. auto corrected_offset = offset - matching_node->position().start_offset - 1;
  1666. if (corrected_offset > m_username.length() + 1)
  1667. return {};
  1668. return shell.complete_user(m_username, corrected_offset);
  1669. }
  1670. String Tilde::text() const
  1671. {
  1672. StringBuilder builder;
  1673. builder.append('~');
  1674. builder.append(m_username);
  1675. return builder.to_string();
  1676. }
  1677. Tilde::Tilde(Position position, String username)
  1678. : Node(move(position))
  1679. , m_username(move(username))
  1680. {
  1681. }
  1682. Tilde::~Tilde()
  1683. {
  1684. }
  1685. void WriteAppendRedirection::dump(int level) const
  1686. {
  1687. Node::dump(level);
  1688. m_path->dump(level + 1);
  1689. print_indented(String::format("From %d", m_fd), level + 1);
  1690. }
  1691. RefPtr<Value> WriteAppendRedirection::run(RefPtr<Shell> shell)
  1692. {
  1693. Command command;
  1694. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1695. StringBuilder builder;
  1696. builder.join(" ", path_segments);
  1697. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::WriteAppend));
  1698. return create<CommandValue>(move(command));
  1699. }
  1700. WriteAppendRedirection::WriteAppendRedirection(Position position, int fd, RefPtr<Node> path)
  1701. : PathRedirectionNode(move(position), fd, move(path))
  1702. {
  1703. }
  1704. WriteAppendRedirection::~WriteAppendRedirection()
  1705. {
  1706. }
  1707. void WriteRedirection::dump(int level) const
  1708. {
  1709. Node::dump(level);
  1710. m_path->dump(level + 1);
  1711. print_indented(String::format("From %d", m_fd), level + 1);
  1712. }
  1713. RefPtr<Value> WriteRedirection::run(RefPtr<Shell> shell)
  1714. {
  1715. Command command;
  1716. auto path_segments = m_path->run(shell)->resolve_as_list(shell);
  1717. StringBuilder builder;
  1718. builder.join(" ", path_segments);
  1719. command.redirections.append(PathRedirection::create(builder.to_string(), m_fd, PathRedirection::Write));
  1720. return create<CommandValue>(move(command));
  1721. }
  1722. WriteRedirection::WriteRedirection(Position position, int fd, RefPtr<Node> path)
  1723. : PathRedirectionNode(move(position), fd, move(path))
  1724. {
  1725. }
  1726. WriteRedirection::~WriteRedirection()
  1727. {
  1728. }
  1729. void VariableDeclarations::dump(int level) const
  1730. {
  1731. Node::dump(level);
  1732. for (auto& var : m_variables) {
  1733. print_indented("Set", level + 1);
  1734. var.name->dump(level + 2);
  1735. var.value->dump(level + 2);
  1736. }
  1737. }
  1738. RefPtr<Value> VariableDeclarations::run(RefPtr<Shell> shell)
  1739. {
  1740. for (auto& var : m_variables) {
  1741. auto name_value = var.name->run(shell)->resolve_as_list(shell);
  1742. ASSERT(name_value.size() == 1);
  1743. auto name = name_value[0];
  1744. auto value = var.value->run(shell);
  1745. if (value->is_list()) {
  1746. auto parts = value->resolve_as_list(shell);
  1747. shell->set_local_variable(name, adopt(*new ListValue(move(parts))));
  1748. } else if (value->is_command()) {
  1749. shell->set_local_variable(name, value);
  1750. } else {
  1751. auto part = value->resolve_as_list(shell);
  1752. shell->set_local_variable(name, adopt(*new StringValue(part[0])));
  1753. }
  1754. }
  1755. return create<ListValue>({});
  1756. }
  1757. void VariableDeclarations::highlight_in_editor(Line::Editor& editor, Shell& shell, HighlightMetadata metadata)
  1758. {
  1759. metadata.is_first_in_list = false;
  1760. for (auto& var : m_variables) {
  1761. var.name->highlight_in_editor(editor, shell, metadata);
  1762. // Highlight the '='.
  1763. editor.stylize({ var.name->position().end_offset - 1, var.name->position().end_offset }, { Line::Style::Foreground(Line::Style::XtermColor::Blue) });
  1764. var.value->highlight_in_editor(editor, shell, metadata);
  1765. }
  1766. }
  1767. HitTestResult VariableDeclarations::hit_test_position(size_t offset)
  1768. {
  1769. if (!position().contains(offset))
  1770. return {};
  1771. for (auto decl : m_variables) {
  1772. auto result = decl.value->hit_test_position(offset);
  1773. if (result.matching_node)
  1774. return result;
  1775. }
  1776. return { nullptr, nullptr, nullptr };
  1777. }
  1778. VariableDeclarations::VariableDeclarations(Position position, Vector<Variable> variables)
  1779. : Node(move(position))
  1780. , m_variables(move(variables))
  1781. {
  1782. for (auto& decl : m_variables) {
  1783. if (decl.name->is_syntax_error()) {
  1784. set_is_syntax_error(decl.name->syntax_error_node());
  1785. break;
  1786. }
  1787. if (decl.value->is_syntax_error()) {
  1788. set_is_syntax_error(decl.value->syntax_error_node());
  1789. break;
  1790. }
  1791. }
  1792. }
  1793. VariableDeclarations::~VariableDeclarations()
  1794. {
  1795. }
  1796. Value::~Value()
  1797. {
  1798. }
  1799. Vector<AST::Command> Value::resolve_as_commands(RefPtr<Shell> shell)
  1800. {
  1801. Command command;
  1802. command.argv = resolve_as_list(shell);
  1803. return { command };
  1804. }
  1805. ListValue::ListValue(Vector<String> values)
  1806. {
  1807. m_contained_values.ensure_capacity(values.size());
  1808. for (auto& str : values)
  1809. m_contained_values.append(adopt(*new StringValue(move(str))));
  1810. }
  1811. ListValue::~ListValue()
  1812. {
  1813. }
  1814. Vector<String> ListValue::resolve_as_list(RefPtr<Shell> shell)
  1815. {
  1816. Vector<String> values;
  1817. for (auto& value : m_contained_values)
  1818. values.append(value.resolve_as_list(shell));
  1819. return values;
  1820. }
  1821. NonnullRefPtr<Value> ListValue::resolve_without_cast(RefPtr<Shell> shell)
  1822. {
  1823. NonnullRefPtrVector<Value> values;
  1824. for (auto& value : m_contained_values)
  1825. values.append(value.resolve_without_cast(shell));
  1826. return create<ListValue>(move(values));
  1827. }
  1828. CommandValue::~CommandValue()
  1829. {
  1830. }
  1831. CommandSequenceValue::~CommandSequenceValue()
  1832. {
  1833. }
  1834. Vector<String> CommandSequenceValue::resolve_as_list(RefPtr<Shell>)
  1835. {
  1836. // TODO: Somehow raise an "error".
  1837. return {};
  1838. }
  1839. Vector<Command> CommandSequenceValue::resolve_as_commands(RefPtr<Shell>)
  1840. {
  1841. return m_contained_values;
  1842. }
  1843. Vector<String> CommandValue::resolve_as_list(RefPtr<Shell>)
  1844. {
  1845. // TODO: Somehow raise an "error".
  1846. return {};
  1847. }
  1848. Vector<Command> CommandValue::resolve_as_commands(RefPtr<Shell>)
  1849. {
  1850. return { m_command };
  1851. }
  1852. JobValue::~JobValue()
  1853. {
  1854. }
  1855. StringValue::~StringValue()
  1856. {
  1857. }
  1858. Vector<String> StringValue::resolve_as_list(RefPtr<Shell>)
  1859. {
  1860. if (is_list()) {
  1861. auto parts = StringView(m_string).split_view(m_split, m_keep_empty);
  1862. Vector<String> result;
  1863. result.ensure_capacity(parts.size());
  1864. for (auto& part : parts)
  1865. result.append(part);
  1866. return result;
  1867. }
  1868. return { m_string };
  1869. }
  1870. GlobValue::~GlobValue()
  1871. {
  1872. }
  1873. Vector<String> GlobValue::resolve_as_list(RefPtr<Shell> shell)
  1874. {
  1875. return shell->expand_globs(m_glob, shell->cwd);
  1876. }
  1877. SimpleVariableValue::~SimpleVariableValue()
  1878. {
  1879. }
  1880. Vector<String> SimpleVariableValue::resolve_as_list(RefPtr<Shell> shell)
  1881. {
  1882. if (auto value = resolve_without_cast(shell); value != this)
  1883. return value->resolve_as_list(shell);
  1884. char* env_value = getenv(m_name.characters());
  1885. if (env_value == nullptr)
  1886. return { "" };
  1887. Vector<String> res;
  1888. String str_env_value = String(env_value);
  1889. const auto& split_text = str_env_value.split_view(' ');
  1890. for (auto& part : split_text)
  1891. res.append(part);
  1892. return res;
  1893. }
  1894. NonnullRefPtr<Value> SimpleVariableValue::resolve_without_cast(RefPtr<Shell> shell)
  1895. {
  1896. if (auto value = shell->lookup_local_variable(m_name))
  1897. return value.release_nonnull();
  1898. return *this;
  1899. }
  1900. SpecialVariableValue::~SpecialVariableValue()
  1901. {
  1902. }
  1903. Vector<String> SpecialVariableValue::resolve_as_list(RefPtr<Shell> shell)
  1904. {
  1905. switch (m_name) {
  1906. case '?':
  1907. return { String::number(shell->last_return_code) };
  1908. case '$':
  1909. return { String::number(getpid()) };
  1910. case '*':
  1911. if (auto argv = shell->lookup_local_variable("ARGV"))
  1912. return argv->resolve_as_list(shell);
  1913. return {};
  1914. case '#':
  1915. if (auto argv = shell->lookup_local_variable("ARGV")) {
  1916. if (argv->is_list()) {
  1917. auto list_argv = static_cast<AST::ListValue*>(argv.ptr());
  1918. return { String::number(list_argv->values().size()) };
  1919. }
  1920. return { "1" };
  1921. }
  1922. return { "0" };
  1923. default:
  1924. return { "" };
  1925. }
  1926. }
  1927. TildeValue::~TildeValue()
  1928. {
  1929. }
  1930. Vector<String> TildeValue::resolve_as_list(RefPtr<Shell> shell)
  1931. {
  1932. StringBuilder builder;
  1933. builder.append("~");
  1934. builder.append(m_username);
  1935. return { shell->expand_tilde(builder.to_string()) };
  1936. }
  1937. Result<NonnullRefPtr<Rewiring>, String> CloseRedirection::apply() const
  1938. {
  1939. return adopt(*new Rewiring(fd, fd, Rewiring::Close::ImmediatelyCloseDestination));
  1940. }
  1941. CloseRedirection::~CloseRedirection()
  1942. {
  1943. }
  1944. Result<NonnullRefPtr<Rewiring>, String> PathRedirection::apply() const
  1945. {
  1946. auto check_fd_and_return = [my_fd = this->fd](int fd, const String& path) -> Result<NonnullRefPtr<Rewiring>, String> {
  1947. if (fd < 0) {
  1948. String error = strerror(errno);
  1949. dbg() << "open() failed for '" << path << "' with " << error;
  1950. return error;
  1951. }
  1952. return adopt(*new Rewiring(my_fd, fd, Rewiring::Close::Destination));
  1953. };
  1954. switch (direction) {
  1955. case AST::PathRedirection::WriteAppend:
  1956. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_APPEND, 0666), path);
  1957. case AST::PathRedirection::Write:
  1958. return check_fd_and_return(open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666), path);
  1959. case AST::PathRedirection::Read:
  1960. return check_fd_and_return(open(path.characters(), O_RDONLY), path);
  1961. case AST::PathRedirection::ReadWrite:
  1962. return check_fd_and_return(open(path.characters(), O_RDWR | O_CREAT, 0666), path);
  1963. }
  1964. ASSERT_NOT_REACHED();
  1965. }
  1966. PathRedirection::~PathRedirection()
  1967. {
  1968. }
  1969. FdRedirection::~FdRedirection()
  1970. {
  1971. }
  1972. Redirection::~Redirection()
  1973. {
  1974. }
  1975. }