Esempio n. 1
0
        static void InitializeCompiler(Compiler.CompilerContext ctx)
        {
            if (compiler_initialized)
            {
                return;
            }

            lock (compiler_initializer) {
                if (compiler_initialized)
                {
                    return;
                }

                // TODO: This smells like pretty big issue
                // AppDomain.CurrentDomain.AssemblyLoad += (sender, e) => { throw new NotImplementedException (); };

                // Add all currently loaded assemblies
                foreach (System.Reflection.Assembly a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    Compiler.GlobalRootNamespace.Instance.AddAssemblyReference(a);
                }

                Compiler.TypeManager.InitCoreTypes(ctx);
                Compiler.TypeManager.InitOptionalCoreTypes(ctx);
                compiler_initialized = true;
            }
        }
Esempio n. 2
0
		public Shell(MainWindow container) : base()
		{
			this.container = container;
			WrapMode = WrapMode.Word;
			CreateTags ();

			Pango.FontDescription font_description = new Pango.FontDescription();
			font_description.Family = "Monospace";
			ModifyFont(font_description);
			
			TextIter end = Buffer.EndIter;
			Buffer.InsertWithTagsByName (ref end, "Mono C# Shell, type 'help;' for help\n\nEnter statements or expressions below.\n", "Comment");
			ShowPrompt (false);
			
			
			context = new CompilerContext (new CompilerSettings (), new ConsoleReportPrinter ());
			evaluator = new Evaluator (context);
			evaluator.DescribeTypeExpressions = true;
			
			evaluator.InteractiveBaseClass = typeof (InteractiveGraphicsBase);
			evaluator.Run ("LoadAssembly (\"System.Drawing\");");
			evaluator.Run ("using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Drawing;");

			if (!MainClass.Debug){
				GuiStream error_stream = new GuiStream ("Error", (x, y) => Output (x, y));
				StreamWriter gui_output = new StreamWriter (error_stream);
				gui_output.AutoFlush = true;
				Console.SetError (gui_output);

				GuiStream stdout_stream = new GuiStream ("Stdout", (x, y) => Output (x, y));
				gui_output = new StreamWriter (stdout_stream);
				gui_output.AutoFlush = true;
				Console.SetOut (gui_output);
			}
		}
Esempio n. 3
0
		public void Simple ()
		{
			//string content = @"class A { }";
			string content = @"

class Foo
{
	void Bar ()
	{
completionList.Add (""delegate"" + sb, ""md-keyword"", GettextCatalog.GetString (""Creates anonymous delegate.""), ""delegate"" + sb + "" {"" + Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent + TextEditorProperties.IndentString + ""|"" + Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent +""};"");
	}
}"
	;


			var stream = new MemoryStream (Encoding.UTF8.GetBytes (content));

			var ctx = new CompilerContext (new CompilerSettings (), new AssertReportPrinter ());

			ModuleContainer module = new ModuleContainer (ctx);
			var file = new SourceFile ("test", "asdfas", 0);
			CSharpParser parser = new CSharpParser (
				new SeekableStreamReader (stream, Encoding.UTF8),
				new CompilationSourceFile (module, file),
				ctx.Report,
				new ParserSession ());

			RootContext.ToplevelTypes = module;
			Location.Initialize (new List<SourceFile> { file });
			parser.parse ();

			Assert.AreEqual (0, ctx.Report.Errors);

			module.Accept (new TestVisitor ());
		}
Esempio n. 4
0
        static void Main(string[] args)
        {
            var compilerContext = new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter());
            var evaluator = new Evaluator(compilerContext);

            // Make it reference our own assembly so it can use IFoo
            evaluator.ReferenceAssembly(typeof(IFoo).Assembly);

            // Feed it some code
            evaluator.Compile(
                @"
            public class Foo : MonoCompilerDemo.IFoo
            {
            public string Bar(string s) { return s.ToUpper(); }
            }");

            for (; ; )
            {
                string line = Console.ReadLine();
                if (line == null) break;

                object result;
                bool result_set;
                evaluator.Evaluate(line, out result, out result_set);
                if (result_set) Console.WriteLine(result);
            }
        }
		public virtual Type LookupTypeReflection (CompilerContext ctx, string name, Location loc, bool must_be_unique)
		{
			Type found_type = null;

			foreach (Assembly a in referenced_assemblies) {
				Type t = GetTypeInAssembly (a, name);
				if (t == null)
					continue;

				if (!must_be_unique)
					return t;

				if (found_type == null) {
					found_type = t;
					continue;
				}

				// When type is forwarded
				if (t.Assembly == found_type.Assembly)
					continue;					

				ctx.Report.SymbolRelatedToPreviousError (found_type);
				ctx.Report.SymbolRelatedToPreviousError (t);
				if (loc.IsNull) {
					Error_AmbiguousPredefinedType (ctx, loc, name, found_type);
				} else {
					ctx.Report.Error (433, loc, "The imported type `{0}' is defined multiple times", name);
				}

				return found_type;
			}

			return found_type;
		}
