void SymbolTableUpdateEventHandler(Compilation updatedSymbolTable, UpdateSpecification updateSpecification, MemberList changedMembers){ lock(this){ Thread savedCurrentThread = this.currentThread; if (Thread.CurrentThread == this.currentThread) Console.WriteLine("Update event called on same thread as the one causing the update"); if (!Thread.CurrentThread.IsThreadPoolThread) Console.WriteLine("Updated event called from a non thread pool thread"); if (!Thread.CurrentThread.IsBackground) Console.WriteLine("Updated event called from a non background thread"); this.currentThread = Thread.CurrentThread; if (updatedSymbolTable == null){Console.WriteLine("SymbolTable update with null value for updatedSymbolTable"); return;} if (updatedSymbolTable.TargetModule == null){Console.WriteLine("SymbolTable update with null value for updatedSymbolTable.TargetModule"); return;} Console.WriteLine("Received update event on symbol table: {0}", ((Compilation)updateSpecification.Original).TargetModule.Name); for (int i = 0, n = changedMembers == null ? 0 : changedMembers.Count; i < n; i++){ Member mem = changedMembers[i]; if (mem == null) Console.WriteLine("changedMembers[{0}] == null", i); else Console.WriteLine("changedMembers[{0}].FullName == {1}", i, mem.FullName); } for (int i = 0, n = this.compilations.Count; i < n; i++){ Compilation compilation = this.compilations[i]; if (compilation == null || compilation == updateSpecification.Original) continue; for (int j = 0, m = compilation.ReferencedCompilations == null ? 0 : compilation.ReferencedCompilations.Count; j < m; j++){ Compilation rComp = compilation.ReferencedCompilations[j]; if (rComp != updateSpecification.Original) continue; Compilation upd = this.compiler.UpdateSymbolTable(compilation, (Compilation)updateSpecification.Original, updatedSymbolTable, changedMembers, this.errors); if (upd == null){ Console.WriteLine("Referenced compilation {0} was not updated", j); }else this.CheckUpdatedCompilation(compilation, upd); } } this.currentThread = savedCurrentThread; } }
public Analyzer(TypeSystem t, Compilation c) : base(t, c) { if (c != null) { SpecSharpCompilerOptions ssco = c.CompilerParameters as SpecSharpCompilerOptions; if (ssco != null) { if (ssco.Compatibility) this.NonNullChecking = false; // i.e., turn it off if we need to be compatible this.WeakPurityAnalysis = ssco.CheckPurity; // Diego said it is important that the same instance of the purity analysis is used across all // methods in the compilation unit. So create it here and just call it for each method in // the override for language specific analysis. // PointsToAnalysis.verbose = true; if (this.WeakPurityAnalysis) { // InterProcedural bottom up traversal with fixpoint //this.WeakPurityAnalyzer = new WeakPurityAndWriteEffectsAnalysis(this,typeSystem, c,true,true); // Only Intraprocedural (in this mode doesnot support delegates...) //this.WeakPurityAnalyzer = new WeakPurityAndWriteEffectsAnalysis(this, typeSystem, c, false); // Interprocedural top-down inlining simulation (with max-depth) this.WeakPurityAnalyzer = new WeakPurityAndWriteEffectsAnalysis(this, typeSystem, c, true,false,2); this.WeakPurityAnalyzer.StandAloneApp = false; this.WeakPurityAnalyzer.BoogieMode = true; } /// Reentrancy ANALYSIS this.ObjectExposureAnalysis = false; ObjectConsistencyAnalysis.verbose = false; if (ObjectExposureAnalysis) { this.ObjectExposureAnalyzer = new ObjectExposureAnalysis(this, typeSystem, c, true, false, 4); } this.ReentrancyAnalysis = false; if (ReentrancyAnalysis) { this.ReentrancyAnalyzer = new ReentrancyAnalysis(this, typeSystem, c, true, false, 4); } } } }
public static void Write(Compilation compilation, Module module, CompilerParameters options) { XmlTextWriter writer = new XmlTextWriter(module.Name + ".source.xml", Encoding.Default); SourceContextWriter scw = new SourceContextWriter(writer); writer.WriteStartDocument(); writer.WriteStartElement("Module"); writer.WriteAttributeString("name", module.Name); scw.VisitCompilation(compilation); writer.WriteEndElement(); // Module writer.WriteEndDocument(); writer.Flush(); writer.Close(); }
public void AddProgramVerifierPlugin(TypeSystem typeSystem, Compilation compilation){ #if Exp string boogieDir = System.Environment.GetEnvironmentVariable("BOOGIE"); if (boogieDir == null) boogieDir = "C:\\boogie"; string boogiePlugin = boogieDir + "\\Binaries\\BoogiePlugin.dll"; string errorInfo = boogiePlugin + " (Set BOOGIE environment variable)"; #else string codebase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; codebase = codebase.Replace("#", "%23"); Uri codebaseUri = new Uri(codebase); Uri uri = new Uri(codebaseUri, "BoogiePlugin.dll"); string boogiePlugin = uri.LocalPath; string errorInfo = boogiePlugin; #endif this.AddPlugin(boogiePlugin, "Microsoft.Boogie.BoogiePlugin", "Microsoft.Boogie.BoogiePlugin from assembly " + errorInfo, typeSystem, compilation); }
public override Compilation GetDummyCompilationFor(string fileName){ if (this.dummyCompilationFor == null) this.dummyCompilationFor = new Hashtable(); WeakReference wref = (WeakReference)this.dummyCompilationFor[fileName]; if (wref != null && wref.IsAlive) return (Compilation)wref.Target; string fContents = null; if (File.Exists(fileName)){ StreamReader sr = new StreamReader(fileName); fContents = sr.ReadToEnd(); sr.Close(); } Compilation compilation = new Compilation(); compilation.CompilerParameters = this.GetDummyCompilerParameters(); compilation.TargetModule = new Module(); DocumentText docText = new DocumentText(new StringSourceText(fContents, true)); SourceContext sctx = new SourceContext(Compiler.CreateSpecSharpDocument(fileName, 0, docText)); compilation.CompilationUnits = new CompilationUnitList(new CompilationUnitSnippet(new Identifier(fileName), new ParserFactory(), sctx)); compilation.CompilationUnits[0].Compilation = compilation; this.dummyCompilationFor[fileName] = new WeakReference(compilation); return compilation; }
protected override void SaveCompilation(Compilation compilation, Module module, CompilerParameters options, CompilerResults results){ CompilerOptions ccioptions = options as CompilerOptions; if (ccioptions != null && ccioptions.EmitSourceContextsOnly) { SourceContextWriter.Write(compilation, module, options); if (ccioptions.XMLDocFileName != null && ccioptions.XMLDocFileName.Length > 0) module.WriteDocumentation(new StreamWriter(ccioptions.XMLDocFileName)); } else{ base.SaveCompilation(compilation, module, options, results); } }
public virtual void ResolveSymbolTable(Compilation/*!*/ parsedCompilation, ErrorNodeList/*!*/ errors, out TrivialHashtable scopeFor){ scopeFor = new TrivialHashtable(); if (parsedCompilation == null) { Debug.Assert(false); return; } if (errors == null){Debug.Assert(false); return;} Scoper scoper = new Scoper(scopeFor); scoper.currentModule = parsedCompilation.TargetModule; scoper.VisitCompilation(parsedCompilation); ErrorHandler errorHandler = new ErrorHandler(errors); TrivialHashtable ambiguousTypes = new TrivialHashtable(); TrivialHashtable referencedLabels = new TrivialHashtable(); Looker looker = new Looker(null, errorHandler, scopeFor, ambiguousTypes, referencedLabels); // begin change by drunje SpecSharpCompilerOptions options = parsedCompilation.CompilerParameters as SpecSharpCompilerOptions; if (options != null) looker.AllowPointersToManagedStructures = options.AllowPointersToManagedStructures; // end change by drunje looker.currentAssembly = (looker.currentModule = parsedCompilation.TargetModule) as AssemblyNode; looker.VisitCompilation(parsedCompilation); }
/// <summary> /// Resolves all type expressions in the given (already parsed) compilation. /// The base types, interfaces and member signatures will all be on an equal footing with signatures from imported, /// already compiled modules and assemblies. /// </summary> public override void ResolveSymbolTable(Compilation/*!*/ parsedCompilation, ErrorNodeList/*!*/ errors){ TrivialHashtable scopeFor; this.ResolveSymbolTable(parsedCompilation, errors, out scopeFor); }
public virtual void ConstructSymbolTable(Compilation compilation, ErrorNodeList errors, TrivialHashtable scopeFor){ if (compilation == null || scopeFor == null){Debug.Assert(false); return;} this.CurrentCompilation = compilation; Module symbolTable = compilation.TargetModule = this.CreateModule(compilation.CompilerParameters, errors, compilation); Scoper scoper = new Scoper(scopeFor); scoper.currentModule = symbolTable; ErrorHandler errorHandler = new ErrorHandler(errors); Looker looker = new Looker(this.GetGlobalScope(symbolTable), errorHandler, scopeFor); // begin change by drunje SpecSharpCompilerOptions options = compilation.CompilerParameters as SpecSharpCompilerOptions; if (options != null) looker.AllowPointersToManagedStructures = options.AllowPointersToManagedStructures; // end change by drunje looker.currentAssembly = (looker.currentModule = symbolTable) as AssemblyNode; looker.ignoreMethodBodies = true; Scope globalScope = compilation.GlobalScope = this.GetGlobalScope(symbolTable); CompilationUnitList sources = compilation.CompilationUnits; if (sources == null) return; int n = sources.Count; for (int i = 0; i < n; i++){ CompilationUnitSnippet compilationUnitSnippet = sources[i] as CompilationUnitSnippet; if (compilationUnitSnippet == null){Debug.Assert(false); continue;} compilationUnitSnippet.ChangedMethod = null; Document doc = compilationUnitSnippet.SourceContext.Document; if (doc == null || doc.Text == null){Debug.Assert(false); continue;} IParserFactory factory = compilationUnitSnippet.ParserFactory; if (factory == null){Debug.Assert(false); return;} IParser p = factory.CreateParser(doc.Name, doc.LineNumber, doc.Text, symbolTable, errors, compilation.CompilerParameters); if (p is ResgenCompilerStub) continue; if (p == null){Debug.Assert(false); continue;} Parser specSharpParser = p as Parser; if (specSharpParser == null) p.ParseCompilationUnit(compilationUnitSnippet); else specSharpParser.ParseCompilationUnit(compilationUnitSnippet, true, false); //TODO: this following is a good idea only if the files will not be frequently reparsed from source //StringSourceText stringSourceText = doc.Text.TextProvider as StringSourceText; //if (stringSourceText != null && stringSourceText.IsSameAsFileContents) // doc.Text.TextProvider = new CollectibleSourceText(doc.Name, doc.Text.Length); //else if (doc.Text.TextProvider != null) // doc.Text.TextProvider.MakeCollectible(); } CompilationUnitList compilationUnits = new CompilationUnitList(); for (int i = 0; i < n; i++){ CompilationUnit cUnit = sources[i]; compilationUnits.Add(scoper.VisitCompilationUnit(cUnit)); } for (int i = 0; i < n; i++){ CompilationUnit cUnit = compilationUnits[i]; if (cUnit == null) continue; looker.VisitCompilationUnit(cUnit); } //Run resolver over symbol table so that custom attributes on member signatures are known and can be used //to error check the the given file. TypeSystem typeSystem = new TypeSystem(errorHandler); Resolver resolver = new Resolver(errorHandler, typeSystem); resolver.currentAssembly = (resolver.currentModule = symbolTable) as AssemblyNode; for (int i = 0; i < n; i++) { CompilationUnit cUnit = compilationUnits[i]; if (cUnit == null) continue; resolver.VisitCompilationUnit(cUnit); } this.CurrentCompilation = null; }
public override CompilerResults CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames, ErrorNodeList errorNodes, bool canUseMemoryMap) { if (options == null) { Debug.Assert(false); return null; } int n = fileNames.Length; if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) { for (int i = 0; i < n; i++) { if (fileNames[i] == null) continue; this.SetOutputFileName(options, fileNames[i]); break; } } CompilerResults results = new CompilerResults(options.TempFiles); AssemblyNode assem = this.CreateAssembly(options, errorNodes); Compilation compilation = new Compilation(assem, new CompilationUnitList(n), options, this.GetGlobalScope(assem)); SnippetParser sp = new SnippetParser(this, assem, errorNodes, options); for (int i = 0; i < n; i++) { string fileName = fileNames[i]; if (fileName == null) continue; DocumentText text = this.CreateDocumentText(fileName, results, options, errorNodes, canUseMemoryMap); CompilationUnitSnippet cu = this.CreateCompilationUnitSnippet(fileName, 1, text, compilation); sp.Visit(cu); compilation.CompilationUnits.Add(cu); cu.Compilation = compilation; } this.CompileParseTree(compilation, errorNodes); this.ProcessErrors(options, results, errorNodes); if (results.NativeCompilerReturnValue == 0) this.SetEntryPoint(compilation, results); // The following line is different from the base class method... this.SaveOrLoadAssembly(this.targetModule as AssemblyNode, options, results, errorNodes); return results; }
public override void CompileParseTree(Compilation compilation, ErrorNodeList errorNodes) { TrivialHashtable ambiguousTypes = new TrivialHashtable(); TrivialHashtable scopeFor = new TrivialHashtable(); TrivialHashtable referencedLabels = new TrivialHashtable(); Hashtable exceptionNames = new Hashtable(); ErrorHandler errorHandler = new ErrorHandler(errorNodes); string target = ""; ZingCompilerOptions zoptions = compilation.CompilerParameters as ZingCompilerOptions; if (zoptions != null && zoptions.DumpSource) { target = compilation.CompilerParameters.OutputAssembly; if (string.IsNullOrEmpty(target)) { target = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar; } string output = Path.GetDirectoryName(target); if (string.IsNullOrEmpty(output)) output = Directory.GetCurrentDirectory(); target = Path.GetFileNameWithoutExtension(target); } if (this.Options == null) this.Options = compilation.CompilerParameters; //Attach scopes to namespaces and types so that forward references to base types can be looked up in the appropriate namespace scope Scoper scoper = new Scoper(scopeFor); scoper.VisitCompilation(compilation); //Walk IR looking up names TypeSystem typeSystem = new TypeSystem(errorHandler); Looker looker = new Looker(compilation.GlobalScope, errorHandler, scopeFor, typeSystem, // LJW: added typeSystem ambiguousTypes, referencedLabels, exceptionNames); looker.VisitCompilation(compilation); //Walk IR inferring types and resolving overloads Resolver resolver = new Resolver(errorHandler, typeSystem); resolver.VisitCompilation(compilation); Checker checker = new Checker(errorHandler, typeSystem, scopeFor, ambiguousTypes, referencedLabels); // LJW: added scopeFor checker.VisitCompilation(compilation); // Walk the Zing IR splicing it into our code-gen templates Splicer splicer = new Splicer(this.Options, referencedLabels, exceptionNames); CompilationUnit cuMerged = splicer.CodeGen(compilation); // // If the 'dumpSource' option is given, then we decompile the IR to C# and write this // to a file. // if (zoptions != null && zoptions.DumpSource) { // Once the codegen is done and we have the IR for the generated code, we use the // decompiler to get C# back out, and hand this to the standard compiler. Later, // we'll replace this with the X# normalizer and avoid going in and out of source // code (except for compiler debugging). string tempSrc; string tempName = compilation.CompilerParameters.OutputAssembly + ".cs"; Decompiler decompiler = new Decompiler(); tempSrc = decompiler.Decompile(cuMerged); StreamWriter sw = File.CreateText(tempName); sw.Write(tempSrc); sw.Close(); } if (zoptions != null && zoptions.DumpLabels) { string tempName = compilation.CompilerParameters.OutputAssembly + ".labels"; StreamWriter sw = File.CreateText(tempName); sw.Write(splicer.LabelString); sw.Close(); } for (int i = 0; i < RequiredTypes.Length; i++) { R.Assembly asm = R.Assembly.GetAssembly(RequiredTypes[i]); if (!compilation.CompilerParameters.ReferencedAssemblies.Contains(asm.Location)) compilation.CompilerParameters.ReferencedAssemblies.Add(asm.Location); } // The if-statement added by Jiri Adamek // It loads a native ZOM assembly if used if (zoptions != null && zoptions.ZomAssemblyName != null) { compilation.CompilerParameters.ReferencedAssemblies.Add(zoptions.ZomAssemblyName); } CS.Compiler csCompiler = new CS.Compiler(); // We have to create a new module to pull in references from the // assemblies we just added above. compilation.TargetModule = this.targetModule = csCompiler.CreateModule(compilation.CompilerParameters, errorNodes); // Our one top-level type must be added to the module's type list compilation.TargetModule.Types.Add(((Namespace)cuMerged.Nodes[0]).NestedNamespaces[0].Types[0]); // The restorer patches the DeclaringModule field of our types Restorer restorer = new Restorer(compilation.TargetModule); restorer.VisitCompilationUnit(cuMerged); // Replace the Zing compilation unit with our generated code before invoking // the Spec# back end. compilation.CompilationUnits = new CompilationUnitList(cuMerged); foreach (CompilationUnit cunit in compilation.CompilationUnits) cunit.Compilation = compilation; // For retail builds, disable the time-consuming definite-assignment checks // in the Spec# compiler. if (!this.Options.IncludeDebugInformation) compilation.CompilationUnits[0].PreprocessorDefinedSymbols["NODEFASSIGN"] = "true"; // Let the Spec# back end process the IR from here csCompiler.CompileParseTree(compilation, errorNodes); }
public override CompilerResults CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] compilationUnits, ErrorNodeList errorNodes) { if (options == null) { Debug.Assert(false); return null; } this.Options = options; int n = compilationUnits == null ? 0 : compilationUnits.Length; if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) { for (int i = 0; i < n; i++) { CodeSnippetCompileUnit csu = compilationUnits[i] as CodeSnippetCompileUnit; if (csu == null || csu.LinePragma == null || csu.LinePragma.FileName == null) continue; this.SetOutputFileName(options, csu.LinePragma.FileName); break; } } CompilerResults results = new CompilerResults(options.TempFiles); AssemblyNode assem = this.CreateAssembly(options, errorNodes); Compilation compilation = new Compilation(assem, new CompilationUnitList(n), options, this.GetGlobalScope(assem)); CodeDomTranslator cdt = new CodeDomTranslator(); SnippetParser sp = new SnippetParser(this, assem, errorNodes, options); for (int i = 0; i < n; i++) { CompilationUnit cu = cdt.Translate(this, compilationUnits[i], assem, errorNodes); sp.Visit(cu); compilation.CompilationUnits.Add(cu); cu.Compilation = compilation; } this.CompileParseTree(compilation, errorNodes); this.ProcessErrors(options, results, errorNodes); if (results.NativeCompilerReturnValue == 0) this.SetEntryPoint(compilation, results); // The following line is different from the base class method... this.SaveOrLoadAssembly(this.targetModule as AssemblyNode, options, results, errorNodes); return results; }
void PerformIncrementalUpdate(){ SourceChangeList changes = this.ConstructSourceChangeList(); string expectedOutput = this.GetExpectedOutput(); //perform update Document originalDocument = this.compilationUnit.SourceContext.Document; Document changedDocument = this.currentDocument = this.GetChangedDocument(this.currentDocument, changes); lock(this){ //prevent asynchronous symbol table update event handler from producing output until after CheckUpdatedCompilation has run Compilation updatedCompilation = this.compiler.UpdateSymbolTable(this.compilation, originalDocument, changedDocument, changes, this.errors); this.CheckUpdatedCompilation(this.compilation, updatedCompilation); this.compilation = updatedCompilation; } //Give asynchronous symbol table update events time to complete Thread.Sleep(20); //Get actual output and compare with expected output string actualOutput = this.output.ToString(); if (expectedOutput != actualOutput){ Console.SetOut(this.savedConsoleOut); Console.WriteLine("Test {0} line {1} failed", this.testName, this.lineCounter-1); Console.WriteLine("Actual output:"); Console.Write(actualOutput); Console.WriteLine("Expected output:"); Console.Write(expectedOutput); this.failures++; } Console.SetOut(new StringWriter(this.output = new StringBuilder())); System.Diagnostics.Debug.Listeners.Remove(this.traceListener); this.traceListener = new System.Diagnostics.TextWriterTraceListener(System.Console.Out); System.Diagnostics.Debug.Listeners.Add(this.traceListener); }
void ConstructCompilations(){ this.compilation = null; this.compilations = new CompilationList(); while (this.inputLine != null && this.inputLine.StartsWith("compilation ")){ this.ConstructCompilation(); } if (this.compilation == null) throw new MalformedSuiteException("Line "+this.lineCounter+": Expected a line of the form 'compilation name'"); Compilation previous = null; for (int i = this.compilations.Count-1; i >= 0; i--){ Compilation comp = this.compilations[i]; if (previous != null){ comp.ReferencedCompilations = new CompilationList(previous); comp.CompilerParameters.ReferencedAssemblies.Add(previous.CompilerParameters.OutputAssembly+".dll"); } this.compiler.ConstructSymbolTable(comp, this.errors); previous = comp; } }
public override Compilation VisitCompilation(Compilation compilation) { if (compilation == null) return null; SpecSharpCompilerOptions ssco = compilation.CompilerParameters as SpecSharpCompilerOptions; this.AllowPropertiesIndexersAsRef = (ssco == null || !ssco.Compatibility); return base.VisitCompilation(compilation); }
public override Cci.AuthoringScope GetAuthoringScopeForMethodBody(string text, Compilation/*!*/ compilation, Method/*!*/ method, AuthoringSink asink) { this.parsingStatement = true; if (text == null || compilation == null || method == null || method.Body == null || method.Body.SourceContext.Document == null) throw new ArgumentNullException(); if (compilation != null && compilation.CompilerParameters is SpecSharpCompilerOptions) this.allowSpecSharpExtensions = !((SpecSharpCompilerOptions)compilation.CompilerParameters).Compatibility; this.currentSymbolTable = compilation.TargetModule; SourceContext sctx = method.Body.SourceContext; DocumentText docText = new DocumentText(text); Document doc = Compiler.CreateSpecSharpDocument(sctx.Document.Name, 1, docText); ErrorNodeList errors = new ErrorNodeList(0); Parser p = new Parser(doc, errors, compilation.TargetModule, compilation.CompilerParameters as SpecSharpCompilerOptions); p.ParseMethodBody(method, sctx.StartPos, asink); ErrorHandler errorHandler = new ErrorHandler(errors); TrivialHashtable ambiguousTypes = new TrivialHashtable(); TrivialHashtable referencedLabels = new TrivialHashtable(); Looker looker = new Looker(null, errorHandler, this.scopeFor, ambiguousTypes, referencedLabels); looker.currentAssembly = (looker.currentModule = compilation.TargetModule) as AssemblyNode; TypeNode currentType = method.DeclaringType; looker.currentType = currentType; looker.scope = method.Scope; if (looker.scope != null) looker.scope = looker.scope.OuterScope; looker.identifierInfos = this.identifierInfos = new NodeList(); looker.identifierPositions = this.identifierPositions = new Int32List(); looker.identifierLengths = this.identifierLengths = new Int32List(); looker.identifierContexts = this.identifierContexts = new Int32List(); looker.identifierScopes = this.identifierScopes = new ScopeList(); looker.allScopes = this.allScopes = new ScopeList(); looker.Visit(method); Resolver resolver = new Resolver(errorHandler, new TypeSystem(errorHandler)); resolver.currentAssembly = (resolver.currentModule = this.currentSymbolTable) as AssemblyNode; resolver.currentType = currentType; if (currentType != null) { if (resolver.currentType.Template == null && resolver.currentType.ConsolidatedTemplateParameters != null && resolver.currentType.ConsolidatedTemplateParameters.Count > 0) resolver.currentTypeInstance = resolver.GetDummyInstance(resolver.currentType); else resolver.currentTypeInstance = resolver.currentType; } resolver.Visit(method); method.Body.Statements = null; return this.GetAuthoringScope(); }
public override CompilationUnit ParseCompilationUnit(string fname, string source, ErrorNodeList errors, Compilation compilation, AuthoringSink sink){ this.parsingStatement = false; if (fname == null || source == null || errors == null || compilation == null){Debug.Assert(false); return null;} if (compilation != null && compilation.CompilerParameters is SpecSharpCompilerOptions) this.allowSpecSharpExtensions = !((SpecSharpCompilerOptions)compilation.CompilerParameters).Compatibility; CompilationUnit cu; #if Xaml if (fname.Length > 5 && string.Compare(fname, fname.Length-5, ".xaml", 0, 5, true, CultureInfo.InvariantCulture) == 0){ Document xamlDocument = Microsoft.XamlCompiler.Compiler.CreateXamlDocument(fname, 1, new DocumentText(source)); Microsoft.XamlCompiler.ErrorHandler xamlErrorHandler = new Microsoft.XamlCompiler.ErrorHandler(errors); Microsoft.XamlCompiler.Compiler xamlCompiler = new Microsoft.XamlCompiler.Compiler(xamlDocument, compilation.TargetModule, xamlErrorHandler, new ParserFactory(), compilation.CompilerParameters as CompilerOptions); cu = xamlCompiler.GetCompilationUnit(); }else{ #endif Parser p = new Parser(compilation.TargetModule); cu = p.ParseCompilationUnit(source, fname, compilation.CompilerParameters, errors, sink); if (cu != null) cu.Compilation = compilation; this.parsingStatement = p.parsingStatement; #if Xaml } #endif this.partialCompilationUnit = cu; return cu; }
public override void ParseAndAnalyzeCompilationUnit(string fname, string text, int line, int col, ErrorNodeList errors, Compilation compilation, AuthoringSink sink) { if (fname == null || text == null || errors == null || compilation == null){Debug.Assert(false); return;} if (compilation != null && compilation.CompilerParameters is SpecSharpCompilerOptions) this.allowSpecSharpExtensions = !((SpecSharpCompilerOptions)compilation.CompilerParameters).Compatibility; CompilationUnitList compilationUnitSnippets = compilation.CompilationUnits; if (compilationUnitSnippets == null){Debug.Assert(false); return;} //Fix up the CompilationUnitSnippet corresponding to fname with the new source text CompilationUnitSnippet cuSnippet = this.GetCompilationUnitSnippet(compilation, fname); if (cuSnippet == null) return; Compiler compiler = new Compiler(); compiler.CurrentCompilation = compilation; cuSnippet.SourceContext.Document = compiler.CreateDocument(fname, 1, new DocumentText(text)); cuSnippet.SourceContext.EndPos = text.Length; //Parse all of the compilation unit snippets Module symbolTable = compilation.TargetModule = compiler.CreateModule(compilation.CompilerParameters, errors); AttributeList assemblyAttributes = symbolTable is AssemblyNode ? symbolTable.Attributes : null; AttributeList moduleAttributes = symbolTable is AssemblyNode ? ((AssemblyNode)symbolTable).ModuleAttributes : symbolTable.Attributes; int n = compilationUnitSnippets.Count; for (int i = 0; i < n; i++){ CompilationUnitSnippet compilationUnitSnippet = compilationUnitSnippets[i] as CompilationUnitSnippet; if (compilationUnitSnippet == null){Debug.Assert(false); continue;} Document doc = compilationUnitSnippet.SourceContext.Document; doc = compilationUnitSnippet.SourceContext.Document; if (doc == null || doc.Text == null){Debug.Assert(false); continue;} IParserFactory factory = compilationUnitSnippet.ParserFactory; if (factory == null) continue; compilationUnitSnippet.Nodes = null; compilationUnitSnippet.PreprocessorDefinedSymbols = null; IParser p = factory.CreateParser(doc.Name, doc.LineNumber, doc.Text, symbolTable, compilationUnitSnippet == cuSnippet ? errors : new ErrorNodeList(), compilation.CompilerParameters); if (p == null){Debug.Assert(false); continue;} if (p is ResgenCompilerStub) continue; Parser specSharpParser = p as Parser; if (specSharpParser == null) p.ParseCompilationUnit(compilationUnitSnippet); else specSharpParser.ParseCompilationUnit(compilationUnitSnippet, compilationUnitSnippet != cuSnippet, false); //TODO: this following is a good idea only if the files will not be frequently reparsed from source //StringSourceText stringSourceText = doc.Text.TextProvider as StringSourceText; //if (stringSourceText != null && stringSourceText.IsSameAsFileContents) // doc.Text.TextProvider = new CollectibleSourceText(doc.Name, doc.Text.Length); } //Construct symbol table for entire project ErrorHandler errorHandler = new ErrorHandler(errors); SpecSharpCompilation ssCompilation = new SpecSharpCompilation(); TrivialHashtable ambiguousTypes = new TrivialHashtable(); TrivialHashtable referencedLabels = new TrivialHashtable(); TrivialHashtable scopeFor = this.scopeFor = new TrivialHashtable(); Scoper scoper = new Scoper(scopeFor); scoper.currentModule = symbolTable; Looker symLooker = new Looker(null, new ErrorHandler(new ErrorNodeList(0)), scopeFor, ambiguousTypes, referencedLabels); symLooker.currentAssembly = (symLooker.currentModule = symbolTable) as AssemblyNode; Looker looker = new Looker(null, errorHandler, scopeFor, ambiguousTypes, referencedLabels); looker.currentAssembly = (looker.currentModule = symbolTable) as AssemblyNode; looker.VisitAttributeList(assemblyAttributes); bool dummyCompilation = compilation.CompilerParameters is SpecSharpCompilerOptions && ((SpecSharpCompilerOptions)compilation.CompilerParameters).DummyCompilation; if (dummyCompilation){ //This happens when there is no project. In this case, semantic errors should be ignored since the references and options are unknown. //But proceed with the full analysis anyway so that some measure of Intellisense can still be provided. errorHandler.Errors = new ErrorNodeList(0); } for (int i = 0; i < n; i++){ CompilationUnit cUnit = compilationUnitSnippets[i]; scoper.VisitCompilationUnit(cUnit); } for (int i = 0; i < n; i++){ CompilationUnit cUnit = compilationUnitSnippets[i]; if (cUnit == cuSnippet) looker.VisitCompilationUnit(cUnit); //Uses real error message list and populate the identifier info lists else symLooker.VisitCompilationUnit(cUnit); //Errors are discarded } //Run resolver over symbol table so that custom attributes on member signatures are known and can be used //to error check the the given file. TypeSystem typeSystem = new TypeSystem(errorHandler); Resolver resolver = new Resolver(errorHandler, typeSystem); resolver.currentAssembly = (resolver.currentModule = symbolTable) as AssemblyNode; Resolver symResolver = new Resolver(new ErrorHandler(new ErrorNodeList(0)), typeSystem); symResolver.currentAssembly = resolver.currentAssembly; symResolver.VisitAttributeList(assemblyAttributes); for (int i = 0; i < n; i++) { CompilationUnit cUnit = compilationUnitSnippets[i]; if (cUnit == cuSnippet) resolver.VisitCompilationUnit(cUnit); //Uses real error message list and populate the identifier info lists else symResolver.VisitCompilationUnit(cUnit); //Errors are discarded } if (dummyCompilation) return; //Now analyze the given file for errors Checker checker = new Checker(ssCompilation, errorHandler, typeSystem, scopeFor, ambiguousTypes, referencedLabels); checker.currentAssembly = (checker.currentModule = symbolTable) as AssemblyNode; checker.VisitAttributeList(assemblyAttributes, checker.currentAssembly); checker.VisitModuleAttributes(moduleAttributes); checker.VisitCompilationUnit(cuSnippet); MemberFinder finder = new MemberFinder(line, col); finder.VisitCompilationUnit(cuSnippet); Node node = finder.Member; if (node == null){ if (line == 0 && col == 0) node = cuSnippet; else return; } SpecSharpCompilerOptions options = (SpecSharpCompilerOptions) compilation.CompilerParameters; if (options.IsContractAssembly) return; ssCompilation.RunPlugins(node, errorHandler); Normalizer normalizer = new Normalizer(typeSystem); normalizer.Visit(node); Analyzer analyzer = new Analyzer(typeSystem, compilation); analyzer.Visit(node); if (options.RunProgramVerifierWhileEditing) ssCompilation.AddProgramVerifierPlugin(typeSystem, compilation); ssCompilation.analyzer = analyzer; // make the analyzer available to plugins for access to method CFGs ssCompilation.RunPlugins(node, errorHandler); ssCompilation.analyzer = null; analyzer = null; }
protected override void SaveCompilation(Compilation compilation, AssemblyNode assem, CompilerParameters options, CompilerResults results, ErrorNodeList errorNodes) { CompilerOptions ccioptions = options as CompilerOptions; if (ccioptions != null && ccioptions.EmitSourceContextsOnly) { SourceContextWriter.Write(compilation, assem, options); if (ccioptions.XMLDocFileName != null && ccioptions.XMLDocFileName.Length > 0) assem.WriteDocumentation(new StreamWriter(ccioptions.XMLDocFileName)); } else{ base.SaveCompilation (compilation, assem, options, results, errorNodes); } }
/// <summary> /// Parses all of the CompilationUnitSnippets in the given compilation, ignoring method bodies. Then resolves all type expressions. /// The resulting types can be retrieved from the module in compilation.TargetModule. The base types, interfaces and /// member signatures will all be resolved and on an equal footing with imported, already compiled modules and assemblies. /// </summary> public override void ConstructSymbolTable(Compilation compilation, ErrorNodeList errors) { if (compilation == null) { Debug.Assert(false); return; } Module symbolTable = compilation.TargetModule = this.CreateModule(compilation.CompilerParameters, errors, compilation); TrivialHashtable scopeFor = new TrivialHashtable(); Scoper scoper = new Scoper(scopeFor); scoper.currentModule = symbolTable; ErrorHandler errorHandler = new ErrorHandler(errors); TypeSystem typeSystem = new TypeSystem(errorHandler); // LJW: added typeSystem Looker looker = new Looker(this.GetGlobalScope(symbolTable), errorHandler, scopeFor, typeSystem); looker.currentAssembly = (looker.currentModule = symbolTable) as AssemblyNode; looker.ignoreMethodBodies = true; compilation.GlobalScope = this.GetGlobalScope(symbolTable); CompilationUnitList sources = compilation.CompilationUnits; if (sources == null) { Debug.Assert(false); return; } int n = sources.Count; for (int i = 0; i < n; i++) { CompilationUnitSnippet compilationUnitSnippet = sources[i] as CompilationUnitSnippet; if (compilationUnitSnippet == null) { Debug.Assert(false); continue; } compilationUnitSnippet.ChangedMethod = null; Document doc = compilationUnitSnippet.SourceContext.Document; if (doc == null || doc.Text == null) { Debug.Assert(false); continue; } IParserFactory factory = compilationUnitSnippet.ParserFactory; if (factory == null) { Debug.Assert(false); return; } IParser p = factory.CreateParser(doc.Name, doc.LineNumber, doc.Text, symbolTable, errors, compilation.CompilerParameters); if (p is ResgenCompilerStub) continue; if (p == null) { Debug.Assert(false); continue; } Parser zingParser = p as Parser; if (zingParser == null) p.ParseCompilationUnit(compilationUnitSnippet); else zingParser.ParseCompilationUnit(compilationUnitSnippet, true, true, null); StringSourceText stringSourceText = doc.Text.TextProvider as StringSourceText; if (stringSourceText != null && stringSourceText.IsSameAsFileContents) doc.Text.TextProvider = new CollectibleSourceText(doc.Name, doc.Text.Length); else if (doc.Text.TextProvider != null) doc.Text.TextProvider.MakeCollectible(); } CompilationUnitList compilationUnits = new CompilationUnitList(); for (int i = 0; i < n; i++) { CompilationUnit cUnit = sources[i]; compilationUnits.Add(scoper.VisitCompilationUnit(cUnit)); } for (int i = 0; i < n; i++) { CompilationUnit cUnit = compilationUnits[i]; if (cUnit == null) continue; looker.VisitCompilationUnit(cUnit); } }
public void RunPlugins(Compilation compilation, ErrorHandler errorHandler){ if (this.plugins == null) return; foreach (Visitor pluginVisitor in this.plugins){ if (pluginVisitor == null){Debug.Assert(false); continue;} try { pluginVisitor.Visit(compilation); }catch(Exception e){ errorHandler.HandleError(compilation, Error.PluginCrash, pluginVisitor.GetType().ToString(), e.Message, e.StackTrace); } } }
public void ResolveIR(Compilation compilation, ErrorNodeList errorNodes) { TrivialHashtable ambiguousTypes = new TrivialHashtable(); TrivialHashtable scopeFor = new TrivialHashtable(); TrivialHashtable referencedLabels = new TrivialHashtable(); Hashtable exceptionNames = new Hashtable(); ErrorHandler errorHandler = new ErrorHandler(errorNodes); string target = ""; ZingCompilerOptions zoptions = compilation.CompilerParameters as ZingCompilerOptions; if (zoptions != null && zoptions.DumpSource) { target = compilation.CompilerParameters.OutputAssembly; if (string.IsNullOrEmpty(target)) { target = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar; } string output = Path.GetDirectoryName(target); if (string.IsNullOrEmpty(output)) output = Directory.GetCurrentDirectory(); target = Path.GetFileNameWithoutExtension(target); } if (this.Options == null) this.Options = compilation.CompilerParameters; //Attach scopes to namespaces and types so that forward references to base types can be looked up in the appropriate namespace scope Scoper scoper = new Scoper(scopeFor); scoper.VisitCompilation(compilation); //Walk IR looking up names TypeSystem typeSystem = new TypeSystem(errorHandler); Looker looker = new Looker(compilation.GlobalScope, errorHandler, scopeFor, typeSystem, // LJW: added typeSystem ambiguousTypes, referencedLabels, exceptionNames); looker.VisitCompilation(compilation); //Walk IR inferring types and resolving overloads Resolver resolver = new Resolver(errorHandler, typeSystem); resolver.VisitCompilation(compilation); Checker checker = new Checker(errorHandler, typeSystem, scopeFor, ambiguousTypes, referencedLabels); // LJW: added scopeFor checker.VisitCompilation(compilation); }
void ConstructCompilation(){ this.testName = this.inputLine.Substring(12); this.compilation = new Compilation(null, new CompilationUnitList(), new CompilerOptions(), null); this.compilation.CompilerParameters.OutputAssembly = this.testName; this.compilations.Add(this.compilation); this.ReadNextLine(); while (this.inputLine != null && this.inputLine.StartsWith("file ")) this.ConstructCompilationUnit(); }
public override void CompileParseTree(Compilation compilation, ErrorNodeList errorNodes){ if (compilation == null || compilation.CompilationUnits == null || compilation.TargetModule == null){Debug.Assert(false); return;} if (compilation.CompilationUnits.Count == 0) return; TrivialHashtable ambiguousTypes = new TrivialHashtable(); TrivialHashtable referencedLabels = new TrivialHashtable(); TrivialHashtable scopeFor = new TrivialHashtable(64); ErrorHandler errorHandler = new ErrorHandler(errorNodes); SpecSharpCompilation ssCompilation = new SpecSharpCompilation(); SpecSharpCompilerOptions options = (SpecSharpCompilerOptions)compilation.CompilerParameters; //Attach scopes to namespaces and types so that forward references to base types can be looked up in the appropriate namespace scope Scoper scoper = new Scoper(scopeFor); scoper.VisitCompilation(compilation); scoper = null; if (options.NoStandardLibrary && compilation.TargetModule is AssemblyNode) { if (compilation.TargetModule.IsValidTypeName(StandardIds.System, StandardIds.CapitalObject)) { SystemAssemblyLocation.ParsedAssembly = (AssemblyNode)compilation.TargetModule; SystemCompilerRuntimeAssemblyLocation.ParsedAssembly = (AssemblyNode)compilation.TargetModule; //So that mscorlib can have contracts but no reference to another assembly } else if (compilation.TargetModule.IsValidTypeName(Identifier.For("System.Compiler"), Identifier.For("ComposerAttribute"))) SystemCompilerRuntimeAssemblyLocation.ParsedAssembly = (AssemblyNode)compilation.TargetModule; else if (compilation.TargetModule.IsValidTypeName(Identifier.For("Microsoft.SpecSharp"), Identifier.For("dummy"))) RuntimeAssemblyLocation.ParsedAssembly = (AssemblyNode)compilation.TargetModule; } object ObjectType = SystemTypes.Object; if (ObjectType == null) return; //system types did not initialize //Walk IR looking up names Looker looker = new Looker(compilation.GlobalScope, errorHandler, scopeFor, ambiguousTypes, referencedLabels); if (options != null && options.EmitSourceContextsOnly) { looker.DontInjectDefaultConstructors = true; } // begin change by drunje looker.AllowPointersToManagedStructures = options.AllowPointersToManagedStructures; // end change by drunje looker.VisitCompilation(compilation); looker = null; if (options != null && options.EmitSourceContextsOnly) return; // stop after looker to have resolved types //Walk IR inferring types and resolving overloads TypeSystem typeSystem = new TypeSystem(errorHandler); Resolver resolver = new Resolver(errorHandler, typeSystem); resolver.VisitCompilation(compilation); resolver = null; //Walk IR checking for semantic errors and repairing it so that the next walk will work Checker checker = new Checker(ssCompilation, errorHandler, typeSystem, scopeFor, ambiguousTypes, referencedLabels); checker.VisitCompilation(compilation); checker = null; scopeFor = null; ambiguousTypes = null; referencedLabels = null; if (!options.IsContractAssembly) { if (options.RunProgramVerifier) ssCompilation.AddProgramVerifierPlugin(typeSystem, compilation); //Allow third party extensions to analyze AST IR for further errors ssCompilation.RunPlugins(compilation, errorHandler); } //Walk IR reducing it to nodes that have predefined mappings to MD+IL Normalizer normalizer = new Normalizer(typeSystem); normalizer.VisitCompilation(compilation); normalizer = null; if (options.IsContractAssembly) return; //Walk normalized IR instrumenting accesses of fields of guarded classes with checks CompilationUnit cu = compilation.CompilationUnits[0]; if (cu != null && cu.PreprocessorDefinedSymbols != null && cu.PreprocessorDefinedSymbols.ContainsKey("GuardedFieldAccessChecks")){ if (errorNodes.Count == 0){ GuardedFieldAccessInstrumenter instrumenter = new GuardedFieldAccessInstrumenter(); instrumenter.VisitCompilation(compilation); instrumenter = null; } } //Walk normalized IR doing code analysis Analyzer analyzer = new Analyzer(typeSystem, compilation); analyzer.Visit(compilation); //Allow third party extensions to analyze normalized IR for further errors ssCompilation.analyzer = analyzer; // make the analyzer available to plugins for access to method CFGs ssCompilation.RunPlugins(compilation, errorHandler); ssCompilation.analyzer = null; ssCompilation = null; analyzer = null; errorHandler = null; //Walk IR to optimize code further after analyses were performed, eg. to remove debug only code Optimizer optimizer = new Optimizer(); optimizer.Visit(compilation); optimizer = null; }
void CheckUpdatedCompilation(Compilation originalCompilation, Compilation updatedCompilation){ this.WriteOutAnyErrors(); if (originalCompilation != updatedCompilation){ Console.WriteLine("update of {0} resulted in a new compilation instance", originalCompilation.TargetModule.Name); return; } CompilationUnit updatedCompilationUnit = null; for (int i = 0, n = updatedCompilation.CompilationUnits == null ? 0 : updatedCompilation.CompilationUnits.Count; i < n; i++){ if (updatedCompilation.CompilationUnits[i] == null) Console.WriteLine("updated compilation unit {0} is null", i); else if (updatedCompilation.CompilationUnits[i].Name.UniqueIdKey == this.compilationUnit.Name.UniqueIdKey){ updatedCompilationUnit = updatedCompilation.CompilationUnits[i]; break; } } StatementVisitor statVis = new StatementVisitor(); statVis.Visit(updatedCompilationUnit); }
public override CompilationUnitSnippet CreateCompilationUnitSnippet(string fileName, int lineNumber, DocumentText text, Compilation compilation){ if (fileName == null) return null; SpecSharpCompilerOptions options = compilation == null ? null : (compilation.CompilerParameters as SpecSharpCompilerOptions); if (options != null && options.Compatibility) return base.CreateCompilationUnitSnippet(fileName, lineNumber, text, compilation); #if Xaml if (this.CompileAsXaml || string.Compare(Path.GetExtension(fileName), ".xaml", true, CultureInfo.InvariantCulture) == 0){ Document doc = Microsoft.XamlCompiler.Compiler.CreateXamlDocument(fileName, 1, text); CompilationUnitSnippet cu = new CompilationUnitSnippet(); cu.Name = Identifier.For(doc.Name); cu.SourceContext = new SourceContext(doc); cu.ParserFactory = new XamlParserFactory(); cu.Compilation = compilation; return cu; }else #endif return base.CreateCompilationUnitSnippet(fileName, lineNumber, text, compilation); }
public override Compilation VisitCompilation(Compilation compilation) { if (compilation == null || compilation.TargetModule == null) return null; this.FindTypesToBeDuplicated(compilation.TargetModule.Types); return base.VisitCompilation((Compilation)compilation.Clone()); }
public override CompilerResults CompileAssemblyFromSource(CompilerParameters options, string source, ErrorNodeList errorNodes){ if (!this.CompileAsXaml) return base.CompileAssemblyFromSource(options, source, errorNodes); AssemblyNode assem = this.CreateAssembly(options, errorNodes); Compilation compilation = new Compilation(); compilation.TargetModule = assem; compilation.CompilerParameters = options; compilation.CompilationUnits = new CompilationUnitList(this.CreateCompilationUnitSnippet("", 1, new DocumentText(source), compilation)); SnippetParser sp = this.CreateSnippetParser(assem, errorNodes, options); sp.Visit(compilation); this.CompileParseTree(compilation, errorNodes); CompilerResults results = new CompilerResults(options.TempFiles); this.ProcessErrors(options, results, errorNodes); SpecSharpCompilerOptions ssco = options as SpecSharpCompilerOptions; if (ssco == null || !ssco.OnlyTypeChecks) { if (results.NativeCompilerReturnValue == 0) this.SetEntryPoint(compilation, results); this.SaveCompilation(compilation, assem, options, results, errorNodes); } return results; }
public virtual Compilation VisitCompilation(Compilation compilation) { if (compilation == null) return null; Module module = compilation.TargetModule; if (module != null) module.Attributes = this.VisitAttributeList(module.Attributes); AssemblyNode assem = module as AssemblyNode; if (assem != null) assem.ModuleAttributes = this.VisitAttributeList(assem.ModuleAttributes); compilation.CompilationUnits = this.VisitCompilationUnitList(compilation.CompilationUnits); return compilation; }
/// <summary> /// Parses all of the CompilationUnitSnippets in the given compilation, ignoring method bodies. Then resolves all type expressions. /// The resulting types can be retrieved from the module in compilation.TargetModule. The base types, interfaces and /// member signatures will all be resolved and on an equal footing with imported, already compiled modules and assemblies. /// </summary> public override void ConstructSymbolTable(Compilation compilation, ErrorNodeList errors){ this.ConstructSymbolTable(compilation, errors, new TrivialHashtable()); }