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);
262 isatty = !Console.IsInputRedirected && !Console.IsOutputRedirected;
267 // Work around, since Console is not accounting for
268 // cursor position when writing to Stderr. It also
269 // has the undesirable side effect of making
270 // errors plain, with no coloring.
271 // Report.Stderr = Console.Out;
274 if (isatty && show_banner)
275 Console.WriteLine ("Mono C# Shell, type \"help;\" for help\n\nEnter statements below.");
279 void ExecuteSources (IEnumerable<string> sources, bool ignore_errors)
281 foreach (string file in sources){
286 using (System.IO.StreamReader r = System.IO.File.OpenText (file)){
287 ReadEvalPrintLoopWith (p => {
288 var line = r.ReadLine ();
290 if (line.StartsWith ("#!"))
291 line = r.ReadLine ();
297 } catch (FileNotFoundException){
298 Console.Error.WriteLine ("cs2001: Source file `{0}' not found", file);
308 protected virtual void LoadStartupFiles ()
310 string dir = Path.Combine (
311 Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData),
313 if (!Directory.Exists (dir))
316 List<string> sources = new List<string> ();
317 List<string> libraries = new List<string> ();
319 foreach (string file in System.IO.Directory.GetFiles (dir)){
320 string l = file.ToLower ();
322 if (l.EndsWith (".cs"))
324 else if (l.EndsWith (".dll"))
325 libraries.Add (file);
328 foreach (string file in libraries)
329 evaluator.LoadAssembly (file);
331 ExecuteSources (sources, true);
334 void ReadEvalPrintLoopWith (ReadLiner readline)
337 while (!InteractiveBase.QuitRequested){
338 string input = readline (expr == null);
345 expr = expr == null ? input : expr + "\n" + input;
347 expr = Evaluate (expr);
351 public int ReadEvalPrintLoop ()
353 if (startup_files != null && startup_files.Length == 0)
354 InitTerminal (startup_files.Length == 0 && Driver.StartupEvalExpression == null);
360 if (startup_files != null && startup_files.Length != 0) {
361 ExecuteSources (startup_files, false);
363 if (Driver.StartupEvalExpression != null){
364 ReadEvalPrintLoopWith (p => {
365 var ret = Driver.StartupEvalExpression;
366 Driver.StartupEvalExpression = null;
370 ReadEvalPrintLoopWith (GetLine);
373 editor.SaveHistory ();
376 Console.CancelKeyPress -= ConsoleInterrupt;
381 protected virtual string Evaluate (string input)
387 input = evaluator.Evaluate (input, out result, out result_set);
390 PrettyPrint (Console.Out, result);
391 Console.WriteLine ();
393 } catch (Exception e){
394 Console.WriteLine (e);
401 static void p (TextWriter output, string s)
406 static string EscapeString (string s)
408 return s.Replace ("\"", "\\\"");
411 static void EscapeChar (TextWriter output, char c)
414 output.Write ("'\\''");
418 output.Write ("'{0}'", c);
423 output.Write ("'\\a'");
427 output.Write ("'\\b'");
431 output.Write ("'\\n'");
435 output.Write ("'\\v'");
439 output.Write ("'\\r'");
443 output.Write ("'\\f'");
447 output.Write ("'\\t");
451 output.Write ("'\\x{0:x}", (int) c);
456 // Some types (System.Json.JsonPrimitive) implement
457 // IEnumerator and yet, throw an exception when we
458 // try to use them, helper function to check for that
460 static internal bool WorksAsEnumerable (object obj)
462 IEnumerable enumerable = obj as IEnumerable;
463 if (enumerable != null){
465 enumerable.GetEnumerator ();
468 // nothing, we return false below
474 internal static void PrettyPrint (TextWriter output, object result)
481 if (result is Array){
482 Array a = (Array) result;
485 int top = a.GetUpperBound (0);
486 for (int i = a.GetLowerBound (0); i <= top; i++){
487 PrettyPrint (output, a.GetValue (i));
492 } else if (result is bool){
497 } else if (result is string){
498 p (output, String.Format ("\"{0}\"", EscapeString ((string)result)));
499 } else if (result is IDictionary){
500 IDictionary dict = (IDictionary) result;
501 int top = dict.Count, count = 0;
504 foreach (DictionaryEntry entry in dict){
507 PrettyPrint (output, entry.Key);
509 PrettyPrint (output, entry.Value);
516 } else if (WorksAsEnumerable (result)) {
519 foreach (object item in (IEnumerable) result) {
523 PrettyPrint (output, item);
526 } else if (result is char) {
527 EscapeChar (output, (char) result);
529 p (output, result.ToString ());
533 public virtual int Run (string [] startup_files)
535 this.startup_files = startup_files;
536 return ReadEvalPrintLoop ();
542 // Stream helper extension methods
544 public static class StreamHelper {
545 static DataConverter converter = DataConverter.LittleEndian;
547 static void GetBuffer (this Stream stream, byte [] b)
553 n = stream.Read (b, offset, len);
555 throw new IOException ("End reached");
562 public static int GetInt (this Stream stream)
564 byte [] b = new byte [4];
565 stream.GetBuffer (b);
566 return converter.GetInt32 (b, 0);
569 public static string GetString (this Stream stream)
571 int len = stream.GetInt ();
575 byte [] b = new byte [len];
576 stream.GetBuffer (b);
578 return Encoding.UTF8.GetString (b);
581 public static void WriteInt (this Stream stream, int n)
583 byte [] bytes = converter.GetBytes (n);
584 stream.Write (bytes, 0, bytes.Length);
587 public static void WriteString (this Stream stream, string s)
589 stream.WriteInt (s.Length);
590 byte [] bytes = Encoding.UTF8.GetBytes (s);
591 stream.Write (bytes, 0, bytes.Length);
595 public enum AgentStatus : byte {
596 // Received partial input, complete
599 // The result was set, expect the string with the result
602 // No result was set, complete
605 // Errors and warnings string follows
609 class ClientCSharpShell : CSharpShell {
613 public ClientCSharpShell (Evaluator evaluator, string target_host, int target_port) : base (evaluator)
615 this.target_port = target_port;
616 this.target_host = target_host;
619 T ConnectServer<T> (Func<NetworkStream,T> callback, Action<Exception> error)
622 var client = new TcpClient (target_host, target_port);
623 var ns = client.GetStream ();
624 T ret = callback (ns);
629 } catch (Exception e){
635 protected override string Evaluate (string input)
637 return ConnectServer<string> ((ns)=> {
639 ns.WriteString ("EVALTXT");
640 ns.WriteString (input);
643 AgentStatus s = (AgentStatus) ns.ReadByte ();
646 case AgentStatus.PARTIAL_INPUT:
649 case AgentStatus.ERROR:
650 string err = ns.GetString ();
651 Console.Error.WriteLine (err);
654 case AgentStatus.RESULT_NOT_SET:
657 case AgentStatus.RESULT_SET:
658 string res = ns.GetString ();
659 Console.WriteLine (res);
663 } catch (Exception e){
664 Console.Error.WriteLine ("Error evaluating expression, exception: {0}", e);
668 Console.Error.WriteLine ("Error communicating with server {0}", e);
672 public override int Run (string [] startup_files)
674 // The difference is that we do not call Evaluator.Init, that is done on the target
675 this.startup_files = startup_files;
676 return ReadEvalPrintLoop ();
679 protected override void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a)
681 ConnectServer<int> ((ns)=> {
682 ns.WriteString ("INTERRUPT");
691 // A shell connected to a CSharpAgent running in a remote process.
692 // - maybe add 'class_name' and 'method_name' arguments to LoadAgent.
693 // - Support Gtk and Winforms main loops if detected, this should
694 // probably be done as a separate agent in a separate place.
696 class ClientCSharpShell_v1 : CSharpShell {
697 NetworkStream ns, interrupt_stream;
699 public ClientCSharpShell_v1 (Evaluator evaluator, int pid)
702 // Create a server socket we listen on whose address is passed to the agent
703 TcpListener listener = new TcpListener (new IPEndPoint (IPAddress.Loopback, 0));
705 TcpListener interrupt_listener = new TcpListener (new IPEndPoint (IPAddress.Loopback, 0));
706 interrupt_listener.Start ();
708 string agent_assembly = typeof (ClientCSharpShell).Assembly.Location;
709 string agent_arg = String.Format ("--agent:{0}:{1}" ,
710 ((IPEndPoint)listener.Server.LocalEndPoint).Port,
711 ((IPEndPoint)interrupt_listener.Server.LocalEndPoint).Port);
713 var vm = new Attach.VirtualMachine (pid);
714 vm.Attach (agent_assembly, agent_arg);
716 /* Wait for the client to connect */
717 TcpClient client = listener.AcceptTcpClient ();
718 ns = client.GetStream ();
719 TcpClient interrupt_client = interrupt_listener.AcceptTcpClient ();
720 interrupt_stream = interrupt_client.GetStream ();
722 Console.WriteLine ("Connected.");
726 // A remote version of Evaluate
728 protected override string Evaluate (string input)
730 ns.WriteString (input);
732 AgentStatus s = (AgentStatus) ns.ReadByte ();
735 case AgentStatus.PARTIAL_INPUT:
738 case AgentStatus.ERROR:
739 string err = ns.GetString ();
740 Console.Error.WriteLine (err);
743 case AgentStatus.RESULT_NOT_SET:
746 case AgentStatus.RESULT_SET:
747 string res = ns.GetString ();
748 Console.WriteLine (res);
754 public override int Run (string [] startup_files)
756 // The difference is that we do not call Evaluator.Init, that is done on the target
757 this.startup_files = startup_files;
758 return ReadEvalPrintLoop ();
761 protected override void ConsoleInterrupt (object sender, ConsoleCancelEventArgs a)
763 // Do not about our program
766 interrupt_stream.WriteByte (0);
767 int c = interrupt_stream.ReadByte ();
769 Console.WriteLine ("Execution interrupted");
775 // This is the agent loaded into the target process when using --attach.
779 NetworkStream interrupt_stream;
780 readonly Evaluator evaluator;
783 public CSharpAgent (Evaluator evaluator, String arg, TextWriter stderr)
785 this.evaluator = evaluator;
786 this.stderr = stderr;
787 new Thread (new ParameterizedThreadStart (Run)).Start (arg);
790 public void InterruptListener ()
793 int b = interrupt_stream.ReadByte();
796 evaluator.Interrupt ();
797 interrupt_stream.WriteByte (0);
801 public void Run (object o)
803 string arg = (string)o;
804 string ports = arg.Substring (8);
805 int sp = ports.IndexOf (':');
806 int port = Int32.Parse (ports.Substring (0, sp));
807 int interrupt_port = Int32.Parse (ports.Substring (sp+1));
809 Console.WriteLine ("csharp-agent: started, connecting to localhost:" + port);
811 TcpClient client = new TcpClient ("127.0.0.1", port);
812 TcpClient interrupt_client = new TcpClient ("127.0.0.1", interrupt_port);
813 Console.WriteLine ("csharp-agent: connected.");
815 NetworkStream s = client.GetStream ();
816 interrupt_stream = interrupt_client.GetStream ();
817 new Thread (InterruptListener).Start ();
820 // Add all assemblies loaded later
821 AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoaded;
823 // Add all currently loaded assemblies
824 foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) {
825 // Some assemblies seem to be already loaded, and loading them again causes 'defined multiple times' errors
826 if (a.GetName ().Name != "mscorlib" && a.GetName ().Name != "System.Core" && a.GetName ().Name != "System")
827 evaluator.ReferenceAssembly (a);
832 AppDomain.CurrentDomain.AssemblyLoad -= AssemblyLoaded;
834 interrupt_client.Close ();
835 Console.WriteLine ("csharp-agent: disconnected.");
839 void AssemblyLoaded (object sender, AssemblyLoadEventArgs e)
841 evaluator.ReferenceAssembly (e.LoadedAssembly);
844 public void RunRepl (NetworkStream s)
848 while (!InteractiveBase.QuitRequested) {
851 StringWriter error_output = (StringWriter)stderr;
853 string line = s.GetString ();
861 input = input + "\n" + line;
864 input = evaluator.Evaluate (input, out result, out result_set);
865 } catch (Exception e) {
866 s.WriteByte ((byte) AgentStatus.ERROR);
867 s.WriteString (e.ToString ());
868 s.WriteByte ((byte) AgentStatus.RESULT_NOT_SET);
873 s.WriteByte ((byte) AgentStatus.PARTIAL_INPUT);
877 // Send warnings and errors back
878 error_string = error_output.ToString ();
879 if (error_string.Length != 0){
880 s.WriteByte ((byte) AgentStatus.ERROR);
881 s.WriteString (error_output.ToString ());
882 error_output.GetStringBuilder ().Clear ();
886 s.WriteByte ((byte) AgentStatus.RESULT_SET);
887 StringWriter sr = new StringWriter ();
888 CSharpShell.PrettyPrint (sr, result);
889 s.WriteString (sr.ToString ());
891 s.WriteByte ((byte) AgentStatus.RESULT_NOT_SET);
893 } catch (IOException) {
895 } catch (Exception e){
896 Console.WriteLine (e);
902 public class UnixUtils {
903 [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")]
904 extern static int _isatty (int fd);
906 public static bool isatty (int fd)
909 return _isatty (fd) == 1;
918 namespace Mono.Management
920 interface IVirtualMachine {
921 void LoadAgent (string filename, string args);