示例#1
0
文件: CSharpTask.cs 项目: kzu/clide
		public override bool Execute()
		{
			if (Language != CSharp)
			{
				Log.LogError("Unsupported language {0}.", Language);
				return false;
			}

			Project = this.GetOrAddProject(ProjectFullPath);
			if (cancellation.IsCancellationRequested)
			{
				Log.LogWarning("Cancellation was requested. Aborting task.");
				return false;
			}

			Compilation = Project.GetCompilationAsync(cancellation.Token).Result;

			var logWarnings = false;
			if (!string.IsNullOrEmpty(LogWarnings) && bool.TryParse(LogWarnings, out logWarnings) && logWarnings)
			{
				var diagnostics = Compilation.GetDiagnostics(cancellation.Token);
				if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
					Log.LogWarning("Code generation may not be complete, since there are compilation errors: " +
						string.Join(Environment.NewLine, diagnostics.Select(d => d.GetMessage())));
			}

			return true;
		}
示例#2
0
        private List <INamedTypeSymbol> AnalyzeProject(Project project)
        {
            var compilation = project.GetCompilationAsync().Result;
            var allTypes    = compilation.GetSymbolsWithName(x => true, SymbolFilter.Type).OfType <ITypeSymbol>().Where(t => t is INamedTypeSymbol).OfType <INamedTypeSymbol>();

            return(allTypes.ToList(  ));
        }
		internal static async Task<ImmutableArray<Diagnostic>> GetDiagnostics (Project project, List<DiagnosticAnalyzer> providers, CancellationToken token)
		{
			var analyzers = ImmutableArray<DiagnosticAnalyzer>.Empty.AddRange (providers);
			try {
				var compilation = await project.GetCompilationAsync (token).ConfigureAwait (false);
				CompilationWithAnalyzers compilationWithAnalyzer;
				var options = new CompilationWithAnalyzersOptions (
					null,
					delegate (Exception exception, DiagnosticAnalyzer analyzer, Diagnostic diag) {
						LoggingService.LogError ("Exception in diagnostic analyzer " + diag.Id + ":" + diag.GetMessage (), exception);
					},
					true,
					false
				);

				compilationWithAnalyzer = compilation.WithAnalyzers (analyzers, options);
				if (token.IsCancellationRequested)
					return ImmutableArray<Diagnostic>.Empty;

				return await compilationWithAnalyzer.GetAnalyzerDiagnosticsAsync ().ConfigureAwait (false);
			} catch (Exception) {
				return ImmutableArray<Diagnostic>.Empty;
			} finally {
				CompilationWithAnalyzers.ClearAnalyzerState (analyzers);
			}
		}
示例#4
0
        public async Task Parse()
        {
            // gather references
            var references = new List <Project>();
            var sln        = roslynProject.Solution;

            foreach (var reference in roslynProject.AllProjectReferences)
            {
                var project = solution.projects.FirstOrDefault(x => x.roslynProject.Id == reference.ProjectId);
                if (project == null)
                {
                    throw new Exception("Project reference not found in solution: " + reference.ProjectId);
                }
                references.Add(project);
            }

            this.references = references;

            // init main objects
            enumObjects      = new List <INamedTypeSymbol>();
            classObjects     = new List <INamedTypeSymbol>();
            structObjects    = new List <INamedTypeSymbol>();
            interfaceObjects = new List <INamedTypeSymbol>();

            // parse lowered objects
            compilation = (CSharpCompilation)await roslynProject.GetCompilationAsync();

            ParseNamespace(compilation.Assembly.GlobalNamespace);
        }
示例#5
0
        private static async Task<IEnumerable<string>> GetThrownExceptionTypeNames(Project project)
        {
            var compilation = await project.GetCompilationAsync();

            return compilation.SyntaxTrees
                              .SelectMany(tree => GetThrownExceptionTypeNames(compilation, tree))
                              .Distinct();
        }
示例#6
0
        public void PinvokeMethodReferences_VB()
        {
            var tree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(
                @"
Module Module1
        Declare Function CreateDirectory Lib ""kernel32"" Alias ""CreateDirectoryA"" (ByVal lpPathName As String) As Integer
 
        Private prop As Integer
        Property Prop1 As Integer
            Get
                Return prop
            End Get
            Set(value As Integer)
                CreateDirectory(""T"")  ' Method Call 1
                prop = value
                prop = Nothing
            End Set
        End Property

        Sub Main()
          CreateDirectory(""T"") 'Method Call 2            
          NormalMethod() ' Method Call 1
          NormalMethod() ' Method Call 2
       End Sub

       Sub NormalMethod()
       End Sub
 End Module
            ");

            ProjectId  prj1Id = ProjectId.CreateNewId();
            DocumentId docId  = DocumentId.CreateNewId(prj1Id);

            Microsoft.CodeAnalysis.Solution sln = new CustomWorkspace().CurrentSolution
                                                  .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.VisualBasic)
                                                  .AddMetadataReference(prj1Id, MscorlibRef)
                                                  .AddDocument(docId, "testFile", tree.GetText());

            Microsoft.CodeAnalysis.Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication, embedVbCoreRuntime: true));
            tree = (SyntaxTree)prj.GetDocument(docId).GetSyntaxTreeAsync().Result;
            Compilation comp = prj.GetCompilationAsync().Result;

            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            SyntaxNode declareMethod = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.VisualBasic.Syntax.DeclareStatementSyntax>().FirstOrDefault();
            SyntaxNode normalMethod  = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.VisualBasic.Syntax.MethodStatementSyntax>().ToList()[1];

            // declared method calls
            var symbol     = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;

            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());
        }
		public async Task<IProjectMetric> Calculate(Project project, Solution solution)
		{
			if (project == null)
			{
				return null;
			}

			var compilation = project.GetCompilationAsync();
			return await InnerCalculate(project, compilation, solution).ConfigureAwait(false);
		}
示例#8
0
        static async Task <LookupResult> TryLookupSymbolInProject(Microsoft.CodeAnalysis.Project prj, string documentationCommentId, CancellationToken token)
        {
            if (string.IsNullOrEmpty(documentationCommentId))
            {
                return(LookupResult.Failure);
            }
            bool searchNs      = documentationCommentId[0] == 'N';
            bool searchType    = documentationCommentId[0] == 'T';
            int  reminderIndex = 2;
            var  comp          = await prj.GetCompilationAsync(token).ConfigureAwait(false);

            var current = LookupNamespace(documentationCommentId, ref reminderIndex, comp.GlobalNamespace);

            if (current == null)
            {
                return(LookupResult.Failure);
            }
            if (searchNs)
            {
                if (current.GetDocumentationCommentId() == documentationCommentId)
                {
                    return(new LookupResult(current, prj.Solution, comp));
                }
                return(LookupResult.Failure);
            }

            INamedTypeSymbol type = null;

            foreach (var t in current.GetAllTypes())
            {
                type = LookupType(documentationCommentId, reminderIndex, t);
                if (type != null)
                {
                    if (searchType)
                    {
                        return(new LookupResult(type, prj.Solution, comp));
                    }
                    break;
                }
            }
            if (type == null)
            {
                return(LookupResult.Failure);
            }
            foreach (var member in type.GetMembers())
            {
                if (member.GetDocumentationCommentId() == documentationCommentId)
                {
                    return(new LookupResult(member, prj.Solution, comp));
                }
            }
            return(LookupResult.Failure);
        }