Esempio n. 6
0
        private static void InitializeEvaluator()
        {
            _Interop.VarStorage["ReplVersion"] = typeof(Program).Assembly.GetName().Version;

            var settings = new CompilerSettings() {
                StdLib = true
            };

            var reportPrinter = new ConsoleReportPrinter();

            var ctx = new CompilerContext(settings, reportPrinter);

            evaluator = new Evaluator(ctx);

            evaluator.ReferenceAssembly(typeof(_Interop).Assembly);

            evaluator.Run(
            @"
            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            ");

            evaluator.Run("var _v = _Interop.VarStorage;");
            evaluator.Run("var _h = _Interop.History;");
            evaluator.Run("_Interop.VoidMethod exit = _Interop.Exit;");
            evaluator.Run("_Interop.ReturnStringListMethod globals = _Interop.GetGlobals");
        }
Esempio n. 7
0
		public void FeatureIsNotAvailable (CompilerContext compiler, Location loc, string feature)
		{
			string version;
			switch (compiler.Settings.Version) {
			case LanguageVersion.ISO_1:
				version = "1.0";
				break;
			case LanguageVersion.ISO_2:
				version = "2.0";
				break;
			case LanguageVersion.V_3:
				version = "3.0";
				break;
			case LanguageVersion.V_4:
				version = "4.0";
				break;
			case LanguageVersion.V_5:
				version = "5.0";
				break;
			default:
				throw new InternalErrorException ("Invalid feature version", compiler.Settings.Version);
			}

			Error (1644, loc,
				"Feature `{0}' cannot be used because it is not part of the C# {1} language specification",
				      feature, version);
		}
Esempio n. 8
0
        public static DynamicContext Create()
        {
            if (dc != null)
            {
                return(dc);
            }

            lock (compiler_initializer) {
                if (dc != null)
                {
                    return(dc);
                }

                var settings = new Compiler.CompilerSettings()
                {
                    WarningLevel = 0
                };

                var cc = new Compiler.CompilerContext(settings, ErrorPrinter.Instance)
                {
                    IsRuntimeBinder = true
                };

                //
                // Any later loaded assemblies are handled internally by GetAssemblyDefinition
                // domain.AssemblyLoad cannot be used as that would be too destructive as we
                // would hold all loaded assemblies even if they can be never visited
                //
                // TODO: Remove this code and rely on GetAssemblyDefinition only
                //
                var module = new Compiler.ModuleContainer(cc);
                module.HasTypesFullyDefined = true;

                // Setup fake assembly, it's used mostly to simplify checks like friend-access
                var temp = new Compiler.AssemblyDefinitionDynamic(module, "dynamic");
                module.SetDeclaringAssembly(temp);

                var importer = new Compiler.ReflectionImporter(module, cc.BuiltinTypes)
                {
                    IgnorePrivateMembers         = false,
                    IgnoreCompilerGeneratedField = false
                };

                // Import all currently loaded assemblies
                // TODO: Rewrite this to populate type cache on-demand, that should greatly
                // reduce our start-up cost
                var domain = AppDomain.CurrentDomain;
                foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    importer.ImportAssembly(a, module.GlobalRootNamespace);
                }

                cc.BuiltinTypes.CheckDefinitions(module);
                module.InitializePredefinedTypes();

                dc = new DynamicContext(module, importer);
            }

            return(dc);
        }
Esempio n. 9
0
        private void resetEvaluator()
        {
            m_errorStream = new StringBuilder();
            //StreamReader sr =
            TextWriter tw  = new StringWriter(m_errorStream);
            var        ctx = new Mono.CSharp.CompilerContext(
                new Mono.CSharp.CompilerSettings()
            {
                AssemblyReferences = new List <string>()
                {
                    typeof(ILMath).Assembly.FullName,
                    typeof(System.Drawing.PointF).Assembly.FullName,
                    typeof(System.Linq.Queryable).Assembly.FullName
                },
                //Unsafe = true
            }, new StreamReportPrinter(tw));

            var eval = new Mono.CSharp.Evaluator(ctx);

            // reset line colors (thread safe)
            ILNumerics.Drawing.Plotting.ILLinePlot.NextColors = new ILColorEnumerator();

            string m_head = @"
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq; 
using ILNumerics;
using ILNumerics.Drawing;
using ILNumerics.Drawing.Plotting;";

            eval.Run(m_head);
            m_evaluator = eval;
        }
Esempio n. 10
0
		void tokenize_file (CompilationUnit file, CompilerContext ctx)
		{
			Stream input;

			try {
				input = File.OpenRead (file.Name);
			} catch {
				Report.Error (2001, "Source file `" + file.Name + "' could not be found");
				return;
			}

			using (input){
				SeekableStreamReader reader = new SeekableStreamReader (input, RootContext.Encoding);
				Tokenizer lexer = new Tokenizer (reader, file, ctx);
				int token, tokens = 0, errors = 0;

				while ((token = lexer.token ()) != Token.EOF){
					tokens++;
					if (token == Token.ERROR)
						errors++;
				}
				Console.WriteLine ("Tokenized: " + tokens + " found " + errors + " errors");
			}
			
			return;
		}
Esempio n. 11
0
        public ScriptingEngine()
        {
            tokenSource = new CancellationTokenSource();
            taskFactory = new TaskFactory(tokenSource.Token);

            context = new CompilerContext(new Mono.CSharp.CompilerSettings(), new ConsoleReportPrinter());
            evaluator = new Evaluator(context);
            evaluator.InteractiveBaseClass = typeof(ScriptingInteractiveBase);
            evaluator.DescribeTypeExpressions = true;

            ScriptingInteractiveBase.Evaluator = evaluator;
            var errorStream = new GuiStream(TextType.Error, OnConsoleOutput);
            var guiOutput = new StreamWriter(errorStream);
            guiOutput.AutoFlush = true;
            Console.SetError(guiOutput);
            ScriptingInteractiveBase.Output = guiOutput;

            var stdoutStream = new GuiStream(TextType.Output, OnConsoleOutput);
            guiOutput = new StreamWriter(stdoutStream);
            guiOutput.AutoFlush = true;
            Console.SetOut(guiOutput);
            ScriptingInteractiveBase.Error = guiOutput;

            codeCompletion = new CSharpCompletion(this);

            Evaluate("using System; using System.Linq; using System.Collections; using System.Collections.Generic;");

            //init the code completion so that the first character typed is not delayed
            //var readOnlyDocument = new ReadOnlyDocument(new StringTextSource(""), "init.csx");
            //codeCompletion.GetCompletions(readOnlyDocument, 0);
        }
