public CSharpCompiler() { CompilerSettings settings = new CompilerSettings (); Report report = new Report (new NullReportPrinter ()); evaluator = new Evaluator (settings, report); }
private static XmlNode GetDocCommentNode (MemberCore mc, string name, Report Report) { // FIXME: It could be even optimizable as not // to use XmlDocument. But anyways the nodes // are not kept in memory. XmlDocument doc = RootContext.Documentation.XmlDocumentation; try { XmlElement el = doc.CreateElement ("member"); el.SetAttribute ("name", name); string normalized = mc.DocComment; el.InnerXml = normalized; // csc keeps lines as written in the sources // and inserts formatting indentation (which // is different from XmlTextWriter.Formatting // one), but when a start tag contains an // endline, it joins the next line. We don't // have to follow such a hacky behavior. string [] split = normalized.Split ('\n'); int j = 0; for (int i = 0; i < split.Length; i++) { string s = split [i].TrimEnd (); if (s.Length > 0) split [j++] = s; } el.InnerXml = line_head + String.Join ( line_head, split, 0, j); return el; } catch (Exception ex) { Report.Warning (1570, 1, mc.Location, "XML comment on `{0}' has non-well-formed XML ({1})", name, ex.Message); XmlComment com = doc.CreateComment (String.Format ("FIXME: Invalid documentation markup was found for member {0}", name)); return com; } }
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); report = new Report (new ConsoleReportPrinter ()); evaluator = new Evaluator (new CompilerSettings (), report); 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); } }
// // Fixes full type name of each documented types/members up. // public void GenerateDocComment(Report r) { TypeContainer root = RootContext.ToplevelTypes; if (root.Types != null) foreach (TypeContainer tc in root.Types) DocUtil.GenerateTypeDocComment (tc, null, r); }
public static void Parse(SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report) { var file = new CompilationSourceFile(module, sourceFile); module.AddTypeContainer(file); CSharpParser parser = new CSharpParser(reader, file, report, session); parser.parse(); }
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; }
/// <summary> /// Initializes the evaluator and includes a few basic System libraries /// </summary> public Runner() { _report = new Report(new Printer(this)); _settings = new CommandLineParser(_report).ParseArguments(new string[] {}); _eval = new Evaluator(_settings, _report); _eval.Run("using System;"); _eval.Run("using System.Linq;"); _eval.Run("using System.Collections.Generic;"); }
public static void Error_InvalidConstantType(TypeSpec t, Location loc, Report Report) { if (t.IsGenericParameter) { Report.Error (1959, loc, "Type parameter `{0}' cannot be declared const", TypeManager.CSharpName (t)); } else { Report.Error (283, loc, "The type `{0}' cannot be declared const", TypeManager.CSharpName (t)); } }
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)); }
public static void GenerateCode (ModuleContainer module, ParserSession session, Report report) { GenerateDynamicPartialClasses(module, session, report); if (report.Errors > 0) return; GenerateEmbedClasses(module, session, report); if (report.Errors > 0) return; }
/// <summary> /// Initializes the evaluator and includes a few basic System libraries /// </summary> public Runner() { _report = new Report(new Printer(this)); _settings = new CommandLineParser(_report).ParseArguments (new string[] {}); _eval = new Evaluator(_settings, _report); _eval.ReferenceAssembly(typeof(System.Linq.Enumerable).Assembly); _eval.Run("using System;"); _eval.Run("using System.Collections.Generic;"); _eval.Run("using System.Linq;"); }
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 static bool InvokeCompiler(string [] args, TextWriter error) { try { var r = new Report (new StreamReportPrinter (error)); CommandLineParser cmd = new CommandLineParser (r, error); var setting = cmd.ParseArguments (args); if (setting == null || r.Errors > 0) return false; var d = new Driver (new CompilerContext (setting, r)); return d.Compile (); } finally { Reset (); } }
// <summary> // Checks the object @mod modifiers to be in @allowed. // Returns the new mask. Side effect: reports any // incorrect attributes. // </summary> public static Modifiers Check(Modifiers allowed, Modifiers mod, Modifiers def_access, Location l, Report Report) { int invalid_flags = (~(int) allowed) & ((int) mod & ((int) Modifiers.TOP - 1)); int i; if (invalid_flags == 0){ if ((mod & Modifiers.UNSAFE) != 0){ RootContext.CheckUnsafeOption (l, Report); } // // If no accessibility bits provided // then provide the defaults. // if ((mod & Modifiers.AccessibilityMask) == 0) { mod |= def_access; if (def_access != 0) mod |= Modifiers.DEFAULT_ACCESS_MODIFER; return mod; } // // Make sure that no conflicting accessibility // bits have been set. Protected+Internal is // allowed, that is why they are placed on bits // 1 and 4 (so the shift 3 basically merges them) // int a = (int) mod; a &= 15; a |= (a >> 3); a = ((a & 2) >> 1) + (a & 5); a = ((a & 4) >> 2) + (a & 3); if (a > 1) Report.Error (107, l, "More than one protection modifier specified"); return mod; } for (i = 1; i <= (int) Modifiers.TOP; i <<= 1) { if ((i & invalid_flags) == 0) continue; Error_InvalidModifier (l, Name ((Modifiers) i), Report); } return allowed & mod; }
// TypeContainer // // Generates xml doc comments (if any), and if required, // handle warning report. // internal static void GenerateTypeDocComment (TypeContainer t, DeclSpace ds, Report Report) { GenerateDocComment (t, ds, Report); if (t.DefaultStaticConstructor != null) t.DefaultStaticConstructor.GenerateDocComment (t); if (t.InstanceConstructors != null) foreach (Constructor c in t.InstanceConstructors) c.GenerateDocComment (t); if (t.Types != null) foreach (TypeContainer tc in t.Types) tc.GenerateDocComment (t); if (t.Delegates != null) foreach (Delegate de in t.Delegates) de.GenerateDocComment (t); if (t.Constants != null) foreach (Const c in t.Constants) c.GenerateDocComment (t); if (t.Fields != null) foreach (FieldBase f in t.Fields) f.GenerateDocComment (t); if (t.Events != null) foreach (Event e in t.Events) e.GenerateDocComment (t); if (t.Indexers != null) foreach (Indexer ix in t.Indexers) ix.GenerateDocComment (t); if (t.Properties != null) foreach (Property p in t.Properties) p.GenerateDocComment (t); if (t.Methods != null) foreach (MethodOrOperator m in t.Methods) m.GenerateDocComment (t); if (t.Operators != null) foreach (Operator o in t.Operators) o.GenerateDocComment (t); }
public static CompilerCompilationUnit ParseFile(string[] args, Stream input, string inputFile, ReportPrinter reportPrinter) { lock (parseLock) { try { // Driver d = Driver.Create (args, false, null, reportPrinter); // if (d == null) // return null; var r = new Report (reportPrinter); CommandLineParser cmd = new CommandLineParser (r, Console.Out); var setting = cmd.ParseArguments (args); if (setting == null || r.Errors > 0) return null; setting.Version = LanguageVersion.V_5; CompilerContext ctx = new CompilerContext (setting, r); var files = new List<CompilationSourceFile> (); var unit = new CompilationSourceFile (inputFile, inputFile, 0); var module = new ModuleContainer (ctx); unit.NamespaceContainer = new NamespaceContainer (null, module, null, unit); files.Add (unit); Location.Initialize (files); // TODO: encoding from driver SeekableStreamReader reader = new SeekableStreamReader (input, Encoding.UTF8); RootContext.ToplevelTypes = module; CSharpParser parser = new CSharpParser (reader, unit); parser.Lexer.TabSize = 1; parser.Lexer.sbag = new SpecialsBag (); parser.LocationsBag = new LocationsBag (); parser.UsingsBag = new UsingsBag (); parser.parse (); return new CompilerCompilationUnit () { ModuleCompiled = RootContext.ToplevelTypes, LocationsBag = parser.LocationsBag, UsingsBag = parser.UsingsBag, SpecialsBag = parser.Lexer.sbag, LastYYValue = parser.LastYYVal }; } finally { Reset (); } } }
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; }
// 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; }
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); }
public void ClearSession(Action callback = null) { ThreadPool.QueueUserWorkItem((o) => { _errors = new List<string>(); _warnings = new List<string>(); var report = new Report(new Printer(msg => _errors.Add(msg.Text), msg => _warnings.Add(msg.Text))); var settings = new CommandLineParser(report).ParseArguments(new string[] { }); _eval = new Evaluator(settings, report); foreach (string @namespace in Options.DefaultNamespaces) { addUsing(@namespace); } if (callback != null) callback(); }); }
public IController Create(RequestContext requestContext, Type controllerType) { CompilerSettings settings = new CompilerSettings(); Report report = new Report(new ConsoleReportPrinter()); Evaluator eval = new Evaluator(settings, report); object instance = null; bool instanceCreated = false; eval.ReferenceAssembly(typeof(Controller).Assembly); foreach (Assembly assembly in assemblies) { eval.ReferenceAssembly(assembly); } string controllerName = GetControllerName(requestContext, controllerType); string path = pathProvider.GetPath(requestContext, controllerName); CSharpControllerFile controllerFile = CSharpControllerFile.Parse(File.ReadAllText(path)); eval.Run(controllerFile.ClassSource); eval.Evaluate("new " + controllerName + "();", out instance, out instanceCreated); return (IController)instance; }
private static TypeSpec FindDocumentedTypeNonArray(MemberCore mc, string identifier, DeclSpace ds, string cref, Report r) { var types = mc.Module.Compiler.BuiltinTypes; switch (identifier) { case "int": return(types.Int); case "uint": return(types.UInt); case "short": return(types.Short); case "ushort": return(types.UShort); case "long": return(types.Long); case "ulong": return(types.ULong); case "float": return(types.Float); case "double": return(types.Double); case "char": return(types.Char); case "decimal": return(types.Decimal); case "byte": return(types.Byte); case "sbyte": return(types.SByte); case "object": return(types.Object); case "bool": return(types.Bool); case "string": return(types.String); case "void": return(types.Void); } FullNamedExpression e = ds.LookupNamespaceOrType(identifier, 0, mc.Location, false); if (e != null) { if (!(e is TypeExpr)) { return(null); } return(e.Type); } int index = identifier.LastIndexOf('.'); if (index < 0) { return(null); } var nsName = identifier.Substring(0, index); var typeName = identifier.Substring(index + 1); Namespace ns = ds.NamespaceEntry.NS.GetNamespace(nsName, false); ns = ns ?? mc.Module.GlobalRootNamespace.GetNamespace(nsName, false); if (ns != null) { var te = ns.LookupType(mc, typeName, 0, true, mc.Location); if (te != null) { return(te.Type); } } int warn; TypeSpec parent = FindDocumentedType(mc, identifier.Substring(0, index), ds, cref, r); if (parent == null) { return(null); } // no need to detect warning 419 here var ts = FindDocumentedMember(mc, parent, identifier.Substring(index + 1), null, ds, out warn, cref, false, null, r) as TypeSpec; if (ts != null) { return(ts); } return(null); }
/// <summary> /// The main virtual method for CLS-Compliant verifications. /// The method returns true if member is CLS-Compliant and false if member is not /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it /// and add their extra verifications. /// </summary> protected virtual bool VerifyClsCompliance() { if (HasClsCompliantAttribute) { if (!Module.DeclaringAssembly.HasCLSCompliantAttribute) { Attribute a = OptAttributes.Search(Module.PredefinedAttributes.CLSCompliant); if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) { Report.Warning(3021, 2, a.Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError()); } else { Report.Warning(3014, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant", GetSignatureForError()); } return(false); } if (!IsExposedFromAssembly()) { Attribute a = OptAttributes.Search(Module.PredefinedAttributes.CLSCompliant); Report.Warning(3019, 2, a.Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError()); return(false); } if ((caching_flags & Flags.ClsCompliantAttributeFalse) != 0) { if (Parent is Interface && Parent.IsClsComplianceRequired()) { Report.Warning(3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError()); } else if (Parent.Kind == MemberKind.Class && (ModFlags & Modifiers.ABSTRACT) != 0 && Parent.IsClsComplianceRequired()) { Report.Warning(3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError()); } return(false); } if (Parent.Kind != MemberKind.Namespace && Parent.Kind != 0 && !Parent.IsClsComplianceRequired()) { Attribute a = OptAttributes.Search(Module.PredefinedAttributes.CLSCompliant); Report.Warning(3018, 1, a.Location, "`{0}' cannot be marked as CLS-compliant because it is a member of non CLS-compliant type `{1}'", GetSignatureForError(), Parent.GetSignatureForError()); return(false); } } else { if (!IsExposedFromAssembly()) { return(false); } if (!Parent.IsClsComplianceRequired()) { return(false); } } if (member_name.Name [0] == '_') { Warning_IdentifierNotCompliant(); } if (member_name.TypeParameters != null) { member_name.TypeParameters.VerifyClsCompliance(); } return(true); }
// // returns a full runtime type name from a name which might // be C# specific type name. // private static TypeSpec FindDocumentedType(MemberCore mc, string name, DeclSpace ds, string cref, Report r) { bool is_array = false; string identifier = name; if (name [name.Length - 1] == ']') { string tmp = name.Substring(0, name.Length - 1).Trim(wsChars); if (tmp [tmp.Length - 1] == '[') { identifier = tmp.Substring(0, tmp.Length - 1).Trim(wsChars); is_array = true; } } TypeSpec t = FindDocumentedTypeNonArray(mc, identifier, ds, cref, r); if (t != null && is_array) { t = ArrayContainer.MakeType(mc.Module, t); } return(t); }
public CommandLineParser (Report report) : this (report, Console.Out) { }
public void WarningDisable (Location location, int code, Report Report) { if (Report.CheckWarningCode (code, location)) regions.Add (new Disable (location.Row, code)); }
// // Processes "see" or "seealso" elements. // Checks cref attribute. // private static void HandleXrefCommon(MemberCore mc, DeclSpace ds, XmlElement xref, Report Report) { string cref = xref.GetAttribute("cref").Trim(wsChars); // when, XmlReader, "if (cref == null)" if (!xref.HasAttribute("cref")) { return; } if (cref.Length == 0) { Report.Warning(1001, 1, mc.Location, "Identifier expected"); } // ... and continue until CS1584. string signature; // "x:" are stripped string name; // method invokation "(...)" are removed string parameters; // method parameter list // When it found '?:' ('T:' 'M:' 'F:' 'P:' 'E:' etc.), // MS ignores not only its member kind, but also // the entire syntax correctness. Nor it also does // type fullname resolution i.e. "T:List(int)" is kept // as T:List(int), not // T:System.Collections.Generic.List<System.Int32> if (cref.Length > 2 && cref [1] == ':') { return; } else { signature = cref; } // Also note that without "T:" any generic type // indication fails. int parens_pos = signature.IndexOf('('); int brace_pos = parens_pos >= 0 ? -1 : signature.IndexOf('['); if (parens_pos > 0 && signature [signature.Length - 1] == ')') { name = signature.Substring(0, parens_pos).Trim(wsChars); parameters = signature.Substring(parens_pos + 1, signature.Length - parens_pos - 2).Trim(wsChars); } else if (brace_pos > 0 && signature [signature.Length - 1] == ']') { name = signature.Substring(0, brace_pos).Trim(wsChars); parameters = signature.Substring(brace_pos + 1, signature.Length - brace_pos - 2).Trim(wsChars); } else { name = signature; parameters = null; } Normalize(mc, ref name, Report); string identifier = GetBodyIdentifierFromName(name); // Check if identifier is valid. // This check is not necessary to mark as error, but // csc specially reports CS1584 for wrong identifiers. string [] name_elems = identifier.Split('.'); for (int i = 0; i < name_elems.Length; i++) { string nameElem = GetBodyIdentifierFromName(name_elems [i]); if (i > 0) { Normalize(mc, ref nameElem, Report); } if (!Tokenizer.IsValidIdentifier(nameElem) && nameElem.IndexOf("operator") < 0) { Report.Warning(1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'", mc.GetSignatureForError(), cref); xref.SetAttribute("cref", "!:" + signature); return; } } // check if parameters are valid AParametersCollection parameter_types; if (parameters == null) { parameter_types = null; } else if (parameters.Length == 0) { parameter_types = ParametersCompiled.EmptyReadOnlyParameters; } else { string [] param_list = parameters.Split(','); var plist = new List <TypeSpec> (); for (int i = 0; i < param_list.Length; i++) { string param_type_name = param_list [i].Trim(wsChars); Normalize(mc, ref param_type_name, Report); TypeSpec param_type = FindDocumentedType(mc, param_type_name, ds, cref, Report); if (param_type == null) { Report.Warning(1580, 1, mc.Location, "Invalid type for parameter `{0}' in XML comment cref attribute `{1}'", (i + 1).ToString(), cref); return; } plist.Add(param_type); } parameter_types = ParametersCompiled.CreateFullyResolved(plist.ToArray()); } TypeSpec type = FindDocumentedType(mc, name, ds, cref, Report); if (type != null // delegate must not be referenced with args && (!type.IsDelegate || parameter_types == null)) { string result = GetSignatureForDoc(type) + (brace_pos < 0 ? String.Empty : signature.Substring(brace_pos)); xref.SetAttribute("cref", "T:" + result); return; // a type } int period = name.LastIndexOf('.'); if (period > 0) { string typeName = name.Substring(0, period); string member_name = name.Substring(period + 1); string lookup_name = member_name == "this" ? MemberCache.IndexerNameAlias : member_name; Normalize(mc, ref lookup_name, Report); Normalize(mc, ref member_name, Report); type = FindDocumentedType(mc, typeName, ds, cref, Report); int warn_result; if (type != null) { var mi = FindDocumentedMember(mc, type, lookup_name, parameter_types, ds, out warn_result, cref, true, name, Report); if (warn_result > 0) { return; } if (mi != null) { // we cannot use 'type' directly // to get its name, since mi // could be from DeclaringType // for nested types. xref.SetAttribute("cref", GetMemberDocHead(mi) + GetSignatureForDoc(mi.DeclaringType) + "." + member_name + GetParametersFormatted(mi)); return; // a member of a type } } } else { int warn_result; var mi = FindDocumentedMember(mc, ds.PartialContainer.Definition, name, parameter_types, ds, out warn_result, cref, true, name, Report); if (warn_result > 0) { return; } if (mi != null) { // we cannot use 'type' directly // to get its name, since mi // could be from DeclaringType // for nested types. xref.SetAttribute("cref", GetMemberDocHead(mi) + GetSignatureForDoc(mi.DeclaringType) + "." + name + GetParametersFormatted(mi)); return; // local member name } } // It still might be part of namespace name. Namespace ns = ds.NamespaceEntry.NS.GetNamespace(name, false); if (ns != null) { xref.SetAttribute("cref", "N:" + ns.GetSignatureForError()); return; // a namespace } if (mc.Module.GlobalRootNamespace.IsNamespace(name)) { xref.SetAttribute("cref", "N:" + name); return; // a namespace } Report.Warning(1574, 1, mc.Location, "XML comment on `{0}' has cref attribute `{1}' that could not be resolved", mc.GetSignatureForError(), cref); xref.SetAttribute("cref", "!:" + name); }
public void Error_DuplicateName(Report r) { r.Error(100, Location, "The parameter name `{0}' is a duplicate", Name); }
public override void Error_FinallyClause(Report Report) { Report.Error(1625, loc, "Cannot yield in the body of a finally clause"); }
public static void Parse(SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report) { var file = new CompilationSourceFile(module, sourceFile); module.AddTypeContainer(file); if (sourceFile.FileType == SourceFileType.CSharp) { CSharpParser parser = new CSharpParser(reader, file, session); parser.parse(); } else { PlayScriptParser parser = new PlayScriptParser(reader, file, session); parser.parsing_playscript = sourceFile.PsExtended; parser.parse(); } }
public CompilerContext (CompilerSettings settings, ReportPrinter reportPrinter) { this.settings = settings; this.report = new Report (this, reportPrinter); this.builtin_types = new BuiltinTypes (); this.TimeReporter = DisabledTimeReporter; }
public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report) { Report.SymbolRelatedToPreviousError (static_class); Report.Error (723, loc, "`{0}': cannot declare variables of static types", variable_name); }
public static void Error_1008(Location loc, Report Report) { Report.Error(1008, loc, "Type byte, sbyte, short, ushort, int, uint, long or ulong expected"); }
SyntaxTree Parse(ITextSource program, string fileName, int initialLine, int initialColumn) { lock (parseLock) { errorReportPrinter = new ErrorReportPrinter(""); var ctx = new CompilerContext(compilerSettings.ToMono(), errorReportPrinter); ctx.Settings.TabSize = 1; var reader = new SeekableStreamReader(program); var file = new SourceFile(fileName, fileName, 0); Location.Initialize(new List<SourceFile>(new [] { file })); var module = new ModuleContainer(ctx); var session = new ParserSession(); session.LocationsBag = new LocationsBag(); var report = new Report(ctx, errorReportPrinter); var parser = Driver.Parse(reader, file, module, session, report, initialLine - 1, initialColumn - 1); var top = new CompilerCompilationUnit { ModuleCompiled = module, LocationsBag = session.LocationsBag, SpecialsBag = parser.Lexer.sbag, Conditionals = parser.Lexer.SourceFile.Conditionals }; var unit = Parse(top, fileName); unit.Errors.AddRange(errorReportPrinter.Errors); CompilerCallableEntryPoint.Reset(); return unit; } }
protected override bool DoDefineMembers() { TypeSpec bt; bool has_task_return_type = false; var istate_machine = Module.PredefinedTypes.IAsyncStateMachine; MethodSpec set_statemachine; if (return_type.IsCustomTaskType()) { // // TODO: Would be nice to cache all this on per-type basis // var btypes = Compiler.BuiltinTypes; bt = return_type.MemberDefinition.GetAsyncMethodBuilder(); TypeSpec bt_inflated; if (return_type.IsGeneric) { bt_inflated = bt.MakeGenericType(Module, bt.MemberDefinition.TypeParameters); } else { bt_inflated = bt; } var set_result_sign = MemberFilter.Method("SetResult", 0, ParametersCompiled.CreateFullyResolved(bt.MemberDefinition.TypeParameters), btypes.Void); set_result = new PredefinedMember <MethodSpec> (Module, bt, set_result_sign).Resolve(Location); var set_exception_sign = MemberFilter.Method("SetException", 0, ParametersCompiled.CreateFullyResolved(btypes.Exception), btypes.Void); set_exception = new PredefinedMember <MethodSpec> (Module, bt, set_exception_sign).Resolve(Location); var builder_factory_sign = MemberFilter.Method("Create", 0, ParametersCompiled.EmptyReadOnlyParameters, bt_inflated); builder_factory = new PredefinedMember <MethodSpec> (Module, bt, builder_factory_sign).Resolve(Location); if (builder_factory?.IsStatic == false) { throw new NotImplementedException("report better error message"); } var builder_start_sign = MemberFilter.Method("Start", 1, new ParametersImported( new [] { new ParameterData(null, Parameter.Modifier.REF), }, new [] { new TypeParameterSpec(0, null, SpecialConstraint.None, Variance.None, null), }, false), btypes.Void); builder_start = new PredefinedMember <MethodSpec> (Module, bt, builder_start_sign).Resolve(Location); if (!istate_machine.Define()) { return(false); } var set_statemachine_sign = MemberFilter.Method("SetStateMachine", 0, ParametersCompiled.CreateFullyResolved(istate_machine.TypeSpec), btypes.Void); set_statemachine = new PredefinedMember <MethodSpec> (Module, bt, set_statemachine_sign).Resolve(Location);; var task_sign = MemberFilter.Property("Task", return_type.MemberDefinition as TypeSpec); task = new PredefinedMember <PropertySpec> (Module, bt, task_sign).Resolve(Location); if (set_result == null || set_exception == null || builder_factory == null || builder_start == null || set_statemachine == null || task == null || !Module.PredefinedTypes.INotifyCompletion.Define()) { return(false); } has_task_return_type = return_type.IsGeneric; } else { PredefinedType builder_type; PredefinedMember <MethodSpec> bf; PredefinedMember <MethodSpec> bs; PredefinedMember <MethodSpec> sr; PredefinedMember <MethodSpec> se; PredefinedMember <MethodSpec> sm; var pred_members = Module.PredefinedMembers; if (return_type.Kind == MemberKind.Void) { builder_type = Module.PredefinedTypes.AsyncVoidMethodBuilder; bf = pred_members.AsyncVoidMethodBuilderCreate; bs = pred_members.AsyncVoidMethodBuilderStart; sr = pred_members.AsyncVoidMethodBuilderSetResult; se = pred_members.AsyncVoidMethodBuilderSetException; sm = pred_members.AsyncVoidMethodBuilderSetStateMachine; } else if (return_type == Module.PredefinedTypes.Task.TypeSpec) { builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilder; bf = pred_members.AsyncTaskMethodBuilderCreate; bs = pred_members.AsyncTaskMethodBuilderStart; sr = pred_members.AsyncTaskMethodBuilderSetResult; se = pred_members.AsyncTaskMethodBuilderSetException; sm = pred_members.AsyncTaskMethodBuilderSetStateMachine; task = pred_members.AsyncTaskMethodBuilderTask.Get(); } else { builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilderGeneric; bf = pred_members.AsyncTaskMethodBuilderGenericCreate; bs = pred_members.AsyncTaskMethodBuilderGenericStart; sr = pred_members.AsyncTaskMethodBuilderGenericSetResult; se = pred_members.AsyncTaskMethodBuilderGenericSetException; sm = pred_members.AsyncTaskMethodBuilderGenericSetStateMachine; task = pred_members.AsyncTaskMethodBuilderGenericTask.Get(); has_task_return_type = true; } set_result = sr.Get(); set_exception = se.Get(); builder_factory = bf.Get(); builder_start = bs.Get(); set_statemachine = sm.Get(); if (!builder_type.Define() || !istate_machine.Define() || set_result == null || builder_factory == null || set_exception == null || set_statemachine == null || builder_start == null || !Module.PredefinedTypes.INotifyCompletion.Define()) { Report.Error(1993, Location, "Cannot find compiler required types for asynchronous functions support. Are you targeting the wrong framework version?"); return(base.DoDefineMembers()); } bt = builder_type.TypeSpec; } // // Inflate generic Task types // if (has_task_return_type) { var task_return_type = return_type.TypeArguments; if (mutator != null) { task_return_type = mutator.Mutate(task_return_type); } bt = bt.MakeGenericType(Module, task_return_type); set_result = MemberCache.GetMember(bt, set_result); set_exception = MemberCache.GetMember(bt, set_exception); set_statemachine = MemberCache.GetMember(bt, set_statemachine); if (task != null) { task = MemberCache.GetMember(bt, task); } } builder = AddCompilerGeneratedField("$builder", new TypeExpression(bt, Location)); Field rfield; if (has_task_return_type && HasAwaitInsideFinally) { // // Special case async block with return value from finally clause. In such case // we rewrite all return expresison stores to stfld to $return. Instead of treating // returns outside of finally and inside of finally differently. // rfield = AddCompilerGeneratedField("$return", new TypeExpression(bt.TypeArguments [0], Location)); } else { rfield = null; } var set_state_machine = new Method(this, new TypeExpression(Compiler.BuiltinTypes.Void, Location), Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PUBLIC, new MemberName("SetStateMachine"), ParametersCompiled.CreateFullyResolved( new Parameter(new TypeExpression(istate_machine.TypeSpec, Location), "stateMachine", Parameter.Modifier.NONE, null, Location), istate_machine.TypeSpec), null); ToplevelBlock block = new ToplevelBlock(Compiler, set_state_machine.ParameterInfo, Location); block.IsCompilerGenerated = true; set_state_machine.Block = block; Members.Add(set_state_machine); if (!base.DoDefineMembers()) { return(false); } // // Fabricates SetStateMachine method // // public void SetStateMachine (IAsyncStateMachine stateMachine) // { // $builder.SetStateMachine (stateMachine); // } // var mg = MethodGroupExpr.CreatePredefined(set_statemachine, bt, Location); mg.InstanceExpression = new FieldExpr(builder, Location); var param_reference = block.GetParameterReference(0, Location); param_reference.Type = istate_machine.TypeSpec; param_reference.eclass = ExprClass.Variable; var args = new Arguments(1); args.Add(new Argument(param_reference)); set_state_machine.Block.AddStatement(new StatementExpression(new Invocation(mg, args))); if (has_task_return_type) { if (rfield != null) { HoistedReturnValue = new FieldExpr(rfield, Location) { InstanceExpression = new CompilerGeneratedThis(CurrentType, Location.Null) }; } else { HoistedReturnValue = TemporaryVariableReference.Create(bt.TypeArguments [0], StateMachineMethod.Block, Location); } } return(true); }
// // Returns a MemberInfo that is referenced in XML documentation // (by "see" or "seealso" elements). // private static MemberSpec FindDocumentedMember(MemberCore mc, TypeSpec type, string member_name, AParametersCollection param_list, DeclSpace ds, out int warning_type, string cref, bool warn419, string name_for_error, Report r) { // for (; type != null; type = type.DeclaringType) { var mi = FindDocumentedMemberNoNest( mc, type, member_name, param_list, ds, out warning_type, cref, warn419, name_for_error, r); if (mi != null) { return(mi); // new FoundMember (type, mi); } // } warning_type = 0; return(null); }
public void Parse(SourceFile file, ModuleContainer module, ParserSession session, Report report) { Stream input; try { input = File.OpenRead(file.Name); } catch { report.Error(2001, "Source file `{0}' could not be found", file.Name); return; } // Check 'MZ' header if (input.ReadByte() == 77 && input.ReadByte() == 90) { report.Error(2015, "Source file `{0}' is a binary file and not a text file", file.Name); input.Close(); return; } input.Position = 0; SeekableStreamReader reader = new SeekableStreamReader(input, ctx.Settings.Encoding, session.StreamReaderBuffer); Parse(reader, file, module, session, report); if (ctx.Settings.GenerateDebugInfo && report.Errors == 0 && !file.HasChecksum) { input.Position = 0; var checksum = session.GetChecksumAlgorithm(); file.SetChecksum(checksum.ComputeHash(input)); } reader.Dispose(); input.Close(); }
private static MemberSpec FindDocumentedMemberNoNest( MemberCore mc, TypeSpec type, string member_name, AParametersCollection param_list, DeclSpace ds, out int warning_type, string cref, bool warn419, string name_for_error, Report Report) { warning_type = 0; // var filter = new MemberFilter (member_name, 0, MemberKind.All, param_list, null); IList <MemberSpec> found = null; while (type != null && found == null) { found = MemberCache.FindMembers(type, member_name, false); type = type.DeclaringType; } if (found == null) { return(null); } if (warn419 && found.Count > 1) { Report419(mc, name_for_error, found.ToArray(), Report); } return(found [0]); /* * if (param_list == null) { * // search for fields/events etc. * mis = TypeManager.MemberLookup (type, null, * type, MemberKind.All, * BindingRestriction.None, * member_name, null); * mis = FilterOverridenMembersOut (mis); * if (mis == null || mis.Length == 0) * return null; * if (warn419 && IsAmbiguous (mis)) * Report419 (mc, name_for_error, mis, Report); * return mis [0]; * } * * MethodSignature msig = new MethodSignature (member_name, null, param_list); * mis = FindMethodBase (type, * BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance, * msig); * * if (warn419 && mis.Length > 0) { * if (IsAmbiguous (mis)) * Report419 (mc, name_for_error, mis, Report); * return mis [0]; * } * * // search for operators (whose parameters exactly * // matches with the list) and possibly report CS1581. * string oper = null; * string return_type_name = null; * if (member_name.StartsWith ("implicit operator ")) { * Operator.GetMetadataName (Operator.OpType.Implicit); * return_type_name = member_name.Substring (18).Trim (wsChars); * } * else if (member_name.StartsWith ("explicit operator ")) { * oper = Operator.GetMetadataName (Operator.OpType.Explicit); * return_type_name = member_name.Substring (18).Trim (wsChars); * } * else if (member_name.StartsWith ("operator ")) { * oper = member_name.Substring (9).Trim (wsChars); * switch (oper) { * // either unary or binary * case "+": * oper = param_list.Length == 2 ? * Operator.GetMetadataName (Operator.OpType.Addition) : * Operator.GetMetadataName (Operator.OpType.UnaryPlus); * break; * case "-": * oper = param_list.Length == 2 ? * Operator.GetMetadataName (Operator.OpType.Subtraction) : * Operator.GetMetadataName (Operator.OpType.UnaryNegation); * break; * default: * oper = Operator.GetMetadataName (oper); * if (oper != null) * break; * * warning_type = 1584; * Report.Warning (1020, 1, mc.Location, "Overloadable {0} operator is expected", param_list.Length == 2 ? "binary" : "unary"); * Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'", * mc.GetSignatureForError (), cref); * return null; * } * } * // here we still don't consider return type (to * // detect CS1581 or CS1002+CS1584). * msig = new MethodSignature (oper, null, param_list); * * mis = FindMethodBase (type, * BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance, * msig); * if (mis.Length == 0) * return null; // CS1574 * var mi = mis [0]; * TypeSpec expected = mi is MethodSpec ? * ((MethodSpec) mi).ReturnType : * mi is PropertySpec ? * ((PropertySpec) mi).PropertyType : * null; * if (return_type_name != null) { * TypeSpec returnType = FindDocumentedType (mc, return_type_name, ds, cref, Report); * if (returnType == null || returnType != expected) { * warning_type = 1581; * Report.Warning (1581, 1, mc.Location, "Invalid return type in XML comment cref attribute `{0}'", cref); * return null; * } * } * return mis [0]; */ }
// // Generates xml doc comments (if any), and if required, // handle warning report. // internal static void GenerateDocComment(MemberCore mc, DeclSpace ds, Report Report) { if (mc.DocComment != null) { string name = mc.GetDocCommentName(ds); XmlNode n = GetDocCommentNode(mc, name, Report); XmlElement el = n as XmlElement; if (el != null) { mc.OnGenerateDocComment(el); // FIXME: it could be done with XmlReader XmlNodeList nl = n.SelectNodes(".//include"); if (nl.Count > 0) { // It could result in current node removal, so prepare another list to iterate. var al = new List <XmlNode> (nl.Count); foreach (XmlNode inc in nl) { al.Add(inc); } foreach (XmlElement inc in al) { if (!HandleInclude(mc, inc, Report)) { inc.ParentNode.RemoveChild(inc); } } } // FIXME: it could be done with XmlReader DeclSpace ds_target = mc as DeclSpace; if (ds_target == null) { ds_target = ds; } foreach (XmlElement see in n.SelectNodes(".//see")) { HandleSee(mc, ds_target, see, Report); } foreach (XmlElement seealso in n.SelectNodes(".//seealso")) { HandleSeeAlso(mc, ds_target, seealso, Report); } foreach (XmlElement see in n.SelectNodes(".//exception")) { HandleException(mc, ds_target, see, Report); } } n.WriteTo(mc.Compiler.Settings.Documentation.XmlCommentOutput); } else if (mc.IsExposedFromAssembly()) { Constructor c = mc as Constructor; if (c == null || !c.IsDefault()) { Report.Warning(1591, 4, mc.Location, "Missing XML comment for publicly visible type or member `{0}'", mc.GetSignatureForError()); } } }
CompiledMethod CompileBlock (Class host, Undo undo, Report Report) { #if STATIC throw new NotSupportedException (); #else string current_debug_name = "eval-" + count + ".dll"; ++count; AssemblyDefinitionDynamic assembly; AssemblyBuilderAccess access; if (Environment.GetEnvironmentVariable ("SAVE") != null) { access = AssemblyBuilderAccess.RunAndSave; assembly = new AssemblyDefinitionDynamic (module, current_debug_name, current_debug_name); assembly.Importer = importer; } else { #if NET_4_0 access = AssemblyBuilderAccess.RunAndCollect; #else access = AssemblyBuilderAccess.Run; #endif assembly = new AssemblyDefinitionDynamic (module, current_debug_name); } assembly.Create (AppDomain.CurrentDomain, access); Method expression_method; if (host != null) { var base_class_imported = importer.ImportType (base_class); var baseclass_list = new List<FullNamedExpression> (1) { new TypeExpression (base_class_imported, host.Location) }; host.SetBaseTypes (baseclass_list); expression_method = (Method) host.Members[0]; if ((expression_method.ModFlags & Modifiers.ASYNC) != 0) { // // Host method is async. When WaitOnTask is set we wrap it with wait // // void AsyncWait (ref object $retval) { // $retval = Host(); // ((Task)$retval).Wait(); // When WaitOnTask is set // } // var p = new ParametersCompiled ( new Parameter (new TypeExpression (module.Compiler.BuiltinTypes.Object, Location.Null), "$retval", Parameter.Modifier.REF, null, Location.Null) ); var method = new Method(host, new TypeExpression(module.Compiler.BuiltinTypes.Void, Location.Null), Modifiers.PUBLIC | Modifiers.STATIC, new MemberName("AsyncWait"), p, null); method.Block = new ToplevelBlock(method.Compiler, p, Location.Null); method.Block.AddStatement(new StatementExpression (new SimpleAssign( new SimpleName(p [0].Name, Location.Null), new Invocation(new SimpleName(expression_method.MemberName.Name, Location.Null), new Arguments(0)), Location.Null), Location.Null)); if (WaitOnTask) { var task = new Cast (expression_method.TypeExpression, new SimpleName (p [0].Name, Location.Null), Location.Null); method.Block.AddStatement (new StatementExpression (new Invocation ( new MemberAccess (task, "Wait", Location.Null), new Arguments (0)), Location.Null)); } host.AddMember(method); expression_method = method; } host.CreateContainer(); host.DefineContainer(); host.Define(); } else { expression_method = null; } module.CreateContainer (); // Disable module and source file re-definition checks module.EnableRedefinition (); source_file.EnableRedefinition (); module.Define (); if (Report.Errors != 0){ if (undo != null) undo.ExecuteUndo (); return null; } if (host != null){ host.PrepareEmit (); host.EmitContainer (); } module.EmitContainer (); if (Report.Errors != 0){ if (undo != null) undo.ExecuteUndo (); return null; } module.CloseContainer (); if (host != null) host.CloseContainer (); if (access == AssemblyBuilderAccess.RunAndSave) assembly.Save (); if (host == null) return null; // // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant // work from MethodBuilders. Retarded, I know. // var tt = assembly.Builder.GetType (host.TypeBuilder.Name); var mi = tt.GetMethod (expression_method.MemberName.Name); // // We need to then go from FieldBuilder to FieldInfo // or reflection gets confused (it basically gets confused, and variables override each // other). // foreach (var member in host.Members) { var field = member as Field; if (field == null) continue; var fi = tt.GetField (field.Name); Tuple<FieldSpec, FieldInfo> old; // If a previous value was set, nullify it, so that we do // not leak memory if (fields.TryGetValue (field.Name, out old)) { if (old.Item1.MemberType.IsStruct) { // // TODO: Clear fields for structs // } else { try { old.Item2.SetValue (null, null); } catch { } } } fields[field.Name] = Tuple.Create (field.Spec, fi); } return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi); #endif }
// // Handles <see> elements. // private static void HandleSee(MemberCore mc, DeclSpace ds, XmlElement see, Report r) { HandleXrefCommon(mc, ds, see, r); }
CompiledMethod CompileBlock(Class host, Undo undo, Report Report) { #if STATIC throw new NotSupportedException(); #else string current_debug_name = "eval-" + count + ".dll"; ++count; AssemblyDefinitionDynamic assembly; AssemblyBuilderAccess access; if (Environment.GetEnvironmentVariable("SAVE") != null) { access = AssemblyBuilderAccess.RunAndSave; assembly = new AssemblyDefinitionDynamic(module, current_debug_name, current_debug_name); assembly.Importer = importer; } else { #if NET_4_0 access = AssemblyBuilderAccess.RunAndCollect; #else access = AssemblyBuilderAccess.Run; #endif assembly = new AssemblyDefinitionDynamic(module, current_debug_name); } assembly.Create(AppDomain.CurrentDomain, access); Method expression_method; if (host != null) { var base_class_imported = importer.ImportType(base_class); var baseclass_list = new List <FullNamedExpression> (1) { new TypeExpression(base_class_imported, host.Location) }; host.AddBasesForPart(baseclass_list); host.CreateContainer(); host.DefineContainer(); host.Define(); expression_method = (Method)host.Members[0]; } else { expression_method = null; } module.CreateContainer(); // Disable module and source file re-definition checks module.EnableRedefinition(); source_file.EnableRedefinition(); module.Define(); if (Report.Errors != 0) { if (undo != null) { undo.ExecuteUndo(); } return(null); } if (host != null) { host.PrepareEmit(); host.EmitContainer(); } module.EmitContainer(); if (Report.Errors != 0) { if (undo != null) { undo.ExecuteUndo(); } return(null); } module.CloseContainer(); if (host != null) { host.CloseContainer(); } if (access == AssemblyBuilderAccess.RunAndSave) { assembly.Save(); } if (host == null) { return(null); } // // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant // work from MethodBuilders. Retarded, I know. // var tt = assembly.Builder.GetType(host.TypeBuilder.Name); var mi = tt.GetMethod(expression_method.MemberName.Name); // // We need to then go from FieldBuilder to FieldInfo // or reflection gets confused (it basically gets confused, and variables override each // other). // foreach (var member in host.Members) { var field = member as Field; if (field == null) { continue; } var fi = tt.GetField(field.Name); Tuple <FieldSpec, FieldInfo> old; // If a previous value was set, nullify it, so that we do // not leak memory if (fields.TryGetValue(field.Name, out old)) { if (old.Item1.MemberType.IsStruct) { // // TODO: Clear fields for structs // } else { try { old.Item2.SetValue(null, null); } catch { } } } fields[field.Name] = Tuple.Create(field.Spec, fi); } return((CompiledMethod)System.Delegate.CreateDelegate(typeof(CompiledMethod), mi)); #endif }
// // Handles <exception> elements. // private static void HandleException(MemberCore mc, DeclSpace ds, XmlElement seealso, Report r) { HandleXrefCommon(mc, ds, seealso, r); }
public CommandLineParser (Report report, TextWriter messagesOutput) { this.report = report; this.output = messagesOutput; }
// TypeContainer // // Generates xml doc comments (if any), and if required, // handle warning report. // internal static void GenerateTypeDocComment(TypeContainer t, DeclSpace ds, Report Report) { GenerateDocComment(t, ds, Report); if (t.DefaultStaticConstructor != null) { t.DefaultStaticConstructor.GenerateDocComment(t); } if (t.InstanceConstructors != null) { foreach (Constructor c in t.InstanceConstructors) { c.GenerateDocComment(t); } } if (t.Types != null) { foreach (TypeContainer tc in t.Types) { tc.GenerateDocComment(t); } } if (t.Constants != null) { foreach (Const c in t.Constants) { c.GenerateDocComment(t); } } if (t.Fields != null) { foreach (FieldBase f in t.Fields) { f.GenerateDocComment(t); } } if (t.Events != null) { foreach (Event e in t.Events) { e.GenerateDocComment(t); } } if (t.Indexers != null) { foreach (Indexer ix in t.Indexers) { ix.GenerateDocComment(t); } } if (t.Properties != null) { foreach (Property p in t.Properties) { p.GenerateDocComment(t); } } if (t.Methods != null) { foreach (MethodOrOperator m in t.Methods) { m.GenerateDocComment(t); } } if (t.Operators != null) { foreach (Operator o in t.Operators) { o.GenerateDocComment(t); } } }
protected void Warning_IdentifierNotCompliant() { Report.Warning(3008, 1, MemberName.Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError()); }
public override void Error_FinallyClause(Report Report) { Report.Error (1625, loc, "Cannot yield in the body of a finally clause"); }
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); }
/* /// <summary> /// Parses a file snippet; guessing what the code snippet represents (whole file, type members, block, type reference, expression). /// </summary> public AstNode ParseSnippet (string code) { // TODO: add support for parsing a part of a file throw new NotImplementedException (); } */ public DocumentationReference ParseDocumentationReference(string cref) { // see Mono.CSharp.DocumentationBuilder.HandleXrefCommon if (cref == null) throw new ArgumentNullException("cref"); // Additional symbols for < and > are allowed for easier XML typing cref = cref.Replace('{', '<').Replace('}', '>'); lock (parseLock) { errorReportPrinter = new ErrorReportPrinter(""); var ctx = new CompilerContext(compilerSettings.ToMono(), errorReportPrinter); ctx.Settings.TabSize = 1; var reader = new SeekableStreamReader(new StringTextSource(cref)); var file = new SourceFile("", "", 0); Location.Initialize(new List<SourceFile>(new [] { file })); var module = new ModuleContainer(ctx); module.DocumentationBuilder = new DocumentationBuilder(module); var source_file = new CompilationSourceFile(module); var report = new Report(ctx, errorReportPrinter); var session = new ParserSession(); session.LocationsBag = new LocationsBag(); var parser = new Mono.CSharp.CSharpParser(reader, source_file, report, session); parser.Lexer.Line += initialLocation.Line - 1; parser.Lexer.Column += initialLocation.Column - 1; parser.Lexer.putback_char = Tokenizer.DocumentationXref; parser.Lexer.parsing_generic_declaration_doc = true; parser.parse(); if (report.Errors > 0) { // Report.Warning (1584, 1, mc.Location, "XML comment on `{0}' has syntactically incorrect cref attribute `{1}'", // mc.GetSignatureForError (), cref); } var conversionVisitor = new ConversionVisitor(false, session.LocationsBag); var docRef = conversionVisitor.ConvertXmlDoc(module.DocumentationBuilder); CompilerCallableEntryPoint.Reset(); return docRef; } }
CompiledMethod CompileBlock (Class host, Undo undo, Report Report) { #if STATIC throw new NotSupportedException (); #else string current_debug_name = "eval-" + count + ".dll"; ++count; AssemblyDefinitionDynamic assembly; AssemblyBuilderAccess access; if (Environment.GetEnvironmentVariable ("SAVE") != null) { access = AssemblyBuilderAccess.RunAndSave; assembly = new AssemblyDefinitionDynamic (module, current_debug_name, current_debug_name); assembly.Importer = importer; } else { #if NET_4_0 access = AssemblyBuilderAccess.RunAndCollect; #else access = AssemblyBuilderAccess.Run; #endif assembly = new AssemblyDefinitionDynamic (module, current_debug_name); } assembly.Create (AppDomain.CurrentDomain, access); Method expression_method; if (host != null) { var base_class_imported = importer.ImportType (base_class); var baseclass_list = new List<FullNamedExpression> (1) { new TypeExpression (base_class_imported, host.Location) }; host.AddBasesForPart (baseclass_list); host.CreateContainer (); host.DefineContainer (); host.Define (); expression_method = (Method) host.Members[0]; } else { expression_method = null; } module.CreateContainer (); source_file.EnableUsingClausesRedefinition (); module.Define (); if (Report.Errors != 0){ if (undo != null) undo.ExecuteUndo (); return null; } if (host != null){ host.EmitContainer (); } module.EmitContainer (); if (Report.Errors != 0){ if (undo != null) undo.ExecuteUndo (); return null; } module.CloseContainer (); if (host != null) host.CloseContainer (); if (access == AssemblyBuilderAccess.RunAndSave) assembly.Save (); if (host == null) return null; // // Unlike Mono, .NET requires that the MethodInfo is fetched, it cant // work from MethodBuilders. Retarded, I know. // var tt = assembly.Builder.GetType (host.TypeBuilder.Name); var mi = tt.GetMethod (expression_method.MemberName.Name); // // We need to then go from FieldBuilder to FieldInfo // or reflection gets confused (it basically gets confused, and variables override each // other). // foreach (var member in host.Members) { var field = member as Field; if (field == null) continue; var fi = tt.GetField (field.Name); Tuple<FieldSpec, FieldInfo> old; // If a previous value was set, nullify it, so that we do // not leak memory if (fields.TryGetValue (field.Name, out old)) { if (old.Item1.MemberType.IsStruct) { // // TODO: Clear fields for structs // } else { try { old.Item2.SetValue (null, null); } catch { } } } fields[field.Name] = Tuple.Create (field.Spec, fi); } return (CompiledMethod) System.Delegate.CreateDelegate (typeof (CompiledMethod), mi); #endif }
public void Warning_UselessOptionalParameter(Report Report) { Report.Warning(1066, 1, Location, "The default value specified for optional parameter `{0}' will never be used", Name); }
public static void Error1599 (Location loc, TypeSpec t, Report Report) { Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", t.GetSignatureForError ()); }
protected override bool DoDefineMembers() { var builtin_types = Compiler.BuiltinTypes; var ctor_parameters = ParametersCompiled.CreateFullyResolved( new [] { new Parameter(new TypeExpression(builtin_types.Object, Location), "object", Parameter.Modifier.NONE, null, Location), new Parameter(new TypeExpression(builtin_types.IntPtr, Location), "method", Parameter.Modifier.NONE, null, Location) }, new [] { builtin_types.Object, builtin_types.IntPtr } ); Constructor = new Constructor(this, Constructor.ConstructorName, Modifiers.PUBLIC, null, ctor_parameters, Location); Constructor.Define(); // // Here the various methods like Invoke, BeginInvoke etc are defined // // First, call the `out of band' special method for // defining recursively any types we need: // var p = parameters; if (!p.Resolve(this)) { return(false); } // // Invoke method // // Check accessibility foreach (var partype in p.Types) { if (!IsAccessibleAs(partype)) { Report.SymbolRelatedToPreviousError(partype); Report.Error(59, Location, "Inconsistent accessibility: parameter type `{0}' is less accessible than delegate `{1}'", partype.GetSignatureForError(), GetSignatureForError()); } } var ret_type = ReturnType.ResolveAsType(this); if (ret_type == null) { return(false); } // // We don't have to check any others because they are all // guaranteed to be accessible - they are standard types. // if (!IsAccessibleAs(ret_type)) { Report.SymbolRelatedToPreviousError(ret_type); Report.Error(58, Location, "Inconsistent accessibility: return type `" + ret_type.GetSignatureForError() + "' is less " + "accessible than delegate `" + GetSignatureForError() + "'"); return(false); } CheckProtectedModifier(); if (Compiler.Settings.StdLib && ret_type.IsSpecialRuntimeType) { Method.Error1599(Location, ret_type, Report); return(false); } VarianceDecl.CheckTypeVariance(ret_type, Variance.Covariant, this); var resolved_rt = new TypeExpression(ret_type, Location); InvokeBuilder = new Method(this, resolved_rt, MethodModifiers, new MemberName(InvokeMethodName), p, null); InvokeBuilder.Define(); // // Don't emit async method for compiler generated delegates (e.g. dynamic site containers) // if (!IsCompilerGenerated) { DefineAsyncMethods(resolved_rt); } return(true); }
public CommandLineParser (TextWriter errorOutput, TextWriter messagesOutput) { var rp = new StreamReportPrinter (errorOutput); parser_settings = new CompilerSettings (); report = new Report (new CompilerContext (parser_settings, rp), rp); this.output = messagesOutput; }
public static CSharpParser Parse(SeekableStreamReader reader, SourceFile sourceFile, ModuleContainer module, ParserSession session, Report report, bool returnAtSignInVerbatimIdentifiers, int lineModifier = 0, int colModifier = 0) { var file = new CompilationSourceFile(module, sourceFile); module.AddTypeContainer(file); CSharpParser parser = new CSharpParser(reader, file, report, session, returnAtSignInVerbatimIdentifiers); parser.Lexer.Line += lineModifier; parser.Lexer.Column += colModifier; parser.Lexer.sbag = new SpecialsBag(); parser.parse(); return(parser); }