示例#9
0
 private static void GenerateDll(Project p)
 {
     var c = p.GetCompilationAsync().Result;
     var fileName = Path.Combine(OutputPath, p.Name, p.AssemblyName + ".dll");
     Directory.CreateDirectory(Path.GetDirectoryName(fileName));
     var result = c.Emit(fileName);
     if (!result.Success)
     {
         foreach (var diagnostic in result.Diagnostics)
             Debug.WriteLine(diagnostic.Location.GetMappedLineSpan().StartLinePosition.Line + " " +
                           diagnostic.GetMessage());
     }
 }
示例#10
0
 private List <INamedTypeSymbol> AnalyzeProject(Project project)
 {
     try
     {
         var compilation = project.GetCompilationAsync().Result;
         var allTypes    = compilation.GetSymbolsWithName(x => true, SymbolFilter.Type).OfType <ITypeSymbol>().Where(t => t is INamedTypeSymbol).OfType <INamedTypeSymbol>();
         return(allTypes.ToList(  ));
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error getting types from '" + project.Name + "': " + ex.Message);
         return(new List <INamedTypeSymbol>());
     }
 }
示例#11
0
        public static void Verify(Project project, DiagnosticAnalyzer diagnosticAnalyzer)
        {
            var compilation = project.GetCompilationAsync().Result;

            var compilationWithAnalyzer = GetDiagnostics(compilation, diagnosticAnalyzer);

            var expected = new List<int>(ExpectedIssues(compilation.SyntaxTrees.First()));
            foreach (var diagnostic in compilationWithAnalyzer
                
                .Where(diag => diag.Id == diagnosticAnalyzer.SupportedDiagnostics.Single().Id))
            {
                var line = diagnostic.GetLineNumberToReport();
                expected.Should().Contain(line);
                expected.Remove(line);
            }

            expected.Should().BeEquivalentTo(Enumerable.Empty<int>());
        }
示例#12
0
        /// <summary>
        /// Create a new P# static analysis context from the given program unit.
        /// </summary>
        /// <param name="project">Project</param>
        public static void Create(Project project)
        {
            AnalysisContext.Compilation = project.GetCompilationAsync().Result;

            AnalysisContext.Machines = new List<ClassDeclarationSyntax>();
            AnalysisContext.MachineInheritance = new Dictionary<ClassDeclarationSyntax, ClassDeclarationSyntax>();
            AnalysisContext.MachineActions = new Dictionary<ClassDeclarationSyntax, List<string>>();
            AnalysisContext.Summaries = new Dictionary<BaseMethodDeclarationSyntax, MethodSummary>();
            AnalysisContext.StateTransitionGraphs = new Dictionary<ClassDeclarationSyntax, StateTransitionGraphNode>();

            // Finds all the machines in the project.
            AnalysisContext.FindAllMachines();

            // Finds machine inheritance information.
            AnalysisContext.FindMachineInheritanceInformation();

            // Find all machine actions in the project.
            AnalysisContext.FindAllMachineActions();
        }
示例#13
0
    private static bool CreateCompilationFromSolution(Options options, MSBuildWorkspace workspace, out Task<Compilation> compilationAsync, out Project project) 
    {
      var solution = workspace.OpenSolutionAsync(options.Solution).Result;
      var projects = solution.Projects.Where(proj => proj.FilePath.Equals(options.Project));
      if (projects.Any())
      {
        project = projects.First();
      }
      else
      {
        Output.WriteError("Unable to find the specified project in solution. Project {0}", options.Project);

        project = null;
        compilationAsync = null;
        return false;
      }

      compilationAsync = project.GetCompilationAsync();
      return true;
    }