Esempio n. 12
0
		public static DynamicContext Create ()
		{
			if (dc != null)
				return dc;

			lock (compiler_initializer) {
				if (dc != null)
					return dc;

				var reporter = new Compiler.Report (ErrorPrinter.Instance) {
					WarningLevel = 0
				};

				var cc = new Compiler.CompilerContext (reporter) {
					IsRuntimeBinder = true
				};

				//IList<Compiler.PredefinedTypeSpec> core_types = null;
				//// HACK: To avoid re-initializing static TypeManager types, like string_type
				//if (!Compiler.RootContext.EvalMode) {
				//    core_types = Compiler.TypeManager.InitCoreTypes ();
				//}

				//
				// Any later loaded assemblies are handled internally by GetAssemblyDefinition
				// domain.AssemblyLoad cannot be used as that would be too destructive as we
				// would hold all loaded assemblies even if they can be never visited
				//
				// TODO: Remove this code and rely on GetAssemblyDefinition only
				//
				var module = new Compiler.ModuleContainer (cc);
				var temp = new Compiler.AssemblyDefinitionDynamic (module, "dynamic");
				module.SetDeclaringAssembly (temp);

				// Import all currently loaded assemblies
				var domain = AppDomain.CurrentDomain;

				temp.Create (domain, System.Reflection.Emit.AssemblyBuilderAccess.Run);
				var importer = new Compiler.ReflectionImporter (cc.BuildinTypes) {
					IgnorePrivateMembers = false
				};

				Compiler.RootContext.ToplevelTypes = module;

				foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()) {
					importer.ImportAssembly (a, module.GlobalRootNamespace);
				}

				if (!Compiler.RootContext.EvalMode) {
					cc.BuildinTypes.CheckDefinitions (module);
					module.InitializePredefinedTypes ();
				}

				dc = new DynamicContext (module, importer);
			}

			return dc;
		}
Esempio n. 13
0
		public ModuleContainer (CompilerContext context, bool isUnsafe)
			: base (null, null, MemberName.Null, null, Kind.Root)
		{
			this.is_unsafe = isUnsafe;
			this.context = context;

			types = new ArrayList ();
			anonymous_types = new Hashtable ();
		}
Esempio n. 14
0
        public ModuleCompiled(CompilerContext context, bool isUnsafe)
            : base(null)
        {
            this.is_unsafe = isUnsafe;
            this.context = context;

            types = new List<TypeContainer> ();
            anonymous_types = new Dictionary<int, List<AnonymousTypeClass>> ();
        }
Esempio n. 15
0
		public Report (CompilerContext context, ReportPrinter printer)
		{
			if (context == null)
				throw new ArgumentNullException ("settings");
			if (printer == null)
				throw new ArgumentNullException ("printer");

			this.settings = context.Settings;
			this.printer = printer;
		}
Esempio n. 16
0
		//
		// Initializes the code generator variables for interactive use (repl)
		//
		static public void InitDynamic (CompilerContext ctx, string name)
		{
			current_domain = AppDomain.CurrentDomain;
			AssemblyName an = Assembly.GetAssemblyName (name, name);
			
			Assembly.Builder = current_domain.DefineDynamicAssembly (an, AssemblyBuilderAccess.Run);
			RootContext.ToplevelTypes = new ModuleCompiled (ctx, true);
			RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule (Basename (name), false);
			Assembly.Name = Assembly.Builder.GetName ();
		}
Esempio n. 17
0
        public static DynamicMetaObject Bind(DynamicMetaObject target, Compiler.Expression expr, BindingRestrictions restrictions, DynamicMetaObject errorSuggestion)
        {
            var report = new Compiler.Report(ErrorPrinter.Instance)
            {
                WarningLevel = 0
            };
            var ctx = new Compiler.CompilerContext(report);

            Compiler.RootContext.ToplevelTypes = new Compiler.ModuleContainer(ctx, true);

            InitializeCompiler(ctx);

            Expression res;

            try {
                // TODO: ResolveOptions
                Compiler.ResolveContext rc = new Compiler.ResolveContext(new RuntimeBinderContext(ctx));

                // Static typemanager and internal caches are not thread-safe
                lock (resolver) {
                    expr = expr.Resolve(rc);
                }

                if (expr == null)
                {
                    throw new RuntimeBinderInternalCompilerException("Expression resolved to null");
                }

                res = expr.MakeExpression(new Compiler.BuilderContext());
            } catch (RuntimeBinderException e) {
                if (errorSuggestion != null)
                {
                    return(errorSuggestion);
                }

                if (binder_exception_ctor == null)
                {
                    binder_exception_ctor = typeof(RuntimeBinderException).GetConstructor(new[] { typeof(string) });
                }

                //
                // Uses target type to keep expressions composition working
                //
                res = Expression.Throw(Expression.New(binder_exception_ctor, Expression.Constant(e.Message)), target.LimitType);
            } catch (Exception) {
                if (errorSuggestion != null)
                {
                    return(errorSuggestion);
                }

                throw;
            }

            return(new DynamicMetaObject(res, restrictions));
        }
Esempio n. 18
0
        public void Setup()
        {
            var builder = new StringBuilder();
            var writer = new StringWriter(builder);
            var printer = new StreamReportPrinter(writer);
            var settings = new CompilerSettings();
            settings.AssemblyReferences.Add("DbTool.Testing");

            var context = new CompilerContext(settings, printer);
            _evaluator = new Evaluator(context);
        }
