2 // repl.cs: Support for using the compiler in interactive mode (read-eval-print loop)
5 // Miguel de Icaza (miguel@gnome.org)
7 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
10 // Copyright 2004, 2005, 2006, 2007, 2008 Novell, Inc
11 // Copyright 2011-2013 Xamarin Inc
15 // Do not print results in Evaluate, do that elsewhere in preparation for Eval refactoring.
16 // Driver.PartialReset should not reset the coretypes, nor the optional types, to avoid
17 // computing that on every call.
22 using System.Globalization;
23 using System.Collections;
24 using System.Reflection;
25 using System.Reflection.Emit;
26 using System.Threading;
28 using System.Net.Sockets;
29 using System.Collections.Generic;
36 public static string StartupEvalExpression;
38 static string target_host;
39 static int target_port;
42 static int Main (string [] args)
44 var cmd = new CommandLineParser (Console.Out);
45 cmd.UnknownOptionHandler += HandleExtraArguments;
47 // Enable unsafe code by default
48 var settings = new CompilerSettings () {
52 if (!cmd.ParseArguments (settings, args))
55 var startup_files = new string [settings.SourceFiles.Count];
57 foreach (var source in settings.SourceFiles)
58 startup_files [i++] = source.FullPathName;
59 settings.SourceFiles.Clear ();
61 TextWriter agent_stderr = null;
62 ReportPrinter printer;
64 agent_stderr = new StringWriter ();
65 printer = new StreamReportPrinter (agent_stderr);
67 printer = new ConsoleReportPrinter ();
70 var eval = new Evaluator (new CompilerContext (settings, printer));
72 eval.InteractiveBaseClass = typeof (InteractiveBaseShell);
73 eval.DescribeTypeExpressions = true;
74 eval.WaitOnTask = true;
78 if (attach.HasValue) {
79 shell = new ClientCSharpShell_v1 (eval, attach.Value);
80 } else if (agent != null) {
81 new CSharpAgent (eval, agent, agent_stderr).Run (startup_files);
85 if (target_host != null)
86 shell = new ClientCSharpShell (eval, target_host, target_port);
88 shell = new CSharpShell (eval);
90 return shell.Run (startup_files);
93 static int HandleExtraArguments (string [] args, int pos)
97 if (pos + 1 < args.Length) {
98 StartupEvalExpression = args[pos + 1];
103 if (pos + 1 < args.Length) {
104 attach = Int32.Parse (args[1]);
109 if (args [pos].StartsWith ("--server=")){
110 var hostport = args [pos].Substring (9);
111 int p = hostport.IndexOf (':');
113 target_host = hostport;
116 target_host = hostport.Substring (0,p);
117 if (!int.TryParse (hostport.Substring (p), out target_port)){
118 Console.Error.WriteLine ("Usage is: --server[=host[:port]");
119 Environment.Exit (1);
124 if (args [pos].StartsWith ("--client")){
125 target_host = "localhost";
129 if (args [pos].StartsWith ("--agent:")) {
141 public class InteractiveBaseShell : InteractiveBase {
142 static bool tab_at_start_completes;
144 static InteractiveBaseShell ()
146 tab_at_start_completes = false;
149 internal static Mono.Terminal.LineEditor Editor;
151 public static bool TabAtStartCompletes {
153 return tab_at_start_completes;
157 tab_at_start_completes = value;
159 Editor.TabAtStartCompletes = value;
163 public static new string help {
165 return InteractiveBase.help +
166 " TabAtStartCompletes - Whether tab will complete even on empty lines\n";
171 public class CSharpShell {
172 static bool isatty = true, is_unix = false;
173 protected string [] startup_files;
175 Mono.Terminal.LineEditor editor;
177 readonly Evaluator evaluator;
179 public CSharpShell (Evaluator evaluator)
181 this.evaluator = evaluator;
184 protected virtual void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a)
186 // Do not about our program
189 evaluator.Interrupt ();
195 string term = Environment.GetEnvironmentVariable ("TERM");
196 dumb = term == "dumb" || term == null || isatty == false;
200 editor = new Mono.Terminal.LineEditor ("csharp", 300);
201 InteractiveBaseShell.Editor = editor;
203 editor.AutoCompleteEvent += delegate (string s, int pos){
204 string prefix = null;
206 string complete = s.Substring (0, pos);
208 string [] completions = evaluator.GetCompletions (complete, out prefix);
210 return new Mono.Terminal.LineEditor.Completion (prefix, completions);
215 // This is a sample of how completions sould be implemented.
217 editor.AutoCompleteEvent += delegate (string s, int pos){
219 // Single match: "Substring": Sub-string
220 if (s.EndsWith ("Sub")){
221 return new string [] { "string" };
224 // Multiple matches: "ToString" and "ToLower"
225 if (s.EndsWith ("T")){
226 return new string [] { "ToString", "ToLower" };
232 Console.CancelKeyPress += ConsoleInterrupt;
235 string GetLine (bool primary)
237 string prompt = primary ? InteractiveBase.Prompt : InteractiveBase.ContinuationPrompt;
241 Console.Write (prompt);
243 return Console.ReadLine ();
245 return editor.Edit (prompt, "");
249 delegate string ReadLiner (bool primary);
251 void InitializeUsing ()
253 Evaluate ("using System; using System.Linq; using System.Collections.Generic; using System.Collections;");
256 void InitTerminal (bool show_banner)
258 int p = (int) Environment.OSVersion.Platform;
259 is_unix = (p == 4) || (p == 128);
261 isatty = !Console.IsInputRedirected && !Console.IsOutputRedirected;
263 // Work around, since Console is not accounting for
264 // cursor position when writing to Stderr. It also
265 // has the undesirable side effect of making
266 // errors plain, with no coloring.
267 // Report.Stderr = Console.Out;
270 if (isatty && show_banner)
271 Console.WriteLine ("Mono C# Shell, type \"help;\" for help\n\nEnter statements below.");
275 void ExecuteSources (IEnumerable<string> sources, bool ignore_errors)
277 foreach (string file in sources){
282 using (System.IO.StreamReader r = System.IO.File.OpenText (file)){
283 ReadEvalPrintLoopWith (p => {
284 var line = r.ReadLine ();
286 if (line.StartsWith ("#!"))
287 line = r.ReadLine ();
293 } catch (FileNotFoundException){
294 Console.Error.WriteLine ("cs2001: Source file `{0}' not found", file);
304 protected virtual void LoadStartupFiles ()
306 string dir = Path.Combine (
307 Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData),
309 if (!Directory.Exists (dir))
312 List<string> sources = new List<string> ();
313 List<string> libraries = new List<string> ();
315 foreach (string file in System.IO.Directory.GetFiles (dir)){
316 string l = file.ToLower ();
318 if (l.EndsWith (".cs"))
320 else if (l.EndsWith (".dll"))
321 libraries.Add (file);
324 foreach (string file in libraries)
325 evaluator.LoadAssembly (file);
327 ExecuteSources (sources, true);
330 void ReadEvalPrintLoopWith (ReadLiner readline)
333 while (!InteractiveBase.QuitRequested){
334 string input = readline (expr == null);
341 expr = expr == null ? input : expr + "\n" + input;
343 expr = Evaluate (expr);
347 public int ReadEvalPrintLoop ()
349 if (startup_files != null && startup_files.Length == 0)
350 InitTerminal (startup_files.Length == 0 && Driver.StartupEvalExpression == null);
356 if (startup_files != null && startup_files.Length != 0) {
357 ExecuteSources (startup_files, false);
359 if (Driver.StartupEvalExpression != null){
360 ReadEvalPrintLoopWith (p => {
361 var ret = Driver.StartupEvalExpression;
362 Driver.StartupEvalExpression = null;
366 ReadEvalPrintLoopWith (GetLine);
369 editor.SaveHistory ();
372 Console.CancelKeyPress -= ConsoleInterrupt;
377 protected virtual string Evaluate (string input)
383 input = evaluator.Evaluate (input, out result, out result_set);
386 PrettyPrint (Console.Out, result);
387 Console.WriteLine ();
389 } catch (Exception e){
390 Console.WriteLine (e);
397 static void p (TextWriter output, string s)
402 static string EscapeString (string s)
404 return s.Replace ("\"", "\\\"");
407 static void EscapeChar (TextWriter output, char c)
410 output.Write ("'\\''");
414 output.Write ("'{0}'", c);
419 output.Write ("'\\a'");
423 output.Write ("'\\b'");
427 output.Write ("'\\n'");
431 output.Write ("'\\v'");
435 output.Write ("'\\r'");
439 output.Write ("'\\f'");
443 output.Write ("'\\t");
447 output.Write ("'\\x{0:x}", (int) c);
452 // Some types (System.Json.JsonPrimitive) implement
453 // IEnumerator and yet, throw an exception when we
454 // try to use them, helper function to check for that
456 static internal bool WorksAsEnumerable (object obj)
458 IEnumerable enumerable = obj as IEnumerable;
459 if (enumerable != null){
461 enumerable.GetEnumerator ();
464 // nothing, we return false below
470 internal static void PrettyPrint (TextWriter output, object result)
477 if (result is Array){
478 Array a = (Array) result;
481 int top = a.GetUpperBound (0);
482 for (int i = a.GetLowerBound (0); i <= top; i++){
483 PrettyPrint (output, a.GetValue (i));
488 } else if (result is bool){
493 } else if (result is string){
494 p (output, String.Format ("\"{0}\"", EscapeString ((string)result)));
495 } else if (result is IDictionary){
496 IDictionary dict = (IDictionary) result;
497 int top = dict.Count, count = 0;
500 foreach (DictionaryEntry entry in dict){
503 PrettyPrint (output, entry.Key);
505 PrettyPrint (output, entry.Value);
512 } else if (WorksAsEnumerable (result)) {
515 foreach (object item in (IEnumerable) result) {
519 PrettyPrint (output, item);
522 } else if (result is char) {
523 EscapeChar (output, (char) result);
525 p (output, result.ToString ());
529 public virtual int Run (string [] startup_files)
531 this.startup_files = startup_files;
532 return ReadEvalPrintLoop ();
538 // Stream helper extension methods
540 public static class StreamHelper {
541 static DataConverter converter = DataConverter.LittleEndian;
543 static void GetBuffer (this Stream stream, byte [] b)
549 n = stream.Read (b, offset, len);
551 throw new IOException ("End reached");
558 public static int GetInt (this Stream stream)
560 byte [] b = new byte [4];
561 stream.GetBuffer (b);
562 return converter.GetInt32 (b, 0);
565 public static string GetString (this Stream stream)
567 int len = stream.GetInt ();
571 byte [] b = new byte [len];
572 stream.GetBuffer (b);
574 return Encoding.UTF8.GetString (b);
577 public static void WriteInt (this Stream stream, int n)
579 byte [] bytes = converter.GetBytes (n);
580 stream.Write (bytes, 0, bytes.Length);
583 public static void WriteString (this Stream stream, string s)
585 stream.WriteInt (s.Length);
586 byte [] bytes = Encoding.UTF8.GetBytes (s);
587 stream.Write (bytes, 0, bytes.Length);
591 public enum AgentStatus : byte {
592 // Received partial input, complete
595 // The result was set, expect the string with the result
598 // No result was set, complete
601 // Errors and warnings string follows
608 class ClientCSharpShell : CSharpShell {
612 public ClientCSharpShell (Evaluator evaluator, string target_host, int target_port) : base (evaluator)
614 this.target_port = target_port;
615 this.target_host = target_host;
618 T ConnectServer<T> (Func<NetworkStream,T> callback, Action<Exception> error)
621 var client = new TcpClient (target_host, target_port);
622 var ns = client.GetStream ();
623 T ret = callback (ns);
628 } catch (Exception e){
634 protected override string Evaluate (string input)
636 return ConnectServer<string> ((ns)=> {
638 ns.WriteString ("EVALTXT");
639 ns.WriteString (input);
642 AgentStatus s = (AgentStatus) ns.ReadByte ();
645 case AgentStatus.PARTIAL_INPUT:
648 case AgentStatus.ERROR:
649 string err = ns.GetString ();
650 Console.Error.WriteLine (err);
653 case AgentStatus.STDOUT:
654 string stdout = ns.GetString ();
655 Console.WriteLine (stdout);
658 case AgentStatus.RESULT_NOT_SET:
661 case AgentStatus.RESULT_SET:
662 string res = ns.GetString ();
663 Console.WriteLine (res);
667 } catch (Exception e){
668 Console.Error.WriteLine ("Error evaluating expression, exception: {0}", e);
672 Console.Error.WriteLine ("Error communicating with server {0}", e);
676 public override int Run (string [] startup_files)
678 // The difference is that we do not call Evaluator.Init, that is done on the target
679 this.startup_files = startup_files;
680 return ReadEvalPrintLoop ();
683 protected override void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a)
685 ConnectServer<int> ((ns)=> {
686 ns.WriteString ("INTERRUPT");
695 // A shell connected to a CSharpAgent running in a remote process.
696 // - maybe add 'class_name' and 'method_name' arguments to LoadAgent.
697 // - Support Gtk and Winforms main loops if detected, this should
698 // probably be done as a separate agent in a separate place.
700 class ClientCSharpShell_v1 : CSharpShell {
701 NetworkStream ns, interrupt_stream;
703 public ClientCSharpShell_v1 (Evaluator evaluator, int pid)
706 // Create a server socket we listen on whose address is passed to the agent
707 TcpListener listener = new TcpListener (new IPEndPoint (IPAddress.Loopback, 0));
709 TcpListener interrupt_listener = new TcpListener (new IPEndPoint (IPAddress.Loopback, 0));
710 interrupt_listener.Start ();
712 string agent_assembly = typeof (ClientCSharpShell).Assembly.Location;
713 string agent_arg = String.Format ("--agent:{0}:{1}" ,
714 ((IPEndPoint)listener.Server.LocalEndPoint).Port,
715 ((IPEndPoint)interrupt_listener.Server.LocalEndPoint).Port);
717 var vm = new Attach.VirtualMachine (pid);
718 vm.Attach (agent_assembly, agent_arg);
720 /* Wait for the client to connect */
721 TcpClient client = listener.AcceptTcpClient ();
722 ns = client.GetStream ();
723 TcpClient interrupt_client = interrupt_listener.AcceptTcpClient ();
724 interrupt_stream = interrupt_client.GetStream ();
726 Console.WriteLine ("Connected.");
730 // A remote version of Evaluate
732 protected override string Evaluate (string input)
734 ns.WriteString (input);
736 AgentStatus s = (AgentStatus) ns.ReadByte ();
739 case AgentStatus.PARTIAL_INPUT:
742 case AgentStatus.ERROR:
743 string err = ns.GetString ();
744 Console.Error.WriteLine (err);
747 case AgentStatus.RESULT_NOT_SET:
750 case AgentStatus.RESULT_SET:
751 string res = ns.GetString ();
752 Console.WriteLine (res);
758 public override int Run (string [] startup_files)
760 // The difference is that we do not call Evaluator.Init, that is done on the target
761 this.startup_files = startup_files;
762 return ReadEvalPrintLoop ();
765 protected override void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a)
767 // Do not about our program
770 interrupt_stream.WriteByte (0);
771 int c = interrupt_stream.ReadByte ();
773 Console.WriteLine ("Execution interrupted");
779 // This is the agent loaded into the target process when using --attach.
783 NetworkStream interrupt_stream;
784 readonly Evaluator evaluator;
787 public CSharpAgent (Evaluator evaluator, String arg, TextWriter stderr)
789 this.evaluator = evaluator;
790 this.stderr = stderr;
791 new Thread (new ParameterizedThreadStart (Run)).Start (arg);
794 public void InterruptListener ()
797 int b = interrupt_stream.ReadByte();
800 evaluator.Interrupt ();
801 interrupt_stream.WriteByte (0);
805 public void Run (object o)
807 string arg = (string)o;
808 string ports = arg.Substring (8);
809 int sp = ports.IndexOf (':');
810 int port = Int32.Parse (ports.Substring (0, sp));
811 int interrupt_port = Int32.Parse (ports.Substring (sp+1));
813 Console.WriteLine ("csharp-agent: started, connecting to localhost:" + port);
815 TcpClient client = new TcpClient ("127.0.0.1", port);
816 TcpClient interrupt_client = new TcpClient ("127.0.0.1", interrupt_port);
817 Console.WriteLine ("csharp-agent: connected.");
819 NetworkStream s = client.GetStream ();
820 interrupt_stream = interrupt_client.GetStream ();
821 new Thread (InterruptListener).Start ();
824 // Add all assemblies loaded later
825 AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoaded;
827 // Add all currently loaded assemblies
828 foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) {
829 // Some assemblies seem to be already loaded, and loading them again causes 'defined multiple times' errors
830 if (a.GetName ().Name != "mscorlib" && a.GetName ().Name != "System.Core" && a.GetName ().Name != "System")
831 evaluator.ReferenceAssembly (a);
836 AppDomain.CurrentDomain.AssemblyLoad -= AssemblyLoaded;
838 interrupt_client.Close ();
839 Console.WriteLine ("csharp-agent: disconnected.");
843 void AssemblyLoaded (object sender, AssemblyLoadEventArgs e)
845 evaluator.ReferenceAssembly (e.LoadedAssembly);
848 public void RunRepl (NetworkStream s)
852 while (!InteractiveBase.QuitRequested) {
855 StringWriter error_output = (StringWriter)stderr;
857 string line = s.GetString ();
865 input = input + "\n" + line;
868 input = evaluator.Evaluate (input, out result, out result_set);
869 } catch (Exception e) {
870 s.WriteByte ((byte) AgentStatus.ERROR);
871 s.WriteString (e.ToString ());
872 s.WriteByte ((byte) AgentStatus.RESULT_NOT_SET);
877 s.WriteByte ((byte) AgentStatus.PARTIAL_INPUT);
881 // Send warnings and errors back
882 error_string = error_output.ToString ();
883 if (error_string.Length != 0){
884 s.WriteByte ((byte) AgentStatus.ERROR);
885 s.WriteString (error_output.ToString ());
886 error_output.GetStringBuilder ().Clear ();
890 s.WriteByte ((byte) AgentStatus.RESULT_SET);
891 StringWriter sr = new StringWriter ();
892 CSharpShell.PrettyPrint (sr, result);
893 s.WriteString (sr.ToString ());
895 s.WriteByte ((byte) AgentStatus.RESULT_NOT_SET);
897 } catch (IOException) {
899 } catch (Exception e){
900 Console.WriteLine (e);
906 public class UnixUtils {
907 [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
908 extern static int _isatty (int fd);
910 public static bool isatty (int fd)
913 return _isatty (fd) == 1;
922 namespace Mono.Management
924 interface IVirtualMachine {
925 void LoadAgent (string filename, string args);