示例#14
0
        public static async Task<Project> MakeRetro(Project prj)
        {
            var compilation = await prj.GetCompilationAsync();

            var changedDocuments = MakeChanges(compilation);

            Project nPrj = prj;

            foreach (var newDoc in changedDocuments)
            {
                var docId = nPrj.GetDocumentId(newDoc.Item1);

                var doc = nPrj.GetDocument(docId);
                nPrj = nPrj.RemoveDocument(docId);

                var nd = nPrj.AddDocument(doc.Name, newDoc.Item2, doc.Folders, doc.FilePath);
                nPrj = nd.Project;
            }

            return nPrj;
        }
        private void NavigateOnForegroundThread(SourceLocation sourceLocation, SymbolKey symbolId, Project project, Document document)
        {
            AssertIsForeground();

            // Notify of navigation so third parties can intercept the navigation
            if (symbolId != null)
            {
                var symbolNavigationService = _workspace.Services.GetService<ISymbolNavigationService>();
                var symbol = symbolId.Resolve(project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None)).Symbol;

                // Do not allow third party navigation to types or constructors
                if (symbol != null &&
                    !(symbol is ITypeSymbol) &&
                    !symbol.IsConstructor() &&
                    symbolNavigationService.TrySymbolNavigationNotify(symbol, project.Solution))
                {
                    return;
                }
            }

            if (sourceLocation.IsValid)
            {
                // We must find the right document in this project. This may not be the
                // ContextDocumentId if you have a partial member that is shown under one
                // document, but only exists in the other

                if (document != null)
                {
                    var editorWorkspace = document.Project.Solution.Workspace;
                    var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
                    navigationService.TryNavigateToLineAndOffset(
                        editorWorkspace,
                        document.Id,
                        sourceLocation.StartPosition.Line,
                        sourceLocation.StartPosition.Character);
                }
            }
        }
        //public string GetMapName(ClassDeclarationSyntax element)
        //{
        //    var value = element.Identifier;
        //    const string nameProperty = "Name";

        //    Attributes attributes = null;

        //    var codeClass = element as CodeClass;
        //    if (codeClass != null)
        //    {
        //        attributes = codeClass.Attributes;
        //    }

        //    var codeProperty = element as CodeProperty;
        //    if (codeProperty != null)
        //    {
        //        attributes = codeProperty.Attributes;
        //    }

        //    foreach (CodeAttribute ca in attributes)
        //    {
        //        if (ca.Name.Contains(MapAttribute) && ca.Value.Contains(nameProperty))
        //        {
        //            value = ca.Value.Remove(0, ca.Value.IndexOf(nameProperty));
        //            value = value.Replace(" ", "");

        //            if (value.Contains(","))
        //            {
        //                value = value.Remove(value.IndexOf(","));
        //            }

        //            value = value.Remove(0, nameProperty.Length + 1);
        //            value = value.Replace("\"", "").ToLower();

        //            if (DoSuffix != null && codeClass != null)
        //            {
        //                if (value.EndsWith(DoSuffix.ToLower()))
        //                {
        //                    value = value.Replace(DoSuffix.ToLower(), "");
        //                }
        //            }

        //            if (DtoSuffix != null && codeClass != null)
        //            {
        //                if (value.EndsWith(DtoSuffix.ToLower()))
        //                {
        //                    value = value.Replace(DtoSuffix.ToLower(), "");
        //                }
        //            }
        //        }
        //    }

        //    value = value.ToLower();

        //    if (DoSuffix != null && codeClass != null)
        //    {
        //        if (value.EndsWith(DoSuffix.ToLower()))
        //        {
        //            value = value.Replace(DoSuffix.ToLower(), "");
        //        }
        //    }

        //    if (DtoSuffix != null && codeClass != null)
        //    {
        //        if (value.EndsWith(DtoSuffix.ToLower()))
        //        {
        //            value = value.Replace(DtoSuffix.ToLower(), "");
        //        }
        //    }

        //    return value;
        //}

        //public bool CompareTwoPropertyType(CodeProperty DOCodeProperty, CodeProperty DtoCodeProperty,
        //    List<MapDtoAndDo> similarClasses)
        //{
        //    var DOType = DOCodeProperty.Type.AsString;
        //    var DtoType = DtoCodeProperty.Type.AsString;

        //    if (DOType.Contains("IEnumerable") && DtoType.Contains("IEnumerable"))
        //    {
        //        DOType = DOType.Remove(0, DOType.IndexOf("<") + 1);
        //        DOType = DOType.Replace(">", "");

        //        DtoType = DtoType.Remove(0, DtoType.IndexOf("<") + 1);
        //        DtoType = DtoType.Replace(">", "");

        //        if (CompareInMapDtoAndDoCollection(DOType, DtoType, similarClasses))
        //            return true;
        //    }

        //    if (CompareInMapDtoAndDoCollection(DOType, DtoType, similarClasses))
        //        return true;

        //    if (DOType == DtoType)
        //    {
        //        return true;
        //    }

        //    return false;
        //}

        //public bool CompareTwoPropertyType(string DOType, string DtoType, List<MapDtoAndDo> similarClasses)
        //{
        //    if (DOType.Contains("IEnumerable") && DtoType.Contains("IEnumerable"))
        //    {
        //        DOType = DOType.Remove(0, DOType.IndexOf("<") + 1);
        //        DOType = DOType.Replace(">", "");

        //        DtoType = DtoType.Remove(0, DtoType.IndexOf("<") + 1);
        //        DtoType = DtoType.Replace(">", "");

        //        if (CompareInMapDtoAndDoCollection(DOType, DtoType, similarClasses))
        //            return true;
        //    }

        //    if (CompareInMapDtoAndDoCollection(DOType, DtoType, similarClasses))
        //        return true;

        //    if (DOType == DtoType)
        //    {
        //        return true;
        //    }

        //    return false;
        //}

        //public bool CompareInMapDtoAndDoCollection(string DOType, string DtoType, List<MapDtoAndDo> similarClasses)
        //{
        //    var similarInterfacesDO =
        //        similarClasses.Where(x => x.DOInterface != null).FirstOrDefault(x => x.DOInterface.FullName == DOType);
        //    var similarInterfacesDto =
        //        similarClasses.Where(x => x.DtoInterface != null)
        //            .FirstOrDefault(x => x.DtoInterface.FullName == DtoType);
        //    var checkingMapClass = new MapDtoAndDo();

        //    checkingMapClass = similarClasses.FirstOrDefault(x => x.DOClass.FullName == DOType);
        //    if (checkingMapClass != null &&
        //        checkingMapClass == similarClasses.FirstOrDefault(x => x.DtoClass.FullName == DtoType))
        //    {
        //        return true;
        //    }

        //    similarInterfacesDO =
        //        similarClasses.Where(x => x.DOInterface != null).FirstOrDefault(x => x.DOInterface.FullName == DOType);
        //    similarInterfacesDto =
        //        similarClasses.Where(x => x.DtoInterface != null)
        //            .FirstOrDefault(x => x.DtoInterface.FullName == DtoType);

        //    if (similarInterfacesDO != null &&
        //        similarInterfacesDO == similarClasses.FirstOrDefault(x => x.DtoClass.FullName == DtoType))
        //    {
        //        return true;
        //    }

        //    if (similarInterfacesDto != null &&
        //        similarClasses.FirstOrDefault(x => x.DOClass.FullName == DOType) == similarInterfacesDto)
        //    {
        //        return true;
        //    }

        //    if (similarInterfacesDO != null && similarInterfacesDO == similarInterfacesDto)
        //    {
        //        return true;
        //    }

        //    return false;
        //}

        //public KindOfProperty GetKindOfMapProperty(CodeProperty codeProperty, List<MapDtoAndDo> listOfSimilarClasses)
        //{
        //    var type = codeProperty.Type.AsString;

        //    if (type.Contains("IEnumerable"))
        //    {
        //        type = type.Remove(0, type.IndexOf("<") + 1);
        //        type = type.Replace(">", "");

        //        if (listOfSimilarClasses.Any(x => x.DOClass.FullName == type) ||
        //            listOfSimilarClasses.Where(x => x.DOInterface != null).Any(x => x.DOInterface.FullName == type))
        //        {
        //            return KindOfProperty.CollectionAttributeClasses;
        //        }

        //        if (listOfSimilarClasses.Any(x => x.DtoClass.FullName == type) ||
        //            listOfSimilarClasses.Where(x => x.DtoInterface != null).Any(x => x.DtoInterface.FullName == type))
        //        {
        //            return KindOfProperty.CollectionAttributeClasses;
        //        }
        //    }

        //    if (listOfSimilarClasses.Any(x => x.DOClass.FullName == type) ||
        //        listOfSimilarClasses.Where(x => x.DOInterface != null).Any(x => x.DOInterface.FullName == type))
        //    {
        //        return KindOfProperty.AttributeClass;
        //    }

        //    if (listOfSimilarClasses.Any(x => x.DtoClass.FullName == type) ||
        //        listOfSimilarClasses.Where(x => x.DtoInterface != null).Any(x => x.DtoInterface.FullName == type))
        //    {
        //        return KindOfProperty.AttributeClass;
        //    }

        //    return KindOfProperty.None;
        //}

        //public KindOfProperty GetKindOfMapProperty(string type, List<MapDtoAndDo> listOfSimilarClasses)
        //{
        //    if (type.Contains("IEnumerable"))
        //    {
        //        type = type.Remove(0, type.IndexOf("<") + 1);
        //        type = type.Replace(">", "");

        //        if (listOfSimilarClasses.Any(x => x.DOClass.FullName == type) ||
        //            listOfSimilarClasses.Where(x => x.DOInterface != null).Any(x => x.DOInterface.FullName == type))
        //        {
        //            return KindOfProperty.CollectionAttributeClasses;
        //        }

        //        if (listOfSimilarClasses.Any(x => x.DtoClass.FullName == type) ||
        //            listOfSimilarClasses.Where(x => x.DtoInterface != null).Any(x => x.DtoInterface.FullName == type))
        //        {
        //            return KindOfProperty.CollectionAttributeClasses;
        //        }
        //    }

        //    if (listOfSimilarClasses.Any(x => x.DOClass.FullName == type) ||
        //        listOfSimilarClasses.Where(x => x.DOInterface != null).Any(x => x.DOInterface.FullName == type))
        //    {
        //        return KindOfProperty.AttributeClass;
        //    }

        //    if (listOfSimilarClasses.Any(x => x.DtoClass.FullName == type) ||
        //        listOfSimilarClasses.Where(x => x.DtoInterface != null).Any(x => x.DtoInterface.FullName == type))
        //    {
        //        return KindOfProperty.AttributeClass;
        //    }

        //    return KindOfProperty.None;
        //}

        public async Task<IEnumerable<ClassDeclarationSyntax>> GetAllClasses(string project, bool isSkipAttribute,string attribute)
        {
            _project = _solution.Projects.First(x => x.Name == project);
            var compilation = await _project.GetCompilationAsync();
            var classVisitor = new ClassVirtualizationVisitor();
            var classes = new List<ClassDeclarationSyntax>();

            foreach (var syntaxTree in compilation.SyntaxTrees)
            {
                classVisitor.Visit(syntaxTree.GetRoot());
            }

            if (!isSkipAttribute)
            {
                classes = classVisitor.Classes.Where(x => x.AttributeLists
                    .Any(att => att.Attributes
                        .Any(att2 => att2.Name.ToString() == attribute))).ToList();
            }
            else
            {
                classes = classVisitor.Classes;
            }

            return classes;
        }