Esempio n. 19
0
		public ModuleContainer (CompilerContext context)
			: base (null, null, MemberName.Null, null, 0)
		{
			this.context = context;

			caching_flags &= ~(Flags.Obsolete_Undetected | Flags.Excluded_Undetected);

			types = new List<TypeContainer> ();
			anonymous_types = new Dictionary<int, List<AnonymousTypeClass>> ();
			global_ns = new GlobalRootNamespace ();
			alias_ns = new Dictionary<string, RootNamespace> ();
		}
Esempio n. 20
0
		public static DynamicContext Create ()
		{
			if (dc != null)
				return dc;

			lock (compiler_initializer) {
				if (dc != null)
					return dc;

				var settings = new Compiler.CompilerSettings () {
					WarningLevel = 0
				};

				var cc = new Compiler.CompilerContext (settings, ErrorPrinter.Instance) {
					IsRuntimeBinder = true
				};

				//
				// Any later loaded assemblies are handled internally by GetAssemblyDefinition
				// domain.AssemblyLoad cannot be used as that would be too destructive as we
				// would hold all loaded assemblies even if they can be never visited
				//
				// TODO: Remove this code and rely on GetAssemblyDefinition only
				//
				var module = new Compiler.ModuleContainer (cc);
				module.HasTypesFullyDefined = true;
				
				// Setup fake assembly, it's used mostly to simplify checks like friend-access
				var temp = new Compiler.AssemblyDefinitionDynamic (module, "dynamic");
				module.SetDeclaringAssembly (temp);

				var importer = new Compiler.ReflectionImporter (module, cc.BuiltinTypes) {
					IgnorePrivateMembers = false,
					IgnoreCompilerGeneratedField = false
				};

				// Import all currently loaded assemblies
				// TODO: Rewrite this to populate type cache on-demand, that should greatly
				// reduce our start-up cost
				var domain = AppDomain.CurrentDomain;
				foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()) {
					importer.ImportAssembly (a, module.GlobalRootNamespace);
				}

				cc.BuiltinTypes.CheckDefinitions (module);
				module.InitializePredefinedTypes ();

				dc = new DynamicContext (module, importer);
			}

			return dc;
		}
Esempio n. 21
0
        //
        // Our constructor
        //
        private Iterator(CompilerContext ctx, IMethodData method, TypeContainer host, TypeSpec iterator_type, bool is_enumerable)
            : base(new ToplevelBlock (ctx, method.Block, ParametersCompiled.EmptyReadOnlyParameters, method.Block.StartLocation),
				TypeManager.bool_type,
				method.Location)
        {
            this.OriginalMethod = method;
            this.OriginalIteratorType = iterator_type;
            this.IsEnumerable = is_enumerable;
            this.Host = host;
            this.type = method.ReturnType;

            IteratorHost = Block.ChangeToIterator (this, method.Block);
        }
Esempio n. 22
0
		public void ImportTypes (CompilerContext ctx)
		{
			foreach (Assembly a in referenced_assemblies) {
				try {
					ctx.MetaImporter.ImportAssembly (a, this);
				} catch (TypeLoadException e) {
					ctx.Report.Error (11, Location.Null, e.Message);
				} catch (System.IO.FileNotFoundException) {
					ctx.Report.Error (12, Location.Null, "An assembly `{0}' is used without being referenced",
						a.FullName);
				}
			}
		}
Esempio n. 23
0
		public void ComputeNamespace (CompilerContext ctx, Type extensionType)
		{
			foreach (Assembly a in referenced_assemblies) {
				try {
					ComputeNamespaces (a, extensionType);
				} catch (TypeLoadException e) {
					ctx.Report.Error (11, Location.Null, e.Message);
				} catch (System.IO.FileNotFoundException) {
					ctx.Report.Error (12, Location.Null, "An assembly `{0}' is used without being referenced",
						a.FullName);
				}
			}
		}
Esempio n. 24
0
		public Evaluator (CompilerSettings settings, Report report)
		{
			ctx = new CompilerContext (settings, report);

			module = new ModuleContainer (ctx);
			module.Evaluator = this;

			// FIXME: Importer needs this assembly for internalsvisibleto
			module.SetDeclaringAssembly (new AssemblyDefinitionDynamic (module, "evaluator"));
			importer = new ReflectionImporter (module, ctx.BuildinTypes);

			InteractiveBaseClass = typeof (InteractiveBase);
			fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> ();
		}
        public void Init()
        {
            var printer = new StreamReportPrinter(_stringWriter);
            var settings = new CompilerSettings();
            settings.AssemblyReferences.AddRange(InitialAssemblies);
            var context = new CompilerContext(settings, printer);
            _evaluator = new Evaluator(context)
                {
                    InteractiveBaseClass = typeof (DbToolInteractive),
                    DescribeTypeExpressions = true,
                };
            ReferenceAssemblies(typeof(Database).Assembly, typeof(DynamicSqlQuery).Assembly);

            Using(InitialUsings);
            DbToolInteractive.Evaluator = _evaluator;
            DbToolInteractive.Output = _stringWriter;
        }
        private CompilerContext CreateContext([NotNull] string source)
        {
            var settings = new CompilerSettings
            {
                Target = Target.Library,
                TargetExt = ".dll",
                LoadDefaultReferences = true,
                ShowFullPaths = false,
                StdLib = true,
            };

            var context = new CompilerContext(settings, new ConsoleReportPrinter(_logger));
            context.SourceFiles.Add(new SourceFile("Source", source, 0));

            _report = new Report(context, new ConsoleReportPrinter(_logger));

            return context;
        }
