AST.cpp 75 KB

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