示例#17
0
 //static public IEnumerable<Project> GetProjects(String solutionPath) {
 //    return GetSolution(solutionPath).Projects;
 //}
 public static Compilation ProjectCompile(Project project)
 {
     //string solutionPath = @"C:\Users\Vitaliy\Documents\Visual Studio 2013\Projects\Metr2\Metr2.sln";
     //var workspace = MSBuildWorkspace.Create();
     //_solution = workspace.OpenSolutionAsync(solutionPath).Result;
     //var projects = _solution.Projects;
     //var project = projects.Where(p => p.Name.ToString() == projectToPick).First();
     return project.GetCompilationAsync().Result;
     // var temp = _compilation.GetCompilationNamespace(_compilation.GlobalNamespace);
 }
 internal ProjectCodeProvider(Project project, Compilation compilation)
 {
     this.Project = project;
     this.Compilation = project.GetCompilationAsync().Result;
 }
示例#19
0
        /// <summary>
        /// Returns a list of all analyzer diagnostics inside the specific project. This is an asynchronous operation.
        /// </summary>
        /// <param name="analyzers">The list of analyzers that should be used</param>
        /// <param name="project">The project that should be analyzed</param>
        /// <param name="cancellationToken">The cancellation token that the task will observe.</param>
        /// <returns>A list of diagnostics inside the project</returns>
        private static async Task<ImmutableArray<Diagnostic>> GetProjectAnalyzerDiagnosticsAsync(ImmutableArray<DiagnosticAnalyzer> analyzers, Project project, CancellationToken cancellationToken)
        {
            Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
            CompilationWithAnalyzers compilationWithAnalyzers = compilation.WithAnalyzers(analyzers, cancellationToken: cancellationToken);

            var allDiagnostics = await compilationWithAnalyzers.GetAllDiagnosticsAsync().ConfigureAwait(false);

            // We want analyzer diagnostics and analyzer exceptions
            return allDiagnostics.RemoveRange(compilation.GetDiagnostics());
        }
示例#20
0
        /// <summary>
        /// Compiles the given P# project.
        /// </summary>
        /// <param name="project">Project</param>
        private void CompileProject(Project project)
        {
            var compilation = project.GetCompilationAsync().Result;

            try
            {
                if (this.CompilationContext.ActiveCompilationTarget == CompilationTarget.Testing ||
                    this.CompilationContext.ActiveCompilationTarget == CompilationTarget.Distribution)
                {
                    this.ToFile(compilation, OutputKind.DynamicallyLinkedLibrary,
                        project.OutputFilePath);
                }
                else
                {
                    this.ToFile(compilation, project.CompilationOptions.OutputKind,
                        project.OutputFilePath);
                }
            }
            catch (ApplicationException ex)
            {
                ErrorReporter.ReportAndExit(ex.Message);
            }
        }
        private static async Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, ImmutableArray<DiagnosticAnalyzer> analyzers)
        {
            WriteInfo($"Running analysis for '{project.Name}'...");

            var compilation = await project.GetCompilationAsync();
            var compilationWithAnalyzers = compilation.WithAnalyzers(analyzers);
            var result = await compilationWithAnalyzers.GetAllDiagnosticsAsync();

            return result;
        }
        private static bool TryResolveSymbol(ISymbol symbol, Project project, CancellationToken cancellationToken, out ISymbol resolvedSymbol, out Project resolvedProject)
        {
            resolvedSymbol = null;
            resolvedProject = null;

            var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id);
            if (currentProject == null)
            {
                return false;
            }

            var originalCompilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var symbolId = SymbolKey.Create(symbol, originalCompilation, cancellationToken);
            var currentCompilation = currentProject.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken);

            if (symbolInfo.Symbol == null)
            {
                return false;
            }

            resolvedSymbol = symbolInfo.Symbol;
            resolvedProject = currentProject;

            return true;
        }
示例#23
0
        /// <summary>
        /// Returns a list of all analyzer diagnostics inside the specific project. This is an asynchronous operation.
        /// </summary>
        /// <param name="analyzers">The list of analyzers that should be used</param>
        /// <param name="project">The project that should be analyzed</param>
        /// <returns>A list of diagnostics inside the project</returns>
        private static async Task<ImmutableArray<Diagnostic>> GetProjectAnalyzerDiagnostics(ImmutableArray<DiagnosticAnalyzer> analyzers, Project project)
        {
            Compilation compilation = await project.GetCompilationAsync().ConfigureAwait(false);
            CompilationWithAnalyzers compilationWithAnalyzers = compilation.WithAnalyzers(analyzers);

            return await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().ConfigureAwait(false);
        }