Esempio n. 27
0
        // This method evaluates the given code and returns a CompilerOutput object
        public static CompilerOutput evaluateCode(string code)
        {
            CompilerOutput compilerOutput = new CompilerOutput ();
            /*
            var compilerContext = new CompilerContext(new CompilerSettings(), new ConsoleReportPrinter());

            var evaluator = new Evaluator(compilerContext);
            */
            var reportWriter = new StringWriter();
            var settings = new CompilerSettings();
            var printer = new ConsoleReportPrinter(reportWriter);

            var compilerContext = new CompilerContext (settings, printer);
            var reports = new Report(compilerContext, printer);
            var evaluator = new Evaluator(compilerContext);

            var myString = "";
            originalConsoleOut_global = Console.Out; // preserve the original stream
            using(var writer = new StringWriter())
            {
                Console.SetOut(writer);

                evaluator.Run (code);
                evaluator.Run ("MainClass m1 = new MainClass(); m1.Main();");

                //bConsole.WriteLine ("after executing code");

                if (reports.Errors > 0) {
                    Console.WriteLine ("reportWriter.ToString: \n" + reportWriter.ToString ());
                    compilerOutput.errors = reportWriter.ToString ();
                }

                writer.Flush(); // make sure everything is written out of consule

                myString = writer.GetStringBuilder().ToString();

                compilerOutput.consoleOut = myString;

            }

            Console.SetOut(originalConsoleOut_global); // restore Console.Out

            return compilerOutput;
        }
Esempio n. 28
0
        ///////////////////////////////////////////////////////////////////////
        private void Initialize()
        {
            CompilerSettings sett = new CompilerSettings();
            ReportPrinter prnt = new ConsoleReportPrinter();

            // TODO programatically add references for all flynn assemblies

            sett.AssemblyReferences.Add("Flynn.Core.dll");
            sett.AssemblyReferences.Add("Flynn.X10.dll");
            sett.AssemblyReferences.Add("Flynn.Cron.dll");
            sett.AssemblyReferences.Add("Flynn.Utilities.dll");

            CompilerContext ctx = new CompilerContext(sett, prnt);

            _eval = new Evaluator(ctx);

            _eval.Run(Resources.CSharpEngine_InitUsings);
            _eval.Run(Resources.CSharpEngine_InitScript);
        }
Esempio n. 29
0
		public Evaluator (CompilerContext ctx)
		{
			this.ctx = ctx;

			module = new ModuleContainer (ctx);
			module.Evaluator = this;

			source_file = new CompilationSourceFile (module);
			module.AddTypeContainer (source_file);

			startup_files = ctx.SourceFiles.Count;

			// FIXME: Importer needs this assembly for internalsvisibleto
			module.SetDeclaringAssembly (new AssemblyDefinitionDynamic (module, "evaluator"));
			importer = new ReflectionImporter (module, ctx.BuiltinTypes);

			InteractiveBaseClass = typeof (InteractiveBase);
			fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> ();
		}
Esempio n. 30
0
		public Evaluator (CompilerSettings settings, Report report)
		{
			ctx = new CompilerContext (settings, report);

			module = new ModuleContainer (ctx);
			module.Evaluator = this;

			source_file = new CompilationSourceFile ("{interactive}", "", 1);
 			source_file.NamespaceContainer = new NamespaceContainer (null, module, null, source_file);

			ctx.SourceFiles.Add (source_file);

			// FIXME: Importer needs this assembly for internalsvisibleto
			module.SetDeclaringAssembly (new AssemblyDefinitionDynamic (module, "evaluator"));
			importer = new ReflectionImporter (module, ctx.BuiltinTypes);

			InteractiveBaseClass = typeof (InteractiveBase);
			fields = new Dictionary<string, Tuple<FieldSpec, FieldInfo>> ();
		}
		public static DynamicMetaObject Bind (DynamicMetaObject target, Compiler.Expression expr, BindingRestrictions restrictions, DynamicMetaObject errorSuggestion)
		{
			var report = new Compiler.Report (ErrorPrinter.Instance) { WarningLevel = 0 };
			var ctx = new Compiler.CompilerContext (report);
			Compiler.RootContext.ToplevelTypes = new Compiler.ModuleContainer (ctx, true);

			InitializeCompiler (ctx);

			Expression res;
			try {
				// TODO: ResolveOptions
				Compiler.ResolveContext rc = new Compiler.ResolveContext (new RuntimeBinderContext (ctx));

				// Static typemanager and internal caches are not thread-safe
				lock (resolver) {
					expr = expr.Resolve (rc);
				}

				if (expr == null)
					throw new RuntimeBinderInternalCompilerException ("Expression resolved to null");

				res = expr.MakeExpression (new Compiler.BuilderContext ());
			} catch (RuntimeBinderException e) {
				if (errorSuggestion != null)
					return errorSuggestion;

				if (binder_exception_ctor == null)
					binder_exception_ctor = typeof (RuntimeBinderException).GetConstructor (new[] { typeof (string) });

				//
				// Uses target type to keep expressions composition working
				//
				res = Expression.Throw (Expression.New (binder_exception_ctor, Expression.Constant (e.Message)), target.LimitType);
			} catch (Exception) {
				if (errorSuggestion != null)
					return errorSuggestion;

				throw;
			}

			return new DynamicMetaObject (res, restrictions);
		}
Esempio n. 32
0
        public DebuggerWindow(PluginContext context, String hackPath)
        {
            this.InitializeComponent();

            Trace.Listeners.Add(this.listener);

            var compilerSettings = new CompilerSettings
            {
                Unsafe = true,
            };
            compilerSettings.AssemblyReferences.Add("System.dll");
            compilerSettings.AssemblyReferences.Add("System.Core.dll");
            compilerSettings.AssemblyReferences.Add(typeof(MessageBox).Assembly.CodeBase); // PresentationFramework.dll
            compilerSettings.AssemblyReferences.Add(Path.Combine(hackPath, "SharpCraft.dll"));

            var compilerContext = new CompilerContext(compilerSettings, new DebuggerReportPrinter());

            evaluator = new Evaluator(compilerContext);
            evaluator.Compile("using System;");
            evaluator.Compile("using TinkerWorX.SharpCraft;");
            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }
        public MonoCSharpExecutor()
        {
            _reportBuilder = new StringBuilder();
            var writer = new StringWriter(_reportBuilder);
            var printer = new StreamReportPrinter(writer);
            var settings = new CompilerSettings();

            var context = new CompilerContext(settings, printer);
            _evaluator = new Evaluator(context);
            _evaluator.InteractiveBaseClass = typeof (InteractiveStuff);
            _evaluator.ReferenceAssembly(typeof(HttpContext).Assembly);
            _evaluator.ReferenceAssembly(typeof(VisualFarmRepo).Assembly);
            _evaluator.ReferenceAssembly(typeof(BondegardFacade).Assembly);
            _evaluator.ReferenceAssembly(typeof(IVFSConfig).Assembly);
            Execute("using System;");
            Execute("using System.Linq;");
            Execute("using System.Web;");
            Execute("using VisualFarmStudio.Core.Domain;");
            Execute("using VisualFarmStudio.Core.Repository;");
            Execute("using VisualFarmStudio.Lib.Model;");
            Execute("using VisualFarmStudio.Lib.Containers;");
        }
Esempio n. 34
0
		public void Simple ()
		{
			//string content = @"class A { }";
			string content = @"

class Foo
{
	void Bar ()
	{
completionList.Add (""delegate"" + sb, ""md-keyword"", GettextCatalog.GetString (""Creates anonymous delegate.""), ""delegate"" + sb + "" {"" + Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent + TextEditorProperties.IndentString + ""|"" + Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent +""};"");
	}
}"
	;


			var stream = new MemoryStream (Encoding.UTF8.GetBytes (content));

			var ctx = new CompilerContext (new CompilerSettings (), new Report (new AssertReportPrinter ()));

			ModuleContainer module = new ModuleContainer (ctx);
			CSharpParser parser = new CSharpParser (
				new SeekableStreamReader (stream, Encoding.UTF8),
				new CompilationUnit ("name", "path", 0),
				module);

			RootContext.ToplevelTypes = module;
			Location.AddFile (ctx.Report, "asdfas");
			Location.Initialize ();
			parser.LocationsBag = new LocationsBag ();
			parser.parse ();

			var m = module.Types[0].Methods[0] as Method;
			var s = m.Block.FirstStatement;
			var o = s.loc.Column;
			

			module.Accept (new TestVisitor ());
		}
Esempio n. 35
0
        public static MethodSpec GetConstructor(CompilerContext ctx, TypeSpec container_type, TypeSpec delType)
        {
            var ctor = MemberCache.FindMember(delType, MemberFilter.Constructor(null), BindingRestriction.DeclaredOnly);

            return((MethodSpec)ctor);
        }
Esempio n. 36
0
        public static AParametersCollection GetParameters(CompilerContext ctx, TypeSpec delType)
        {
            var invoke_mb = GetInvokeMethod(ctx, delType);

            return(invoke_mb.Parameters);
        }
Esempio n. 37
0
 public RuntimeBinderContext(Compiler.CompilerContext ctx)
 {
     this.ctx = ctx;
 }
        public TypeExpr LookupType(CompilerContext ctx, string name, int arity, bool silent, Location loc)
        {
            if (types == null)
            {
                return(null);
            }

            TypeExpr te;

            if (arity == 0 && cached_types.TryGetValue(name, out te))
            {
                return(te);
            }

            IList <TypeSpec> found;

            if (!types.TryGetValue(name, out found))
            {
                return(null);
            }

            TypeSpec best = null;

            foreach (var ts in found)
            {
                if (ts.Arity == arity)
                {
                    if (best == null)
                    {
                        best = ts;
                        continue;
                    }

                    var pts = best as BuildinTypeSpec;
                    if (pts == null)
                    {
                        pts = ts as BuildinTypeSpec;
                    }

                    if (pts != null)
                    {
                        ctx.Report.SymbolRelatedToPreviousError(best);
                        ctx.Report.SymbolRelatedToPreviousError(ts);

                        // TODO: This should use different warning number but we want to be csc compatible
                        ctx.Report.Warning(1685, 1, loc,
                                           "The predefined type `{0}.{1}' is redefined in the source code. Ignoring the local type definition",
                                           pts.Namespace, pts.Name);
                        best = pts;
                        continue;
                    }

                    if (best.MemberDefinition.IsImported && ts.MemberDefinition.IsImported)
                    {
                        ctx.Report.SymbolRelatedToPreviousError(best);
                        ctx.Report.SymbolRelatedToPreviousError(ts);
                        if (silent)
                        {
                            ctx.Report.Warning(1685, 1, loc,
                                               "The predefined type `{0}' is defined in multiple assemblies. Using definition from `{1}'",
                                               ts.GetSignatureForError(), best.MemberDefinition.DeclaringAssembly.Name);
                        }
                        else
                        {
                            ctx.Report.Error(433, loc, "The imported type `{0}' is defined multiple times", ts.GetSignatureForError());
                        }

                        break;
                    }

                    if (best.MemberDefinition.IsImported)
                    {
                        best = ts;
                    }

                    if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic(RootContext.ToplevelTypes.DeclaringAssembly))
                    {
                        continue;
                    }

                    if (silent)
                    {
                        continue;
                    }

                    if (ts.MemberDefinition.IsImported)
                    {
                        ctx.Report.SymbolRelatedToPreviousError(ts);
                    }

                    ctx.Report.Warning(436, 2, loc,
                                       "The type `{0}' conflicts with the imported type of same name'. Ignoring the imported type definition",
                                       best.GetSignatureForError());
                }

                //
                // Lookup for the best candidate with closest arity match
                //
                if (arity < 0)
                {
                    if (best == null)
                    {
                        best = ts;
                    }
                    else if (System.Math.Abs(ts.Arity + arity) < System.Math.Abs(best.Arity + arity))
                    {
                        best = ts;
                    }
                }
            }

            if (best == null)
            {
                return(null);
            }

            if ((best.Modifiers & Modifiers.INTERNAL) != 0 && !best.MemberDefinition.IsInternalAsPublic(RootContext.ToplevelTypes.DeclaringAssembly))
            {
                return(null);
            }

            te = new TypeExpression(best, Location.Null);

            // TODO MemberCache: Cache more
            if (arity == 0 && !silent)
            {
                cached_types.Add(name, te);
            }

            return(te);
        }