示例#24
0
        internal async Task Parse()
        {
            if (isParsed)
            {
                return;
            }
            isParsed = true;

            // gather references
            var references = new List <Project>();
            var sln        = roslynProject.Solution;

            foreach (var reference in roslynProject.AllProjectReferences)
            {
                var project = solution.projects.FirstOrDefault(x => x.roslynProject.Id == reference.ProjectId);
                if (project == null)
                {
                    throw new Exception("Project reference not found in solution: " + reference.ProjectId);
                }
                references.Add(project);
                await project.Parse();
            }

            this.references = references;

            // init main objects
            classTypes     = new List <INamedTypeSymbol>();
            structTypes    = new List <INamedTypeSymbol>();
            interfaceTypes = new List <INamedTypeSymbol>();
            enumTypes      = new List <INamedTypeSymbol>();

            typeClassMethods = new HashSet <InvocationExpressionSyntax>();
            genericMethods   = new HashSet <IMethodSymbol>();
            genericTypes     = new HashSet <INamedTypeSymbol>();
            arrayTypes       = new HashSet <IArrayTypeSymbol>();
            pointerTypes     = new HashSet <IPointerTypeSymbol>();

            // parse normal members
            compilation = (CSharpCompilation)await roslynProject.GetCompilationAsync();

            ParseNamespace(compilation.Assembly.GlobalNamespace);

            // get special types
            foreach (var syntaxTree in compilation.SyntaxTrees)
            {
                ParseSpecialMembers(compilation, syntaxTree.GetRoot());
            }

            // merge all types in one list
            var allTypesList = new List <INamedTypeSymbol>();

            allTypesList.AddRange(classTypes);
            allTypesList.AddRange(structTypes);
            allTypesList.AddRange(interfaceTypes);
            allTypesList.AddRange(enumTypes);

            // dependency sort all types
            var allTypesDependencyOrderedList = new List <INamedTypeSymbol>();

            foreach (var type in allTypesList)
            {
                int index = -1, i = 0;
                foreach (var orderedType in allTypesDependencyOrderedList)
                {
                    if (type.IsValueType)
                    {
                        foreach (var member in orderedType.GetMembers())
                        {
                            if (member.Kind != SymbolKind.Field)
                            {
                                continue;
                            }
                            var field = (IFieldSymbol)member;
                            if (field.Type.FullName() == type.FullName())
                            {
                                index = i;
                                break;
                            }
                        }
                        if (index != -1)
                        {
                            break;
                        }
                    }
                    ++i;
                }

                if (index == -1)
                {
                    allTypesDependencyOrderedList.Add(type);
                }
                else
                {
                    allTypesDependencyOrderedList.Insert(index, type);
                }
            }
            allTypes = allTypesDependencyOrderedList;

            // validate basic syntax rules
            foreach (var type in allTypes)
            {
                ValidateType(type);
            }
        }
		internal static async Task<Tuple<ProjectCodeProvider, IMethodSymbol, SyntaxTree>> GetProviderContainingEntryPointAsync(
            Project project, CancellationToken cancellationToken = default(CancellationToken))
		{
            var compilation = project.GetCompilationAsync().Result;
			var mainSymbol = compilation.GetEntryPoint(cancellationToken);
			if (mainSymbol == null)
			{
				return null;
			}
			else
			{
				try
				{
					foreach (var tree in compilation.SyntaxTrees)
					{
						var finder = new MethodFinder(mainSymbol, compilation.GetSemanticModel(tree));
						var root = await tree.GetRootAsync(cancellationToken);
						finder.Visit(root);
						if (finder.Result != null)
						{
							return new Tuple<ProjectCodeProvider, IMethodSymbol, SyntaxTree>
                                (
                                    new ProjectCodeProvider(project, compilation), mainSymbol, tree
                                );
						}
					}
				}
				catch (OperationCanceledException)
				{
					Console.Error.WriteLine("Cancelling...");
				}

				return null;
			}
		}
		internal static ProjectCodeProvider GetProviderContainingEntryPoint(Project project, out IMethodSymbol mainSymbol)
		{
            var compilation = project.GetCompilationAsync().Result;
			mainSymbol = compilation.GetEntryPoint(new System.Threading.CancellationToken());

			foreach (var tree in compilation.SyntaxTrees)
			{
				var finder = new MethodFinder(mainSymbol, compilation.GetSemanticModel(tree));
				finder.Visit(tree.GetRoot());
				if (finder.Result != null)
				{
					return new ProjectCodeProvider(project, compilation);
				}
			}

			return null;
		}
        public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet options, CancellationToken cancellationToken)
        {
            if (project == null || symbol == null)
            {
                return false;
            }

            options = options ?? project.Solution.Workspace.Options;
            symbol = symbol.OriginalDefinition;

            // Prefer visible source locations if possible.
            var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource);
            var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
            var sourceLocation = visibleSourceLocations.FirstOrDefault() ?? sourceLocations.FirstOrDefault();

            if (sourceLocation != null)
            {
                var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
                if (targetDocument != null)
                {
                    var editorWorkspace = targetDocument.Project.Solution.Workspace;
                    var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
                    return navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options);
                }
            }

            // We don't have a source document, so show the Metadata as Source view in a preview tab.

            var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();
            if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
            {
                return false;
            }

            // Should we prefer navigating to the Object Browser over metadata-as-source?
            if (options.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language))
            {
                var libraryService = project.LanguageServices.GetService<ILibraryService>();
                if (libraryService == null)
                {
                    return false;
                }

                var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                var navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation);
                if (navInfo == null)
                {
                    navInfo = libraryService.NavInfoFactory.CreateForProject(project);
                }

                if (navInfo != null)
                {
                    var navigationTool = _serviceProvider.GetService<SVsObjBrowser, IVsNavigationTool>();
                    return navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK;
                }

                // Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen.
            }

            // Generate new source or retrieve existing source for the symbol in question
            var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, cancellationToken).WaitAndGetResult(cancellationToken);

            var vsRunningDocumentTable4 = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable4>();
            var fileAlreadyOpen = vsRunningDocumentTable4.IsMonikerValid(result.FilePath);

            var openDocumentService = _serviceProvider.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>();

            IVsUIHierarchy hierarchy;
            uint itemId;
            IOleServiceProvider localServiceProvider;
            IVsWindowFrame windowFrame;
            openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out localServiceProvider, out hierarchy, out itemId, out windowFrame);

            var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);

            var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie);
            var textBuffer = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer);

            if (!fileAlreadyOpen)
            {
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
                ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
            }

            windowFrame.Show();

            var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault();
            if (openedDocument != null)
            {
                var editorWorkspace = openedDocument.Project.Solution.Workspace;
                var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();

                return navigationService.TryNavigateToSpan(
                    workspace: editorWorkspace,
                    documentId: openedDocument.Id,
                    textSpan: result.IdentifierLocation.SourceSpan,
                    options: options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true));
            }

            return true;
        }
示例#28
0
        internal async Task Parse()
        {
            if (isParsed)
            {
                return;
            }
            isParsed = true;

            // get compilation
            compilation = (CSharpCompilation)await roslynProject.GetCompilationAsync();

            // validate syntax rules
            var options = new ProjectAnalyzer.Options()
            {
                breakOnError      = false,
                writeSyntaxSuffix = true,
                scanChilderen     = true
            };
            var analyzer = new ProjectAnalyzer(compilation, options);

            if (!await analyzer.Analyze(roslynProject))
            {
                throw new Exception("Failed to Analyze project: " + roslynProject.FilePath);
            }

            // gather references
            var references = new List <Project>();
            var sln        = roslynProject.Solution;

            foreach (var reference in roslynProject.AllProjectReferences)
            {
                var project = solution.projects.FirstOrDefault(x => x.roslynProject.Id == reference.ProjectId);
                if (project == null)
                {
                    throw new Exception("Project reference not found in solution: " + reference.ProjectId);
                }
                references.Add(project);
                await project.Parse();
            }

            this.references = references;

            // init main objects
            classTypes     = new List <INamedTypeSymbol>();
            structTypes    = new List <INamedTypeSymbol>();
            interfaceTypes = new List <INamedTypeSymbol>();
            enumTypes      = new List <INamedTypeSymbol>();
            delegateTypes  = new List <INamedTypeSymbol>();

            // parse normal members
            ParseNamespace(compilation.Assembly.GlobalNamespace);

            // merge all types in one list
            var allTypesList = new List <INamedTypeSymbol>();

            allTypesList.AddRange(classTypes);
            allTypesList.AddRange(structTypes);
            allTypesList.AddRange(interfaceTypes);
            allTypesList.AddRange(enumTypes);
            allTypesList.AddRange(delegateTypes);

            // dependency sort all types
            allTypes = DependencySortTypes(allTypesList);
        }