Esempio n. 39
0
        //
        // Initializes the code generator variables
        //
        static public bool Init(string name, string output, bool want_debugging_support, CompilerContext ctx)
        {
            FileName = output;
            AssemblyName an = Assembly.GetAssemblyName(name, output);

            if (an == null)
            {
                return(false);
            }

            if (an.KeyPair != null)
            {
                // If we are going to strong name our assembly make
                // sure all its refs are strong named
                foreach (Assembly a in GlobalRootNamespace.Instance.Assemblies)
                {
                    AssemblyName ref_name = a.GetName();
                    byte []      b        = ref_name.GetPublicKeyToken();
                    if (b == null || b.Length == 0)
                    {
                        ctx.Report.Error(1577, "Assembly generation failed " +
                                         "-- Referenced assembly '" +
                                         ref_name.Name +
                                         "' does not have a strong name.");
                        //Environment.Exit (1);
                    }
                }
            }

            current_domain = AppDomain.CurrentDomain;

            try {
                Assembly.Builder = current_domain.DefineDynamicAssembly(an,
                                                                        AssemblyBuilderAccess.RunAndSave | COMPILER_ACCESS, Dirname(name));
            }
            catch (ArgumentException) {
                // specified key may not be exportable outside it's container
                if (RootContext.StrongNameKeyContainer != null)
                {
                    ctx.Report.Error(1548, "Could not access the key inside the container `" +
                                     RootContext.StrongNameKeyContainer + "'.");
                    Environment.Exit(1);
                }
                throw;
            }
            catch (CryptographicException) {
                if ((RootContext.StrongNameKeyContainer != null) || (RootContext.StrongNameKeyFile != null))
                {
                    ctx.Report.Error(1548, "Could not use the specified key to strongname the assembly.");
                    Environment.Exit(1);
                }
                return(false);
            }

            // Get the complete AssemblyName from the builder
            // (We need to get the public key and token)
            Assembly.Name = Assembly.Builder.GetName();

            //
            // Pass a path-less name to DefineDynamicModule.  Wonder how
            // this copes with output in different directories then.
            // FIXME: figure out how this copes with --output /tmp/blah
            //
            // If the third argument is true, the ModuleBuilder will dynamically
            // load the default symbol writer.
            //
            try {
                RootContext.ToplevelTypes.Builder = Assembly.Builder.DefineDynamicModule(
                    Basename(name), Basename(output), want_debugging_support);

#if !MS_COMPATIBLE
                // TODO: We should use SymbolWriter from DefineDynamicModule
                if (want_debugging_support && !SymbolWriter.Initialize(RootContext.ToplevelTypes.Builder, output))
                {
                    ctx.Report.Error(40, "Unexpected debug information initialization error `{0}'",
                                     "Could not find the symbol writer assembly (Mono.CompilerServices.SymbolWriter.dll)");
                    return(false);
                }
#endif
            } catch (ExecutionEngineException e) {
                ctx.Report.Error(40, "Unexpected debug information initialization error `{0}'",
                                 e.Message);
                return(false);
            }

            return(true);
        }
Esempio n. 40
0
        public static DynamicContext Create()
        {
            if (dc != null)
            {
                return(dc);
            }

            lock (compiler_initializer) {
                if (dc != null)
                {
                    return(dc);
                }

                var reporter = new Compiler.Report(ErrorPrinter.Instance)
                {
                    WarningLevel = 0
                };

                var settings = new Compiler.CompilerSettings();

                var cc = new Compiler.CompilerContext(settings, reporter)
                {
                    IsRuntimeBinder = true
                };

                //IList<Compiler.PredefinedTypeSpec> core_types = null;
                //// HACK: To avoid re-initializing static TypeManager types, like string_type
                //if (!Compiler.RootContext.EvalMode) {
                //    core_types = Compiler.TypeManager.InitCoreTypes ();
                //}

                //
                // Any later loaded assemblies are handled internally by GetAssemblyDefinition
                // domain.AssemblyLoad cannot be used as that would be too destructive as we
                // would hold all loaded assemblies even if they can be never visited
                //
                // TODO: Remove this code and rely on GetAssemblyDefinition only
                //
                var module = new Compiler.ModuleContainer(cc);
                module.HasTypesFullyDefined = true;
                var temp = new Compiler.AssemblyDefinitionDynamic(module, "dynamic");
                module.SetDeclaringAssembly(temp);

                // Import all currently loaded assemblies
                var domain = AppDomain.CurrentDomain;

                temp.Create(domain, System.Reflection.Emit.AssemblyBuilderAccess.Run);
                var importer = new Compiler.ReflectionImporter(module, cc.BuiltinTypes)
                {
                    IgnorePrivateMembers = false
                };

                foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
                {
                    importer.ImportAssembly(a, module.GlobalRootNamespace);
                }

                cc.BuiltinTypes.CheckDefinitions(module);
                module.InitializePredefinedTypes();

                dc = new DynamicContext(module, importer);
            }

            return(dc);
        }
Esempio n. 41
0
 public static ParametersCompiled MergeGenerated(CompilerContext ctx, ParametersCompiled userParams, bool checkConflicts, Parameter compilerParams, TypeSpec compilerTypes)
 {
     return(MergeGenerated(ctx, userParams, checkConflicts,
                           new Parameter [] { compilerParams },
                           new TypeSpec [] { compilerTypes }));
 }
Esempio n. 42
0
 public AssemblyBuilderIKVM(AssemblyBuilder builder, CompilerContext ctx)
     : base(ctx)
 {
     this.builder = builder;
 }
Esempio n. 43
0
File: driver.cs Progetto: N3X15/mono
 public Driver(CompilerContext ctx)
 {
     this.ctx = ctx;
 }
Esempio n. 44
0
        TypeExpr CreateSiteType(CompilerContext ctx, bool isStatement, int dyn_args_count)
        {
            int default_args = isStatement ? 1 : 2;

            bool has_ref_out_argument = false;

            FullNamedExpression[] targs = new FullNamedExpression[dyn_args_count + default_args];
            targs [0] = new TypeExpression(TypeManager.call_site_type, loc);
            for (int i = 0; i < dyn_args_count; ++i)
            {
                Type     arg_type;
                Argument a = arguments [i];
                if (a.Type == TypeManager.null_type)
                {
                    arg_type = TypeManager.object_type;
                }
                else
                {
                    arg_type = TypeManager.TypeToReflectionType(a.Type);
                }

                if (a.ArgType == Argument.AType.Out || a.ArgType == Argument.AType.Ref)
                {
                    has_ref_out_argument = true;
                }

                targs [i + 1] = new TypeExpression(arg_type, loc);
            }

            TypeExpr del_type = null;

            if (!has_ref_out_argument)
            {
                string d_name = isStatement ? "Action`" : "Func`";

                Type t = TypeManager.CoreLookupType(ctx, "System", d_name + (dyn_args_count + default_args), Kind.Delegate, false);
                if (t != null)
                {
                    if (!isStatement)
                    {
                        targs[targs.Length - 1] = new TypeExpression(TypeManager.TypeToReflectionType(type), loc);
                    }

                    del_type = new GenericTypeExpr(t, new TypeArguments(targs), loc);
                }
            }

            // No appropriate predefined delegate found
            if (del_type == null)
            {
                Type        rt = isStatement ? TypeManager.void_type : type;
                Parameter[] p  = new Parameter [dyn_args_count + 1];
                p[0] = new Parameter(targs [0], "p0", Parameter.Modifier.NONE, null, loc);

                for (int i = 1; i < dyn_args_count + 1; ++i)
                {
                    p[i] = new Parameter(targs[i], "p" + i.ToString("X"), arguments[i - 1].Modifier, null, loc);
                }

                TypeContainer parent = CreateSiteContainer();
                Delegate      d      = new Delegate(parent.NamespaceEntry, parent, new TypeExpression(rt, loc),
                                                    Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED,
                                                    new MemberName("Container" + container_counter++.ToString("X")),
                                                    new ParametersCompiled(p), null);

                d.DefineType();
                d.Define();

                parent.AddDelegate(d);
                del_type = new TypeExpression(d.TypeBuilder, loc);
            }

            TypeExpr site_type = new GenericTypeExpr(TypeManager.generic_call_site_type, new TypeArguments(del_type), loc);

            return(site_type);
        }
Esempio n. 45
0
        public static void CreateIterator(IMethodData method, TypeContainer parent, int modifiers, CompilerContext ctx)
        {
            bool is_enumerable;
            Type iterator_type;

            Type ret = method.ReturnType;

            if (ret == null)
            {
                return;
            }

            if (!CheckType(ret, out iterator_type, out is_enumerable))
            {
                ctx.Report.Error(1624, method.Location,
                                 "The body of `{0}' cannot be an iterator block " +
                                 "because `{1}' is not an iterator interface type",
                                 method.GetSignatureForError(),
                                 TypeManager.CSharpName(ret));
                return;
            }

            ParametersCompiled parameters = method.ParameterInfo;

            for (int i = 0; i < parameters.Count; i++)
            {
                Parameter          p   = parameters [i];
                Parameter.Modifier mod = p.ModFlags;
                if ((mod & Parameter.Modifier.ISBYREF) != 0)
                {
                    ctx.Report.Error(1623, p.Location,
                                     "Iterators cannot have ref or out parameters");
                    return;
                }

                if (p is ArglistParameter)
                {
                    ctx.Report.Error(1636, method.Location,
                                     "__arglist is not allowed in parameter list of iterators");
                    return;
                }

                if (parameters.Types [i].IsPointer)
                {
                    ctx.Report.Error(1637, p.Location,
                                     "Iterators cannot have unsafe parameters or " +
                                     "yield types");
                    return;
                }
            }

            if ((modifiers & Modifiers.UNSAFE) != 0)
            {
                ctx.Report.Error(1629, method.Location, "Unsafe code may not appear in iterators");
                return;
            }

            Iterator iter = new Iterator(ctx, method, parent, iterator_type, is_enumerable);

            iter.Storey.DefineType();
        }
Esempio n. 46
0
 public bool Validate(CompilerContext compiler, bool isExplicit)
 {
     ((IMethodData)method).Block.Accept(this);
     return(can_inline && (isExplicit || statements < MAX_INLINE_STATEMENTS));
 }
Esempio n. 47
0
 public AssemblyBuilderExtension(CompilerContext ctx)
 {
     this.ctx = ctx;
 }
Esempio n. 48
0
 public AssemblyBuilderMonoSpecific(AssemblyBuilder ab, CompilerContext ctx)
     : base(ctx)
 {
     this.builder = ab;
 }