示例#29
0
        /// <summary>
        /// Compiles the given P# project.
        /// </summary>
        /// <param name="project">Project</param>
        private void CompileProject(Project project)
        {
            CompilationOptions options = null;
            if (this.CompilationContext.Configuration.OptimizationTarget == OptimizationTarget.Debug)
            {
                options = project.CompilationOptions.WithOptimizationLevel(OptimizationLevel.Debug);
            }
            else if (this.CompilationContext.Configuration.OptimizationTarget == OptimizationTarget.Release)
            {
                options = project.CompilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
            }

            project = project.WithCompilationOptions(options);

            var compilation = project.GetCompilationAsync().Result;

            try
            {
                if (this.CompilationContext.Configuration.CompilationTarget == CompilationTarget.Library ||
                    this.CompilationContext.Configuration.CompilationTarget == CompilationTarget.Testing ||
                    this.CompilationContext.Configuration.CompilationTarget == CompilationTarget.Remote)
                {
                    this.ToFile(compilation, OutputKind.DynamicallyLinkedLibrary,
                        project.OutputFilePath, true, true);
                }
                else
                {
                    this.ToFile(compilation, project.CompilationOptions.OutputKind,
                        project.OutputFilePath, true, true);
                }
            }
            catch (ApplicationException ex)
            {
                IO.Error.ReportAndExit(ex.Message);
            }
        }
示例#30
0
        /// <summary>
        /// Compiles the given P# project.
        /// </summary>
        /// <param name="project">Project</param>
        private void CompileProject(Project project)
        {
            var runtimeDllPath = typeof(Dispatcher).Assembly.Location;
            var bugFindingRuntimeDllPath = typeof(BugFindingDispatcher).Assembly.Location;

            var runtimeDll = project.MetadataReferences.FirstOrDefault(val => val.Display.EndsWith(
                Path.DirectorySeparatorChar + "Microsoft.PSharp.Runtime.dll"));

            if (runtimeDll != null && this.CompilationContext.ActiveCompilationTarget == CompilationTarget.Testing)
            {
                project = project.RemoveMetadataReference(runtimeDll);
            }

            if (this.CompilationContext.ActiveCompilationTarget == CompilationTarget.Testing &&
                !project.MetadataReferences.Any(val => val.Display.EndsWith(
                Path.DirectorySeparatorChar + "Microsoft.PSharp.BugFindingRuntime.dll")))
            {
                project = project.AddMetadataReference(MetadataReference.CreateFromFile(
                    bugFindingRuntimeDllPath));
            }

            var compilation = project.GetCompilationAsync().Result;

            try
            {
                if (this.CompilationContext.ActiveCompilationTarget == CompilationTarget.Testing ||
                    this.CompilationContext.ActiveCompilationTarget == CompilationTarget.Distribution)
                {
                    this.ToFile(compilation, OutputKind.DynamicallyLinkedLibrary,
                        project.OutputFilePath);
                }
                else
                {
                    this.ToFile(compilation, project.CompilationOptions.OutputKind,
                        project.OutputFilePath);
                }
            }
            catch (ApplicationException ex)
            {
                ErrorReporter.ReportAndExit(ex.Message);
            }
        }
		public virtual async Task<IEnumerable<INamespaceMetric>> Calculate(Project project, Solution solution)
		{
			var compilation = await project.GetCompilationAsync().ConfigureAwait(false);
			var namespaceDeclarations = await GetNamespaceDeclarations(project).ConfigureAwait(false);
			return await CalculateNamespaceMetrics(namespaceDeclarations, compilation, solution).ConfigureAwait(false);
		}
示例#32
0
        public void PinvokeMethodReferences_CS()
        {
            var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(
                @"

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
static class Module1
{
	[DllImport(""kernel32"", EntryPoint = ""CreateDirectoryA"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    public static extern int CreateDirectory(string lpPathName);

        private static int prop;
        public static int Prop1
        {
            get { return prop; }
            set
            {
                CreateDirectory(""T"");
                // Method Call 1
                prop = value;
                prop = null;
            }
        }

        public static void Main()
        {
            CreateDirectory(""T""); // Method Call 2            
            NormalMethod(); // Method Call 1
            NormalMethod(); // Method Call 2
        }

        public static void NormalMethod()
        {
        }
    }
                ");

            ProjectId  prj1Id = ProjectId.CreateNewId();
            DocumentId docId  = DocumentId.CreateNewId(prj1Id);

            var sln = new CustomWorkspace().CurrentSolution
                      .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.CSharp)
                      .AddMetadataReference(prj1Id, MscorlibRef)
                      .AddDocument(docId, "testFile", tree.GetText());

            Microsoft.CodeAnalysis.Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication));
            tree = (SyntaxTree)prj.GetDocument(docId).GetSyntaxTreeAsync().Result;
            Compilation comp = prj.GetCompilationAsync().Result;

            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            List <Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax> methodlist = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax>().ToList();
            SyntaxNode declareMethod = methodlist.ElementAt(0);
            SyntaxNode normalMethod  = methodlist.ElementAt(2);

            // pinvoke method calls
            var symbol     = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;

            Assert.Equal(2, references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(2, references.ElementAt(0).Locations.Count());
        }
 private static IMethodSymbol FindMethodSymbolInProject(MethodDescriptor methodDescriptor, Project project)
 {
     var compilation = project.GetCompilationAsync().Result;
     return FindMethodInCompilation(methodDescriptor, compilation);
 }
 private static Diagnostic[] GetDiagnostics(Project project, DiagnosticAnalyzer analyzer)
 {
     var compilationWithAnalyzers = project.GetCompilationAsync().Result.WithAnalyzers(ImmutableArray.Create(analyzer));
     var diagnostics = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result;
     return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray();
 }
 static void ProcessProject(Project project)
 {
     //TODO: ignore unit test projects....
     var compilation = project.GetCompilationAsync().Result;
     if (compilation.Language != "C#")
         return;
     foreach (var document in project.Documents)
         ProcessDocument(document);
 }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            MSBuildWorkspace workspace = MSBuildWorkspace.Create();

            var    targetProject = GetSelectedProject();
            string projectPath   = null;
            string projectName   = null;

            for (var i = 1; i <= targetProject.Properties.Count; i++)
            {
                if (targetProject.Properties.Item(i).Name == "FullPath")
                {
                    projectPath = targetProject.Properties.Item(i).Value.ToString();
                }
                if (targetProject.Properties.Item(i).Name == "FileName")
                {
                    projectName = targetProject.Properties.Item(i).Value.ToString();
                }
            }

            Microsoft.CodeAnalysis.Project currentProject = workspace.OpenProjectAsync(projectPath + projectName).Result;
            var projectCompilation = currentProject.GetCompilationAsync().Result;
            var assemblyTypes      = projectCompilation.Assembly.TypeNames;
            var namedSymbols       = assemblyTypes.Select(type => (INamedTypeSymbol)projectCompilation.GetSymbolsWithName(symbolName => symbolName == type).Where(symbol => symbol.Kind == SymbolKind.NamedType).First());
            var controllerSymbols  = namedSymbols.Where(symbol => CheckTypeIsOrInheritedFromController(symbol)).ToList();

            var controllerMethodsCollection = new Dictionary <INamedTypeSymbol, IEnumerable <IMethodSymbol> >();

            foreach (var controller in controllerSymbols)
            {
                var isAuthorized            = CheckControllerIsOrInheritedFromAuthorizedController(controller);
                var controllerActionMethods = controller.GetMembers()
                                              .Where(member => member.DeclaredAccessibility == Accessibility.Public && member.Kind == SymbolKind.Method && ((IMethodSymbol)member).MethodKind == MethodKind.Ordinary)
                                              .Select(item => (IMethodSymbol)item).ToList();
                var anonymousMethods = isAuthorized
                    ? controllerActionMethods.Where(action => action.GetAttributes().Any(attribute => attribute.AttributeClass.Name == "AllowAnonymousAttribute"))
                    : controllerActionMethods.Where(action => action.GetAttributes().All(attribute => attribute.AttributeClass.Name != "AuthorizeAttribute"));

                if (anonymousMethods.Count() > 0)
                {
                    controllerMethodsCollection.Add(controller, anonymousMethods);
                }
            }

            DTE2 dte = (DTE2)ServiceProvider.GetServiceAsync(typeof(DTE)).Result;
            OutputWindowPanes panes = dte.ToolWindows.OutputWindow.OutputWindowPanes;
            OutputWindowPane  outputPane;

            try
            {
                outputPane = panes.Item("N-Tools");
            }
            catch (ArgumentException)
            {
                outputPane = panes.Add("N-Tools");
            }
            outputPane.Activate();
            foreach (var record in controllerMethodsCollection)
            {
                outputPane.OutputString("Controller: " + record.Key.Name);
                foreach (var method in record.Value)
                {
                    outputPane.OutputString(Environment.NewLine);
                    outputPane.OutputString("\t");
                    outputPane.OutputString("Action: ");
                    outputPane.OutputString(method.Name);
                    outputPane.OutputString(Environment.NewLine);
                }
                outputPane.OutputString(Environment.NewLine);
            }
        }
        /// <summary>
        /// Gets all <see cref="Diagnostic"/> instances within a specific <see cref="Project"/> which are relevant to a
        /// <see cref="FixAllContext"/>.
        /// </summary>
        /// <param name="fixAllContext">The context for the Fix All operation.</param>
        /// <param name="project">The project.</param>
        /// <returns>A <see cref="Task{TResult}"/> representing the asynchronous operation. When the task completes
        /// successfully, the <see cref="Task{TResult}.Result"/> will contain the requested diagnostics.</returns>
        private static async Task<ImmutableArray<Diagnostic>> GetAllDiagnosticsAsync(FixAllContext fixAllContext, Project project)
        {
            if (GetAnalyzerSyntaxDiagnosticsAsync == null || GetAnalyzerSemanticDiagnosticsAsync == null)
            {
                return await fixAllContext.GetAllDiagnosticsAsync(project).ConfigureAwait(false);
            }

            /*
             * The rest of this method is workaround code for issues with Roslyn 1.1...
             */

            var analyzers = GetDiagnosticAnalyzersForContext(fixAllContext);

            // Most code fixes in this project operate on diagnostics reported by analyzers in this project. However, a
            // few code fixes also operate on standard warnings produced by the C# compiler. Special handling is
            // required for the latter case since these warnings are not considered "analyzer diagnostics".
            bool includeCompilerDiagnostics = fixAllContext.DiagnosticIds.Any(x => x.StartsWith("CS", StringComparison.Ordinal));

            // Use a single CompilationWithAnalyzers for the entire operation. This allows us to use the
            // GetDeclarationDiagnostics workaround for dotnet/roslyn#7446 a single time, rather than once per document.
            var compilation = await project.GetCompilationAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
            var compilationWithAnalyzers = compilation.WithAnalyzers(analyzers, project.AnalyzerOptions, fixAllContext.CancellationToken);
            ImmutableArray<Diagnostic> diagnostics = await GetAllDiagnosticsAsync(compilation, compilationWithAnalyzers, analyzers, project.Documents, includeCompilerDiagnostics, fixAllContext.CancellationToken).ConfigureAwait(false);

            // Make sure to filter the results to the set requested for the Fix All operation, since analyzers can
            // report diagnostics with different IDs.
            diagnostics = diagnostics.RemoveAll(x => !fixAllContext.DiagnosticIds.Contains(x.Id));
            return diagnostics;
        }
示例#38
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="configuration">Configuration</param>
        /// <param name="project">Project</param>
        private AnalysisContext(Configuration configuration, Project project)
        {
            this.Configuration = configuration;
            this.Solution = project.Solution;
            this.Compilation = project.GetCompilationAsync().Result;

            this.Machines = new List<ClassDeclarationSyntax>();
            this.MachineInheritance = new Dictionary<ClassDeclarationSyntax, ClassDeclarationSyntax>();
            this.MachineActions = new Dictionary<ClassDeclarationSyntax, List<string>>();
            this.Summaries = new Dictionary<BaseMethodDeclarationSyntax, MethodSummary>();
            this.StateTransitionGraphs = new Dictionary<ClassDeclarationSyntax, StateTransitionGraphNode>();

            // Finds all the machines in the project.
            this.FindAllMachines();

            // Finds machine inheritance information.
            this.FindMachineInheritanceInformation();

            // Find all machine actions in the project.
            this.FindAllMachineActions();
        }
示例#39
0
        private static void CompileProject(Microsoft.CodeAnalysis.Project project)
        {
            project = project.WithParseOptions(((CSharpParseOptions)project.ParseOptions).WithPreprocessorSymbols(project.ParseOptions.PreprocessorSymbolNames.Concat(new[] { "LINQREWRITE" })));
            var compilation = project.GetCompilationAsync().Result;

            var hasErrs = false;

            foreach (var item in compilation.GetDiagnostics())
            {
                PrintDiagnostic(item);
                if (item.Severity == DiagnosticSeverity.Error)
                {
                    hasErrs = true;
                }
            }

            if (hasErrs)
            {
                throw new ExitException(1);
            }
            var updatedProject = project;

            if (!NoRewrite)
            {
                foreach (var doc in project.Documents)
                {
                    Console.WriteLine(doc.FilePath);
                    var syntaxTree = doc.GetSyntaxTreeAsync().Result;

                    var rewriter = new LinqRewriter(compilation.GetSemanticModel(syntaxTree));

                    var rewritten = rewriter.Visit(syntaxTree.GetRoot()).NormalizeWhitespace();
                    if (WriteFiles)
                    {
                        var tostring = rewritten.ToFullString();
                        if (syntaxTree.ToString() != tostring)
                        {
                            File.WriteAllText(doc.FilePath, tostring, Encoding.UTF8);
                        }
                    }
                    updatedProject = updatedProject.GetDocument(doc.Id).WithSyntaxRoot(rewritten).Project;
                }
                project     = updatedProject;
                compilation = project.GetCompilationAsync().Result;
                hasErrs     = false;
                foreach (var item in compilation.GetDiagnostics())
                {
                    PrintDiagnostic(item);
                    if (item.Severity == DiagnosticSeverity.Error)
                    {
                        hasErrs = true;
                        if (item.Location != Location.None)
                        {
                            Console.ForegroundColor = ConsoleColor.White;
                            //var lines = item.Location.GetLineSpan();
                            var node = item.Location.SourceTree.GetRoot().FindNode(item.Location.SourceSpan);
                            var k    = node.AncestorsAndSelf().FirstOrDefault(x => x is MethodDeclarationSyntax);
                            if (k != null)
                            {
                                Console.WriteLine(k.ToString());
                            }
                            Console.ResetColor();
                        }
                    }
                }
            }
            string outputPath = project.OutputFilePath.Replace("\\", "/");
            var    objpath    = outputPath.Replace("/bin/", "/obj/");

            if (ForProjBuild)
            {
                outputPath = objpath;
            }

            var ns           = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");
            var xml          = XDocument.Load(project.FilePath);
            var hasResources = xml
                               .DescendantNodes()
                               .OfType <XElement>()
                               .Where(x => x.Name == ns + "EmbeddedResource" || x.Name == ns + "Resource")
                               .Any();

            if (hasResources)
            {
                foreach (var resource in Directory.GetFiles(Path.GetDirectoryName(objpath), "*.resources"))
                {
                    File.Delete(resource);
                }

                var args = new object[] { project.FilePath, new Shaman.Runtime.ProcessUtils.RawCommandLineArgument("/p:Configuration=Release") };
                try
                {
                    ProcessUtils.RunPassThrough("msbuild", args);
                }
                catch (Exception ex) when(!(ex is ProcessException))
                {
                    ProcessUtils.RunPassThrough("xbuild", args);
                }
            }
            var resources = hasResources ? Directory.EnumerateFiles(Path.GetDirectoryName(objpath), "*.resources")
                            .Select(x =>
            {
                return(new ResourceDescription(Path.GetFileName(x), () => File.OpenRead(x), true));
            }).ToList() : Enumerable.Empty <ResourceDescription>();

            /*
             * var resources = XDocument.Load(project.FilePath)
             *  .DescendantNodes()
             *  .OfType<XElement>().Where(x => x.Name == ns + "EmbeddedResource")
             *  .Select(x => x.Attribute(ns + "Include"))
             *  .Select(x => Path.Combine(Path.GetDirectoryName(project.FilePath), x.Value))
             *  .Select(x =>
             *  {
             *      var rd = new ResourceDescription();
             *  }).ToList();
             */

            compilation.Emit(outputPath, manifestResources: resources);



            //compilation.Emit(@"C:\temp\roslynrewrite\" + project.AssemblyName + ".dll");
            if (hasErrs)
            {
                throw new ExitException(1);
            }
        }
示例#40
0
        /// <summary>
        /// Compiles the given P# project.
        /// </summary>
        /// <param name="project">Project</param>
        private static void CompileProject(Project project)
        {
            var runtimeDllPath = typeof(Dispatcher).Assembly.Location;
            var bugFindingRuntimeDllPath = typeof(BugFindingDispatcher).Assembly.Location;

            var runtimeDll = project.MetadataReferences.FirstOrDefault(val => val.Display.EndsWith(
                Path.DirectorySeparatorChar + "Microsoft.PSharp.Runtime.dll"));

            if (runtimeDll != null && (Configuration.RunStaticAnalysis ||
                Configuration.RunDynamicAnalysis))
            {
                project = project.RemoveMetadataReference(runtimeDll);
            }

            if ((Configuration.RunStaticAnalysis || Configuration.RunDynamicAnalysis) &&
                !project.MetadataReferences.Any(val => val.Display.EndsWith(
                Path.DirectorySeparatorChar + "Microsoft.PSharp.BugFindingRuntime.dll")))
            {
                project = project.AddMetadataReference(MetadataReference.CreateFromFile(
                    bugFindingRuntimeDllPath));
            }

            var compilation = project.GetCompilationAsync().Result;

            try
            {
                if (Configuration.RunDynamicAnalysis)
                {
                    var dll = CompilationEngine.ToFile(compilation, OutputKind.DynamicallyLinkedLibrary,
                        project.OutputFilePath);

                    if (Configuration.ProjectName.Equals(project.Name))
                    {
                        Configuration.AssembliesToBeAnalyzed.Add(dll);
                    }
                }
                else if (Configuration.CompileForDistribution)
                {
                    CompilationEngine.ToFile(compilation, OutputKind.DynamicallyLinkedLibrary,
                        project.OutputFilePath);
                }
                else
                {
                    CompilationEngine.ToFile(compilation, project.CompilationOptions.OutputKind,
                        project.OutputFilePath);
                }
            }
            catch (ApplicationException ex)
            {
                ErrorReporter.ReportAndExit(ex.Message);
            }
        }
示例#41
0
        public async Task Parse()
        {
            // init main objects
            assemblyName     = project.AssemblyName;
            allObjects       = new List <ObjectType>();
            classObjects     = new List <ClassType>();
            structObjects    = new List <StructType>();
            interfaceObjects = new List <InterfaceType>();
            enumObjects      = new List <EnumType>();

            // validate compiler options
            var parseOptions = (CSharpParseOptions)project.ParseOptions;

            if (parseOptions.LanguageVersion != LanguageVersion.CSharp3)
            {
                throw new Exception("Project lang version must be 3.0: " + project.FilePath);
            }

            var compilationOptions = project.CompilationOptions;

            if (compilationOptions.Platform != Platform.AnyCpu)
            {
                throw new Exception("Project platform must be AnyCpu: " + project.FilePath);
            }

            // get project type
            var kind = compilationOptions.OutputKind;

            if (kind == OutputKind.DynamicallyLinkedLibrary)
            {
                type = ProjectTypes.Dll;
            }
            else if (kind == OutputKind.ConsoleApplication || kind == OutputKind.WindowsApplication)
            {
                type = ProjectTypes.Exe;
            }
            else
            {
                throw new Exception("Unsuported project kind: " + project.FilePath);
            }

            // check optimization level
            isReleaseBuild = compilationOptions.OptimizationLevel == OptimizationLevel.Release;

            // gather references
            references = new List <string>();
            var sln = project.Solution;

            foreach (var reference in project.AllProjectReferences)
            {
                var p = sln.GetProject(reference.ProjectId);
                references.Add(p.AssemblyName);
            }

            // parse syntax tree
            var compilation = await project.GetCompilationAsync();

            foreach (var doc in project.Documents)
            {
                var syntaxTree = await doc.GetSyntaxTreeAsync() as CSharpSyntaxTree;

                if (syntaxTree == null)
                {
                    throw new Exception("Not a C# file: " + doc.FilePath);
                }
                var semanticModel = await doc.GetSemanticModelAsync();

                AddObjects(syntaxTree.GetRoot().ChildNodes(), syntaxTree, semanticModel);
            }

            // add all objects to all list
            allObjects.AddRange(enumObjects);
            allObjects.AddRange(interfaceObjects);
            allObjects.AddRange(structObjects);
            allObjects.AddRange(classObjects);

            // resolve objects
            foreach (var obj in allObjects)
            {
                obj.Resolve();
            }
        }