コード例 #1
0
        internal void VerifyRudeDiagnostics(
            EditScript <SyntaxNode> editScript,
            ActiveStatementsDescription description,
            RudeEditDiagnosticDescription[] expectedDiagnostics)
        {
            var oldActiveStatements = description.OldSpans;

            if (description.OldTrackingSpans != null)
            {
                Assert.Equal(oldActiveStatements.Length, description.OldTrackingSpans.Length);
            }

            string newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
            string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();

            var oldText = SourceText.From(oldSource);
            var newText = SourceText.From(newSource);

            var diagnostics = new List <RudeEditDiagnostic>();
            var actualNewActiveStatements  = new LinePositionSpan[oldActiveStatements.Length];
            var actualNewExceptionRegions  = new ImmutableArray <LinePositionSpan> [oldActiveStatements.Length];
            var updatedActiveMethodMatches = new List <AbstractEditAndContinueAnalyzer.UpdatedMemberInfo>();
            var editMap = Analyzer.BuildEditMap(editScript);

            DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");

            TestActiveStatementTrackingService trackingService;

            if (description.OldTrackingSpans != null)
            {
                trackingService = new TestActiveStatementTrackingService(documentId, description.OldTrackingSpans);
            }
            else
            {
                trackingService = null;
            }

            Analyzer.AnalyzeSyntax(
                editScript,
                editMap,
                oldText,
                newText,
                documentId,
                trackingService,
                oldActiveStatements.AsImmutable(),
                actualNewActiveStatements,
                actualNewExceptionRegions,
                updatedActiveMethodMatches,
                diagnostics);

            diagnostics.Verify(newSource, expectedDiagnostics);

            // check active statements:
            AssertSpansEqual(description.NewSpans, actualNewActiveStatements, newSource, newText);

            if (diagnostics.Count == 0)
            {
                // check old exception regions:
                for (int i = 0; i < oldActiveStatements.Length; i++)
                {
                    var actualOldExceptionRegions = Analyzer.GetExceptionRegions(
                        oldText,
                        editScript.Match.OldRoot,
                        oldActiveStatements[i].Span,
                        isLeaf: (oldActiveStatements[i].Flags & ActiveStatementFlags.LeafFrame) != 0);

                    AssertSpansEqual(description.OldRegions[i], actualOldExceptionRegions, oldSource, oldText);
                }

                // check new exception regions:
                Assert.Equal(description.NewRegions.Length, actualNewExceptionRegions.Length);
                for (int i = 0; i < description.NewRegions.Length; i++)
                {
                    AssertSpansEqual(description.NewRegions[i], actualNewExceptionRegions[i], newSource, newText);
                }
            }
            else
            {
                for (int i = 0; i < oldActiveStatements.Length; i++)
                {
                    Assert.Equal(0, description.NewRegions[i].Length);
                }
            }

            if (description.OldTrackingSpans != null)
            {
                // Verify that the new tracking spans are equal to the new active statements.
                AssertEx.Equal(trackingService.TrackingSpans, description.NewSpans.Select(s => (TextSpan?)s));
            }
        }
コード例 #2
0
 public void TestDocumentId()
 {
     VerifyJsonSerialization(DocumentId.CreateNewId(ProjectId.CreateNewId("project"), "document"));
 }
        internal void VerifySemantics(
            EditScript <SyntaxNode> editScript,
            ActiveStatementsDescription?activeStatements        = null,
            IEnumerable <string>?additionalOldSources           = null,
            IEnumerable <string>?additionalNewSources           = null,
            SemanticEditDescription[]?expectedSemanticEdits     = null,
            DiagnosticDescription?expectedDeclarationError      = null,
            RudeEditDiagnosticDescription[]?expectedDiagnostics = null)
        {
            activeStatements ??= ActiveStatementsDescription.Empty;

            var editMap = BuildEditMap(editScript);

            var oldRoot = editScript.Match.OldRoot;
            var newRoot = editScript.Match.NewRoot;

            var oldSource = oldRoot.SyntaxTree.ToString();
            var newSource = newRoot.SyntaxTree.ToString();

            var oldText = SourceText.From(oldSource);
            var newText = SourceText.From(newSource);

            IEnumerable <SyntaxTree> oldTrees = new[] { oldRoot.SyntaxTree };
            IEnumerable <SyntaxTree> newTrees = new[] { newRoot.SyntaxTree };

            if (additionalOldSources != null)
            {
                oldTrees = oldTrees.Concat(additionalOldSources.Select(s => ParseText(s)));
            }

            if (additionalOldSources != null)
            {
                newTrees = newTrees.Concat(additionalNewSources.Select(s => ParseText(s)));
            }

            var oldCompilation = CreateLibraryCompilation("Old", oldTrees);
            var newCompilation = CreateLibraryCompilation("New", newTrees);

            var oldModel = oldCompilation.GetSemanticModel(oldRoot.SyntaxTree);
            var newModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree);

            var oldActiveStatements        = activeStatements.OldStatements.AsImmutable();
            var updatedActiveMethodMatches = new List <UpdatedMemberInfo>();
            var triviaEdits         = new List <(SyntaxNode OldNode, SyntaxNode NewNode)>();
            var actualLineEdits     = new List <LineChange>();
            var actualSemanticEdits = new List <SemanticEdit>();
            var diagnostics         = new List <RudeEditDiagnostic>();

            Assert.IsType <TestActiveStatementSpanTracker>(Analyzer.GetTestAccessor().ActiveStatementSpanTracker);
            var documentId = DocumentId.CreateNewId(ProjectId.CreateNewId());

            var actualNewActiveStatements = new ActiveStatement[activeStatements.OldStatements.Length];
            var actualNewExceptionRegions = new ImmutableArray <LinePositionSpan> [activeStatements.OldStatements.Length];

            Analyzer.GetTestAccessor().AnalyzeSyntax(
                editScript,
                editMap,
                oldText,
                newText,
                documentId,
                oldActiveStatements,
                actualNewActiveStatements,
                actualNewExceptionRegions,
                updatedActiveMethodMatches,
                diagnostics);

            diagnostics.Verify(newSource);

            Analyzer.GetTestAccessor().AnalyzeTrivia(
                oldText,
                newText,
                editScript.Match,
                editMap,
                triviaEdits,
                actualLineEdits,
                diagnostics,
                CancellationToken.None);

            diagnostics.Verify(newSource);

            Analyzer.GetTestAccessor().AnalyzeSemantics(
                editScript,
                editMap,
                oldText,
                oldActiveStatements,
                triviaEdits,
                updatedActiveMethodMatches,
                oldModel,
                newModel,
                actualSemanticEdits,
                diagnostics,
                out var firstDeclarationErrorOpt,
                CancellationToken.None);

            var actualDeclarationErrors   = (firstDeclarationErrorOpt != null) ? new[] { firstDeclarationErrorOpt } : Array.Empty <Diagnostic>();
            var expectedDeclarationErrors = (expectedDeclarationError != null) ? new[] { expectedDeclarationError } : Array.Empty <DiagnosticDescription>();

            actualDeclarationErrors.Verify(expectedDeclarationErrors);

            diagnostics.Verify(newSource, expectedDiagnostics);

            if (expectedSemanticEdits == null)
            {
                return;
            }

            Assert.Equal(expectedSemanticEdits.Length, actualSemanticEdits.Count);

            for (var i = 0; i < actualSemanticEdits.Count; i++)
            {
                var editKind = expectedSemanticEdits[i].Kind;

                Assert.Equal(editKind, actualSemanticEdits[i].Kind);

                var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdits[i].SymbolProvider(oldCompilation) : null;
                var expectedNewSymbol = expectedSemanticEdits[i].SymbolProvider(newCompilation);
                var actualOldSymbol   = actualSemanticEdits[i].OldSymbol;
                var actualNewSymbol   = actualSemanticEdits[i].NewSymbol;

                Assert.Equal(expectedOldSymbol, actualOldSymbol);
                Assert.Equal(expectedNewSymbol, actualNewSymbol);

                var expectedSyntaxMap = expectedSemanticEdits[i].SyntaxMap;
                var actualSyntaxMap   = actualSemanticEdits[i].SyntaxMap;

                Assert.Equal(expectedSemanticEdits[i].PreserveLocalVariables, actualSemanticEdits[i].PreserveLocalVariables);

                if (expectedSyntaxMap != null)
                {
                    Contract.ThrowIfNull(actualSyntaxMap);
                    Assert.True(expectedSemanticEdits[i].PreserveLocalVariables);

                    var newNodes = new List <SyntaxNode>();

                    foreach (var expectedSpanMapping in expectedSyntaxMap)
                    {
                        var newNode         = FindNode(newRoot, expectedSpanMapping.Value);
                        var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key);
                        var actualOldNode   = actualSyntaxMap(newNode);

                        Assert.Equal(expectedOldNode, actualOldNode);

                        newNodes.Add(newNode);
                    }
                }
                else if (!expectedSemanticEdits[i].PreserveLocalVariables)
                {
                    Assert.Null(actualSyntaxMap);
                }
            }
        }
コード例 #4
0
        private async Task <int> OnExecuteAsync(CommandLineApplication app,
                                                CancellationToken cancellationToken = default)
        {
            var outputDir = Path.IsPathFullyQualified(OutputProjectDir)
                ? OutputProjectDir
                : Path.GetFullPath(OutputProjectDir);

            Directory.CreateDirectory(outputDir);

            var workspace   = new AdhocWorkspace();
            var projectId   = ProjectId.CreateNewId();
            var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), "XP.SDK", "XP.SDK", LanguageNames.CSharp)
                              .WithDefaultNamespace("XP.SDK");
            var project = workspace.AddProject(projectInfo);

            var typeMap = new TypeMap(BuildTypeCallback);

            _enumBuilder = new EnumBuilder(workspace, projectId, outputDir, typeMap)
                           .Map("xpMainWindowStyle_MainWindow", "MainWindowType")
                           .Map("xpProperty_MainWindowType", "MainWindowProperty")
                           .Map("xpMessage_CloseButtonPushed", "MainWindowMessage")
                           .Map("xpSubWindowStyle_SubWindow", "SubWindowType")
                           .Map("xpProperty_SubWindowType", "SubWindowProperty")
                           .Map("xpPushButton", "ButtonType")
                           .Map("xpButtonBehaviorPushButton", "ButtonBehavior")
                           .Map("xpProperty_ButtonType", "ButtonProperty")
                           .Map("xpMsg_PushButtonPressed", "ButtonMessage")
                           .Map("xpTextEntryField", "TextFieldType")
                           .Map("xpProperty_EditFieldSelStart", "TextFieldProperty")
                           .Map("xpMsg_TextFieldChanged", "TextFieldMessage")
                           .Map("xpScrollBarTypeScrollBar", "ScrollBarType")
                           .Map("xpProperty_ScrollBarSliderPosition", "ScrollBarProperty")
                           .Map("xpMsg_ScrollBarSliderPositionChanged", "ScrollBarMessage")
                           .Map("xpProperty_CaptionLit", "CaptionProperty")
                           .Map("xpShip", "GeneralGraphicsType")
                           .Map("xpProperty_GeneralGraphicsType", "GeneralGraphicsProperty")
                           .Map("xpProperty_ProgressPosition", "ProgressBarProperty");
            _handleBuilder   = new HandleBuilder(workspace, projectId, outputDir, typeMap);
            _delegateBuilder = new DelegateBuilder(workspace, projectId, outputDir, typeMap);
            _structBuilder   = new StructBuilder(workspace, projectId, outputDir, typeMap);
            var functionBuilder = new FunctionBuilder(workspace, projectId, outputDir, typeMap);

            var xplmHeadersPath = Path.Combine(SdkRoot, "CHeaders", "XPLM");

            if (!Directory.Exists(xplmHeadersPath))
            {
                throw new DirectoryNotFoundException($"Directory '{xplmHeadersPath}' does not exist.");
            }
            var xmplHeaders = Directory.EnumerateFiles(xplmHeadersPath, "*.h");

            var xpWidgetsHeadersPath = Path.Combine(SdkRoot, "CHeaders", "Widgets");

            if (!Directory.Exists(xpWidgetsHeadersPath))
            {
                throw new DirectoryNotFoundException($"Directory '{xpWidgetsHeadersPath}' does not exist.");
            }
            var xpWidgetsHeaders = Directory.EnumerateFiles(xpWidgetsHeadersPath, "*.h");
            var headers          = xmplHeaders.Concat(xpWidgetsHeaders)
                                   /*.Where(x => Path.GetFileName(x) != "XPStandardWidgets.h")*/;

            var parserOptions = new CppParserOptions
            {
                Defines             = { "IBM", "XPLM303", "XPLM302", "XPLM301", "XPLM300", "XPLM210", "XPLM200" },
                ParseSystemIncludes = false,
                TargetCpu           = CppTargetCpu.X86_64,
                IncludeFolders      = { xplmHeadersPath },
            };


            var compilation = CppParser.ParseFiles(headers.ToList(), parserOptions);

            foreach (var child in compilation.Children().OfType <CppType>())
            {
                await BuildTypeAsync(child);
            }

            var functionsByHeader = compilation
                                    .Functions
                                    .ToLookup(x => x.Span.Start.File);

            foreach (var functionsInHeader in functionsByHeader)
            {
                await functionBuilder.BuildAsync(functionsInHeader);
            }

            foreach (var document in workspace.CurrentSolution.Projects.SelectMany(p => p.Documents))
            {
                var text = await document.GetTextAsync(cancellationToken);

                await using var writer = new StreamWriter(document.FilePath, false);
                text.Write(writer, cancellationToken);
            }

            return(0);

            async Task BuildTypeCallback(dynamic item)
            {
                using (Log.PushIdent())
                {
                    await BuildTypeAsync(item);
                }
            }
        }
コード例 #5
0
        public async Task AnalyzeDocumentAsync_InsignificantChangesInMethodBody()
        {
            var source1 = @"
class C
{
    public static void Main()
    {
        // comment
        System.Console.WriteLine(1);
    }
}
";
            var source2 = @"
class C
{
    public static void Main()
    {
        System.Console.WriteLine(1);
    }
}
";

            using var workspace = TestWorkspace.CreateCSharp(source1, composition: s_composition);
            var oldSolution = workspace.CurrentSolution;
            var oldProject  = oldSolution.Projects.Single();
            var oldDocument = oldProject.Documents.Single();
            var oldText     = await oldDocument.GetTextAsync();

            var oldSyntaxRoot = await oldDocument.GetSyntaxRootAsync();

            var documentId  = oldDocument.Id;
            var newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2));
            var newDocument = newSolution.GetDocument(documentId);
            var newText     = await newDocument.GetTextAsync();

            var newSyntaxRoot = await newDocument.GetSyntaxRootAsync();

            const string oldStatementSource   = "System.Console.WriteLine(1);";
            var          oldStatementPosition = source1.IndexOf(oldStatementSource, StringComparison.Ordinal);
            var          oldStatementTextSpan = new TextSpan(oldStatementPosition, oldStatementSource.Length);
            var          oldStatementSpan     = oldText.Lines.GetLinePositionSpan(oldStatementTextSpan);
            var          oldStatementSyntax   = oldSyntaxRoot.FindNode(oldStatementTextSpan);

            var baseActiveStatements = ImmutableArray.Create(ActiveStatementsDescription.CreateActiveStatement(ActiveStatementFlags.IsLeafFrame, oldStatementSpan, DocumentId.CreateNewId(ProjectId.CreateNewId())));
            var analyzer             = new CSharpEditAndContinueAnalyzer();

            var result = await analyzer.AnalyzeDocumentAsync(oldDocument, baseActiveStatements, newDocument, ImmutableArray <TextSpan> .Empty, CancellationToken.None);

            Assert.True(result.HasChanges);
            Assert.True(result.SemanticEdits[0].PreserveLocalVariables);
            var syntaxMap = result.SemanticEdits[0].SyntaxMap;

            var newStatementSpan     = result.ActiveStatements[0].Span;
            var newStatementTextSpan = newText.Lines.GetTextSpan(newStatementSpan);
            var newStatementSyntax   = newSyntaxRoot.FindNode(newStatementTextSpan);

            var oldStatementSyntaxMapped = syntaxMap(newStatementSyntax);

            Assert.Same(oldStatementSyntax, oldStatementSyntaxMapped);
        }
コード例 #6
0
        public void TestImplicitCacheKeepsObjectAlive1()
        {
            var workspace    = new AdhocWorkspace(MockHostServices.Instance, workspaceKind: WorkspaceKind.Host);
            var cacheService = new ProjectCacheService(workspace, int.MaxValue);
            var reference    = ObjectReference.CreateFromFactory(() => new object());

            reference.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, r));
            reference.AssertHeld();

            GC.KeepAlive(cacheService);
        }
コード例 #7
0
        public void Initalize()
        {
            _logger.LogInformation($"Detecting CSX files in '{_env.Path}'.");

            var allCsxFiles = Directory.GetFiles(_env.Path, "*.csx", SearchOption.TopDirectoryOnly);

            if (allCsxFiles.Length == 0)
            {
                _logger.LogInformation("Could not find any CSX files");
                return;
            }

            _scriptCsContext.Path = _env.Path;
            _logger.LogInformation($"Found {allCsxFiles.Length} CSX files.");

            //script name is added here as a fake one (dir path not even a real file); this is OK though -> it forces MEF initialization
            var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger()).
                                        LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptName(_env.Path).ScriptEngine <NullScriptEngine>();

            _scriptServices = scriptServicesBuilder.Build();

            var mscorlib          = MetadataReference.CreateFromAssembly(typeof(object).GetTypeInfo().Assembly);
            var systemCore        = MetadataReference.CreateFromAssembly(typeof(Enumerable).GetTypeInfo().Assembly);
            var scriptcsContracts = MetadataReference.CreateFromAssembly(typeof(IScriptHost).Assembly);

            var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Script);

            var scriptPacks   = _scriptServices.ScriptPackResolver.GetPacks().ToList();
            var assemblyPaths = _scriptServices.AssemblyResolver.GetAssemblyPaths(_env.Path);

            foreach (var csxPath in allCsxFiles)
            {
                try
                {
                    _scriptCsContext.CsxFiles.Add(csxPath);
                    var processResult = _scriptServices.FilePreProcessor.ProcessFile(csxPath);

                    var references = new List <MetadataReference> {
                        mscorlib, systemCore, scriptcsContracts
                    };
                    var usings = new List <string>(ScriptExecutor.DefaultNamespaces);

                    //default references
                    ImportReferences(references, ScriptExecutor.DefaultReferences);

                    //file usings
                    usings.AddRange(processResult.Namespaces);

                    //#r references
                    ImportReferences(references, processResult.References);

                    //nuget references
                    ImportReferences(references, assemblyPaths);

                    //script packs
                    if (scriptPacks != null && scriptPacks.Any())
                    {
                        var scriptPackSession = new ScriptPackSession(scriptPacks, new string[0]);
                        scriptPackSession.InitializePacks();

                        //script pack references
                        ImportReferences(references, scriptPackSession.References);

                        //script pack usings
                        usings.AddRange(scriptPackSession.Namespaces);

                        _scriptCsContext.ScriptPacks.UnionWith(scriptPackSession.Contexts.Select(pack => pack.GetType().ToString()));
                    }

                    _scriptCsContext.References.UnionWith(references.Select(x => x.Display));
                    _scriptCsContext.Usings.UnionWith(usings);

                    var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings.Distinct());

                    var fileName = Path.GetFileName(csxPath);

                    var projectId = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                    var project   = ProjectInfo.Create(projectId, VersionStamp.Create(), fileName, $"{fileName}.dll", LanguageNames.CSharp, null, null,
                                                       compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                    _workspace.AddProject(project);
                    AddFile(csxPath, projectId);

                    foreach (var filePath in processResult.LoadedScripts.Distinct().Except(new[] { csxPath }))
                    {
                        _scriptCsContext.CsxFiles.Add(filePath);
                        var loadedFileName = Path.GetFileName(filePath);

                        var loadedFileProjectId         = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                        var loadedFileSubmissionProject = ProjectInfo.Create(loadedFileProjectId, VersionStamp.Create(),
                                                                             $"{loadedFileName}-LoadedFrom-{fileName}", $"{loadedFileName}-LoadedFrom-{fileName}.dll", LanguageNames.CSharp, null, null,
                                                                             compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                        _workspace.AddProject(loadedFileSubmissionProject);
                        AddFile(filePath, loadedFileProjectId);
                        _workspace.AddProjectReference(projectId, new ProjectReference(loadedFileProjectId));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"{csxPath} will be ignored due to the following error:", ex);
                }
            }
        }
コード例 #8
0
ファイル: CompilerInvocation.cs プロジェクト: mpeyrotc/roslyn
        public static async Task <CompilerInvocation> CreateFromJsonAsync(string jsonContents)
        {
            var invocationInfo = JsonConvert.DeserializeObject <CompilerInvocationInfo>(jsonContents);

            Assumes.Present(invocationInfo);

            // We will use a Workspace to simplify the creation of the compilation, but will be careful not to return the Workspace instance from this class.
            // We will still provide the language services which are used by the generator itself, but we don't tie it to a Workspace object so we can
            // run this as an in-proc source generator if one day desired.
            var workspace = new AdhocWorkspace();

            var languageName     = GetLanguageName(invocationInfo);
            var languageServices = workspace.Services.GetLanguageServices(languageName);

            var mapPath = GetPathMapper(invocationInfo);

            var splitCommandLine = CommandLineParser.SplitCommandLineIntoArguments(invocationInfo.Arguments, removeHashComments: false).ToList();

            // Unfortunately for us there are a few paths that get directly read by the command line parse which we need to remap,
            // such as /ruleset files. So let's go through and process them now.
            for (var i = 0; i < splitCommandLine.Count; i++)
            {
                const string RuleSetSwitch = "/ruleset:";

                if (splitCommandLine[i].StartsWith(RuleSetSwitch, StringComparison.Ordinal))
                {
                    var rulesetPath = splitCommandLine[i].Substring(RuleSetSwitch.Length);

                    var quoted = rulesetPath.Length > 2 &&
                                 rulesetPath.StartsWith("\"", StringComparison.Ordinal) &&
                                 rulesetPath.EndsWith("\"", StringComparison.Ordinal);

                    if (quoted)
                    {
                        rulesetPath = rulesetPath.Substring(1, rulesetPath.Length - 2);
                    }

                    rulesetPath = mapPath(rulesetPath);

                    if (quoted)
                    {
                        rulesetPath = "\"" + rulesetPath + "\"";
                    }

                    splitCommandLine[i] = RuleSetSwitch + rulesetPath;
                }
            }

            var commandLineParserService = languageServices.GetRequiredService <ICommandLineParserService>();
            var parsedCommandLine        = commandLineParserService.Parse(splitCommandLine, Path.GetDirectoryName(invocationInfo.ProjectFilePath), isInteractive: false, sdkDirectory: null);

            var analyzerLoader = new DefaultAnalyzerAssemblyLoader();

            var projectId = ProjectId.CreateNewId(invocationInfo.ProjectFilePath);

            var projectInfo = ProjectInfo.Create(
                projectId,
                VersionStamp.Default,
                name: Path.GetFileNameWithoutExtension(invocationInfo.ProjectFilePath),
                assemblyName: parsedCommandLine.CompilationName !,
                language: languageName,
                filePath: invocationInfo.ProjectFilePath,
                outputFilePath: parsedCommandLine.OutputFileName,
                parsedCommandLine.CompilationOptions,
                parsedCommandLine.ParseOptions,
                parsedCommandLine.SourceFiles.Select(s => CreateDocumentInfo(unmappedPath: s.Path)),
                metadataReferences: parsedCommandLine.MetadataReferences.Select(r => MetadataReference.CreateFromFile(mapPath(r.Reference), r.Properties)),
                additionalDocuments: parsedCommandLine.AdditionalFiles.Select(f => CreateDocumentInfo(unmappedPath: f.Path)),
                analyzerReferences: parsedCommandLine.AnalyzerReferences.Select(r => new AnalyzerFileReference(r.FilePath, analyzerLoader)))
                              .WithAnalyzerConfigDocuments(parsedCommandLine.AnalyzerConfigPaths.Select(CreateDocumentInfo));

            workspace.AddProject(projectInfo);

            var compilation = await workspace.CurrentSolution.GetProject(projectId) !.GetRequiredCompilationAsync(CancellationToken.None);

            return(new CompilerInvocation(compilation, languageServices, invocationInfo.ProjectFilePath, workspace.CurrentSolution.Options));

            // Local methods:
            DocumentInfo CreateDocumentInfo(string unmappedPath)
            {
                var mappedPath = mapPath(unmappedPath);

                return(DocumentInfo.Create(
                           DocumentId.CreateNewId(projectId, mappedPath),
                           name: mappedPath,
                           filePath: mappedPath,
                           loader: new FileTextLoader(mappedPath, parsedCommandLine.Encoding)));
            }
        }
コード例 #9
0
        protected static void Analyze <T>(Func <string, SyntaxTree> parseTextFunc, Func <SyntaxTree[], Compilation> createCompilationFunc, string language, string input, string output = null, int issueToFix = -1, int actionToRun = 0, Action <int, Diagnostic> diagnosticCheck = null) where T : DiagnosticAnalyzer, new()
        {
            var text = new StringBuilder();

            var expectedDiagnosics = new List <TextSpan>();
            int start = -1;

            for (int i = 0; i < input.Length; i++)
            {
                char ch = input[i];
                if (ch == '$' && ((i > 0) && (input[i - 1] == '$')))
                {
                    // Ignore 2nd "$" in "$$"
                }
                else if (ch == '$' && (i + 1 >= input.Length || input[i + 1] != '$'))
                {
                    if (start < 0)
                    {
                        start = text.Length;
                        continue;
                    }
                    expectedDiagnosics.Add(TextSpan.FromBounds(start, text.Length));
                    start = -1;
                }
                else
                {
                    text.Append(ch);
                }
            }

            var syntaxTree = parseTextFunc(text.ToString());

            Compilation compilation = createCompilationFunc(new[] { syntaxTree });

            var diagnostics = new List <Diagnostic>();

            var compilationWithAnalyzers = compilation.WithAnalyzers(System.Collections.Immutable.ImmutableArray <DiagnosticAnalyzer> .Empty.Add(new T()));
            var result = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().GetAwaiter().GetResult();

            diagnostics.AddRange(result);

            diagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start.CompareTo(d2.Location.SourceSpan.Start));
            expectedDiagnosics.Sort((d1, d2) => d1.Start.CompareTo(d2.Start));

            if (expectedDiagnosics.Count != diagnostics.Count)
            {
                foreach (var diag in diagnostics)
                {
                    Console.WriteLine(diag.Id + "/" + diag.GetMessage() + "/" + diag.Location.SourceSpan);
                }
                Assert.True(false, "Diagnostic count mismatch expected: " + expectedDiagnosics.Count + " was " + diagnostics.Count);
            }

            for (int i = 0; i < expectedDiagnosics.Count; i++)
            {
                var d         = diagnostics[i];
                var wholeSpan = GetWholeSpan(d);
                if (wholeSpan != expectedDiagnosics[i])
                {
                    Assert.True(false, "Diagnostic " + i + " span mismatch expected: " + expectedDiagnosics[i] + " but was " + wholeSpan);
                }
                if (diagnosticCheck != null)
                {
                    diagnosticCheck(i, d);
                }
            }

            if (output == null)
            {
                return;
            }

            var workspace  = new TestWorkspace();
            var projectId  = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            workspace.Open(ProjectInfo.Create(
                               projectId,
                               VersionStamp.Create(),
                               "a", "a.exe", language, null, null, null, null,
                               new[] {
                DocumentInfo.Create(
                    documentId,
                    "a.cs",
                    null,
                    SourceCodeKind.Regular,
                    TextLoader.From(TextAndVersion.Create(SourceText.From(text.ToString()), VersionStamp.Create())))
            }
                               ));
            if (issueToFix < 0)
            {
                diagnostics.Reverse();
                foreach (var v in diagnostics)
                {
                    RunFix(workspace, projectId, documentId, v);
                }
            }
            else
            {
                RunFix(workspace, projectId, documentId, diagnostics.ElementAt(issueToFix), actionToRun);
            }

            var txt = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId).GetTextAsync().GetAwaiter().GetResult().ToString();

            output = Utils.HomogenizeEol(output);
            txt    = Utils.HomogenizeEol(txt);
            if (output != txt)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("expected:");
                sb.AppendLine(output);
                sb.AppendLine("got:");
                sb.AppendLine(txt);
                sb.AppendLine("-----Mismatch:");
                for (int i = 0; i < txt.Length; i++)
                {
                    if (i >= output.Length)
                    {
                        sb.Append("#");
                        continue;
                    }
                    if (txt[i] != output[i])
                    {
                        sb.Append("#");
                        continue;
                    }
                    sb.Append(txt[i]);
                }
                Assert.True(false, sb.ToString());
            }
        }
コード例 #10
0
        public VisualStudioProject CreateAndAddToWorkspace(string projectSystemName, string language, VisualStudioProjectCreationInfo creationInfo)
        {
            // HACK: Fetch this service to ensure it's still created on the UI thread; once this is moved off we'll need to fix up it's constructor to be free-threaded.
            _visualStudioWorkspaceImpl.Services.GetRequiredService <VisualStudioMetadataReferenceManager>();

            var id = ProjectId.CreateNewId(projectSystemName);
            var directoryNameOpt = creationInfo.FilePath != null?Path.GetDirectoryName(creationInfo.FilePath) : null;

            // We will use the project system name as the default display name of the project
            var project = new VisualStudioProject(_visualStudioWorkspaceImpl, _dynamicFileInfoProviders, _hostDiagnosticUpdateSource, id, displayName: projectSystemName, language, directoryNameOpt);

            var versionStamp = creationInfo.FilePath != null?VersionStamp.Create(File.GetLastWriteTimeUtc(creationInfo.FilePath))
                                   : VersionStamp.Create();

            var assemblyName = creationInfo.AssemblyName ?? projectSystemName;

            _visualStudioWorkspaceImpl.AddProjectToInternalMaps(project, creationInfo.Hierarchy, creationInfo.ProjectGuid, projectSystemName);

            _visualStudioWorkspaceImpl.ApplyChangeToWorkspace(w =>
            {
                var projectInfo = ProjectInfo.Create(
                    id,
                    versionStamp,
                    name: projectSystemName,
                    assemblyName: assemblyName,
                    language: language,
                    filePath: creationInfo.FilePath,
                    compilationOptions: creationInfo.CompilationOptions,
                    parseOptions: creationInfo.ParseOptions);

                // HACK: update this since we're still on the UI thread. Note we can only update this if we don't have projects -- the workspace
                // only lets us really do this with OnSolutionAdded for now.
                string solutionPathToSetWithOnSolutionAdded = null;
                var solution = (IVsSolution)Shell.ServiceProvider.GlobalProvider.GetService(typeof(SVsSolution));
                if (solution != null && ErrorHandler.Succeeded(solution.GetSolutionInfo(out _, out var solutionFilePath, out _)))
                {
                    if (w.CurrentSolution.FilePath != solutionFilePath && w.CurrentSolution.ProjectIds.Count == 0)
                    {
                        solutionPathToSetWithOnSolutionAdded = solutionFilePath;
                    }
                }

                if (solutionPathToSetWithOnSolutionAdded != null)
                {
                    w.OnSolutionAdded(
                        SolutionInfo.Create(
                            SolutionId.CreateNewId(solutionPathToSetWithOnSolutionAdded),
                            VersionStamp.Create(),
                            solutionPathToSetWithOnSolutionAdded,
                            projects: new[] { projectInfo }));

                    // set working folder for the persistent service
                    var persistenceService = w.Services.GetRequiredService <IPersistentStorageLocationService>() as VisualStudioPersistentStorageLocationService;
                    persistenceService?.UpdateForVisualStudioWorkspace(w);
                }
                else
                {
                    w.OnProjectAdded(projectInfo);
                }
            });

            // We do all these sets after the w.OnProjectAdded, as the setting of these properties is going to try to modify the workspace
            // again. Those modifications will all implicitly do nothing, since the workspace already has the values from above.
            // We could pass these all through the constructor (but that gets verbose), or have some other control to ignore these,
            // but that seems like overkill.
            project.AssemblyName       = assemblyName;
            project.CompilationOptions = creationInfo.CompilationOptions;
            project.FilePath           = creationInfo.FilePath;
            project.ParseOptions       = creationInfo.ParseOptions;

            return(project);
        }
コード例 #11
0
        public async Task <bool> Execute(CancellationToken cancellationToken)
        {
            var stopwatch   = Stopwatch.StartNew();
            var projectName = Path.GetFileNameWithoutExtension(ProjectPath);
            var projectId   = !string.IsNullOrEmpty(ProjectGuid) && Guid.TryParse(ProjectGuid, out var projectIdGuid)
                ? ProjectId.CreateFromSerialized(projectIdGuid)
                : ProjectId.CreateNewId();

            this.Log.LogDebug($"AssemblyName: {this.AssemblyName}");
            if (!string.IsNullOrWhiteSpace(this.ProjectGuid))
            {
                this.Log.LogDebug($"ProjectGuid: {this.ProjectGuid}");
            }
            this.Log.LogDebug($"ProjectID: {projectId}");
            this.Log.LogDebug($"ProjectName: {projectName}");
            this.Log.LogDebug($"CodeGenOutputFile: {this.CodeGenOutputFile}");
            this.Log.LogDebug($"ProjectPath: {this.ProjectPath}");
            this.Log.LogDebug($"OutputType: {this.OutputType}");
            this.Log.LogDebug($"TargetPath: {this.TargetPath}");
            this.Log.LogDebug($"DefineConstants ({this.DefineConstants.Count}): {string.Join(", ", this.DefineConstants)}");
            this.Log.LogDebug($"Sources ({this.Compile.Count}): {string.Join(", ", this.Compile)}");
            this.Log.LogDebug($"References ({this.Reference.Count}): {string.Join(", ", this.Reference)}");

            var languageName = GetLanguageName(ProjectPath);

            var projectInfo = ProjectInfo.Create(
                projectId,
                VersionStamp.Default,
                projectName,
                AssemblyName,
                languageName,
                ProjectPath,
                TargetPath,
                CreateCompilationOptions(this),
                documents: GetDocuments(Compile, projectId),
                metadataReferences: GetMetadataReferences(Reference),
                parseOptions: new CSharpParseOptions(preprocessorSymbols: this.DefineConstants)
                );

            var workspace = new AdhocWorkspace();

            workspace.AddProject(projectInfo);

            var project = workspace.CurrentSolution.Projects.Single();

            this.Log.LogDebug($"Workspace creation completed in {stopwatch.ElapsedMilliseconds}ms.");
            stopwatch.Restart();

            var compilation = await project.GetCompilationAsync(cancellationToken);

            this.Log.LogDebug($"GetCompilation completed in {stopwatch.ElapsedMilliseconds}ms.");
            stopwatch.Restart();

            if (compilation.ReferencedAssemblyNames.All(name => name.Name != AbstractionsAssemblyShortName))
            {
                this.Log.LogWarning($"Assembly {compilation.AssemblyName} does not reference {AbstractionsAssemblyShortName} (references: {string.Join(", ", compilation.ReferencedAssemblyNames)})");
                return(false);
            }

            var generator = new CodeGenerator(compilation, this.Log);
            var syntax    = generator.GenerateCode(cancellationToken);

            this.Log.LogDebug($"GenerateCode completed in {stopwatch.ElapsedMilliseconds}ms.");
            stopwatch.Restart();

            var normalized = syntax.NormalizeWhitespace();

            this.Log.LogDebug($"NormalizeWhitespace completed in {stopwatch.ElapsedMilliseconds}ms.");
            stopwatch.Restart();

            var sourceBuilder = new StringBuilder();

            sourceBuilder.AppendLine("// <auto-generated />");
            sourceBuilder.AppendLine("#if !EXCLUDE_GENERATED_CODE");
            foreach (var warningNum in SuppressCompilerWarnings)
            {
                sourceBuilder.AppendLine($"#pragma warning disable {warningNum}");
            }
            sourceBuilder.AppendLine(normalized.ToFullString());
            foreach (var warningNum in SuppressCompilerWarnings)
            {
                sourceBuilder.AppendLine($"#pragma warning restore {warningNum}");
            }
            sourceBuilder.AppendLine("#endif");
            var source = sourceBuilder.ToString();

            this.Log.LogDebug($"Generate source from syntax completed in {stopwatch.ElapsedMilliseconds}ms.");
            stopwatch.Restart();

            if (File.Exists(this.CodeGenOutputFile))
            {
                using (var reader = new StreamReader(this.CodeGenOutputFile))
                {
                    var existing = await reader.ReadToEndAsync();

                    if (string.Equals(source, existing, StringComparison.Ordinal))
                    {
                        this.Log.LogDebug("Generated code matches existing code.");
                        return(true);
                    }
                }
            }

            using (var sourceWriter = new StreamWriter(this.CodeGenOutputFile))
            {
                await sourceWriter.WriteAsync(source);
            }

            this.Log.LogDebug($"Write source to disk completed in {stopwatch.ElapsedMilliseconds}ms.");

            return(true);
        }
コード例 #12
0
        static List <CodeAction> GetActions(CodeRefactoringProvider action, string input, out DiagnosticTestBase.TestWorkspace workspace, out Document doc, CSharpParseOptions parseOptions = null)
        {
            TextSpan selectedSpan;
            TextSpan markedSpan;
            string   text = ParseText(input, out selectedSpan, out markedSpan);

            workspace = new DiagnosticTestBase.TestWorkspace();
            var projectId  = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            if (parseOptions == null)
            {
                parseOptions = new CSharpParseOptions(
                    LanguageVersion.CSharp6,
                    DocumentationMode.Diagnose | DocumentationMode.Parse,
                    SourceCodeKind.Regular,
                    ImmutableArray.Create("DEBUG", "TEST")
                    );
            }
            workspace.Options = workspace.Options
                                .WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, true)
                                .WithChangedOption(new OptionKey(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.CSharp), true)
                                .WithChangedOption(new OptionKey(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.CSharp), true);
            workspace.Open(ProjectInfo.Create(
                               projectId,
                               VersionStamp.Create(),
                               "TestProject",
                               "TestProject",
                               LanguageNames.CSharp,
                               null,
                               null,
                               new CSharpCompilationOptions(
                                   OutputKind.DynamicallyLinkedLibrary,
                                   false,
                                   "",
                                   "",
                                   "Script",
                                   null,
                                   OptimizationLevel.Debug,
                                   false,
                                   true
                                   ),
                               parseOptions,
                               new[] {
                DocumentInfo.Create(
                    documentId,
                    "a.cs",
                    null,
                    SourceCodeKind.Regular,
                    TextLoader.From(TextAndVersion.Create(SourceText.From(text), VersionStamp.Create()))
                    )
            },
                               null,
                               DiagnosticTestBase.DefaultMetadataReferences
                               )
                           );
            doc = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId);
            var actions = new List <CodeAction>();
            var context = new CodeRefactoringContext(doc, selectedSpan, actions.Add, default(CancellationToken));

            action.ComputeRefactoringsAsync(context).GetAwaiter().GetResult();
            if (markedSpan.Start > 0)
            {
                foreach (var nra in actions.OfType <NRefactoryCodeAction>())
                {
                    Assert.True(markedSpan == nra.TextSpan, "Activation span does not match.");
                }
            }
            return(actions);
        }
コード例 #13
0
ファイル: CodeGeneratorCommand.cs プロジェクト: totr/orleans
        public async Task <bool> Execute(CancellationToken cancellationToken)
        {
            var stopwatch   = Stopwatch.StartNew();
            var projectName = Path.GetFileNameWithoutExtension(ProjectPath);
            var projectId   = !string.IsNullOrEmpty(ProjectGuid) && Guid.TryParse(ProjectGuid, out var projectIdGuid)
                ? ProjectId.CreateFromSerialized(projectIdGuid)
                : ProjectId.CreateNewId();

            var languageName = GetLanguageName(ProjectPath);

            var projectInfo = ProjectInfo.Create(
                projectId,
                VersionStamp.Default,
                projectName,
                AssemblyName,
                languageName,
                ProjectPath,
                TargetPath,
                CreateCompilationOptions(this),
                documents: GetDocuments(Compile, projectId),
                metadataReferences: GetMetadataReferences(Reference),
                parseOptions: new CSharpParseOptions(preprocessorSymbols: this.DefineConstants)
                );

            var workspace = new AdhocWorkspace();

            workspace.AddProject(projectInfo);

            var project = workspace.CurrentSolution.Projects.Single();

            stopwatch.Restart();

            var compilation = await project.GetCompilationAsync(cancellationToken);

            stopwatch.Restart();

            if (!compilation.SyntaxTrees.Any())
            {
                Console.WriteLine($"Skipping empty project, {compilation.AssemblyName}.");
                return(true);
            }

            if (compilation.ReferencedAssemblyNames.All(name => name.Name != AbstractionsAssemblyShortName))
            {
                Console.WriteLine($"Project {compilation.AssemblyName} does not reference {AbstractionsAssemblyShortName} (references: {string.Join(", ", compilation.ReferencedAssemblyNames)})");
                return(false);
            }

            var options = new CodeGeneratorOptions
            {
                DebuggerStepThrough = this.DebuggerStepThrough
            };
            var generator = new CodeGenerator(new CodeGeneratorExecutionContext {
                Compilation = compilation
            }, options);
            var syntax = generator.GenerateCode(cancellationToken);

            stopwatch.Restart();

            var normalized = syntax.NormalizeWhitespace();

            stopwatch.Restart();

            var sourceBuilder = new StringBuilder();

            sourceBuilder.AppendLine("// <auto-generated />");
            sourceBuilder.AppendLine("#if !EXCLUDE_GENERATED_CODE");
            foreach (var warningNum in SuppressCompilerWarnings)
            {
                sourceBuilder.AppendLine($"#pragma warning disable {warningNum}");
            }
            sourceBuilder.AppendLine(normalized.ToFullString());
            foreach (var warningNum in SuppressCompilerWarnings)
            {
                sourceBuilder.AppendLine($"#pragma warning restore {warningNum}");
            }
            sourceBuilder.AppendLine("#endif");
            var source = sourceBuilder.ToString();

            stopwatch.Restart();

            if (File.Exists(this.CodeGenOutputFile))
            {
                using (var reader = new StreamReader(this.CodeGenOutputFile))
                {
                    var existing = await reader.ReadToEndAsync();

                    if (string.Equals(source, existing, StringComparison.Ordinal))
                    {
                        return(true);
                    }
                }
            }

            using (var sourceWriter = new StreamWriter(this.CodeGenOutputFile))
            {
                await sourceWriter.WriteAsync(source);
            }

            return(true);
        }
コード例 #14
0
        public async Task TestUpdatedDocumentHasTextVersionAsync()
        {
            var pid      = ProjectId.CreateNewId();
            var text     = SourceText.From("public class C { }");
            var version  = VersionStamp.Create();
            var docInfo  = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
            var projInfo = ProjectInfo.Create(
                pid,
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp,
                documents: new[] { docInfo });

            using var ws = new AdhocWorkspace();
            ws.AddProject(projInfo);
            var doc = ws.CurrentSolution.GetDocument(docInfo.Id);

            Assert.False(doc.TryGetText(out var currentText));
            Assert.False(doc.TryGetTextVersion(out var currentVersion));

            // cause text to load and show that TryGet now works for text and version
            currentText = await doc.GetTextAsync();

            Assert.True(doc.TryGetText(out currentText));
            Assert.True(doc.TryGetTextVersion(out currentVersion));
            Assert.Equal(version, currentVersion);

            // change document
            var root = await doc.GetSyntaxRootAsync();

            var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation());

            Assert.NotSame(root, newRoot);
            var newDoc = doc.WithSyntaxRoot(newRoot);

            Assert.NotSame(doc, newDoc);

            // text is now unavailable since it must be constructed from tree
            Assert.False(newDoc.TryGetText(out currentText));

            // version is available because it is cached
            Assert.True(newDoc.TryGetTextVersion(out currentVersion));

            // access it the hard way
            var actualVersion = await newDoc.GetTextVersionAsync();

            // version is the same
            Assert.Equal(currentVersion, actualVersion);

            // accessing text version did not cause text to be constructed.
            Assert.False(newDoc.TryGetText(out currentText));

            // now access text directly (force it to be constructed)
            var actualText = await newDoc.GetTextAsync();

            actualVersion = await newDoc.GetTextVersionAsync();

            // prove constructing text did not introduce a new version
            Assert.Equal(currentVersion, actualVersion);
        }
        public ProjectBuildChangeTriggerTest()
        {
            SomeProject      = new HostProject("c:\\SomeProject\\SomeProject.csproj", FallbackRazorConfiguration.MVC_1_0, "SomeProject");
            SomeOtherProject = new HostProject("c:\\SomeOtherProject\\SomeOtherProject.csproj", FallbackRazorConfiguration.MVC_2_0, "SomeOtherProject");

            Workspace = TestWorkspace.Create(w => SomeWorkspaceProject = w.AddProject(ProjectInfo.Create(
                                                                                          ProjectId.CreateNewId(),
                                                                                          VersionStamp.Create(),
                                                                                          "SomeProject",
                                                                                          "SomeProject",
                                                                                          LanguageNames.CSharp,
                                                                                          filePath: SomeProject.FilePath)));
        }
コード例 #16
0
        public async Task TestDoNotAddDuplicateImportIfNamespaceIsDefinedInSourceAndExternalAssembly()
        {
            var externalCode =
                @"namespace N.M { public class A : System.Attribute { } }";

            var code =
                @"using System;
using N.M;

class C
{
    public void M1(String p1) { }

    public void M2([A] String p2) { }
}";

            var otherAssemblyReference = GetInMemoryAssemblyReferenceForCode(externalCode);

            var ws           = new AdhocWorkspace();
            var emptyProject = ws.AddProject(
                ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Default,
                    "test",
                    "test.dll",
                    LanguageNames.CSharp,
                    metadataReferences: new[] { TestReferences.NetFx.v4_0_30319.mscorlib }));

            var project = emptyProject
                          .AddMetadataReferences(new[] { otherAssemblyReference })
                          .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            project = project.AddDocument("duplicate.cs", externalCode).Project;
            var document = project.AddDocument("test.cs", code);

            var options = document.Project.Solution.Workspace.Options;

            var compilation = await document.Project.GetCompilationAsync(CancellationToken.None);

            ImmutableArray <Diagnostic> compilerDiagnostics = compilation.GetDiagnostics(CancellationToken.None);

            Assert.Empty(compilerDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error));

            var attribute = compilation.GetTypeByMetadataName("N.M.A");

            var syntaxRoot = await document.GetSyntaxRootAsync(CancellationToken.None).ConfigureAwait(false);

            SyntaxNode p1SyntaxNode = syntaxRoot.DescendantNodes().OfType <ParameterSyntax>().FirstOrDefault();

            // Add N.M.A attribute to p1.
            var editor = await DocumentEditor.CreateAsync(document, CancellationToken.None).ConfigureAwait(false);

            SyntaxNode attributeSyntax = editor.Generator.Attribute(editor.Generator.TypeExpression(attribute));

            editor.AddAttribute(p1SyntaxNode, attributeSyntax);
            Document documentWithAttribute = editor.GetChangedDocument();

            // Add namespace import.
            Document imported = await ImportAdder.AddImportsAsync(documentWithAttribute, null,
                                                                  CancellationToken.None).ConfigureAwait(false);

            var formatted = await Formatter.FormatAsync(imported, options);

            var actualText = (await formatted.GetTextAsync()).ToString();

            Assert.Equal(actualText,
                         @"using System;
using N.M;

class C
{
    public void M1([global::N.M.A] String p1) { }

    public void M2([A] String p2) { }
}");
        }
コード例 #17
0
        private static ObjectReference <object> PutObjectInImplicitCache(ProjectCacheService cacheService)
        {
            var reference = ObjectReference.CreateFromFactory(() => new object());

            reference.UseReference(r => cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, r));

            return(reference);
        }
コード例 #18
0
ファイル: MSBuildHost.cs プロジェクト: nopara73/AvalonStudio
        public async Task <(ProjectInfo info, List <string> projectReferences, string targetPath)> LoadProject(string solutionDirectory, string projectFile)
        {
            lock (outputLines)
            {
                outputLines.Clear();
                errorLines.Clear();
            }

            return(await Task.Run(() =>
            {
                var project = XDocument.Load(projectFile);

                var projectReferences = project.Descendants("ProjectReference").Select(e => e.Attribute("Include").Value).ToList();

                var frameworks = GetTargetFrameworks(project);

                var targetFramework = frameworks.FirstOrDefault();

                if (targetFramework != null)
                {
                    Console.WriteLine($"Automatically selecting {targetFramework} as TargetFramework");
                }
                else
                {
                    //throw new Exception("Must specify target framework to load project.");
                    Console.WriteLine($"Non-Dotnet core project trying anyway.");
                    targetFramework = "";
                }

                ProjectInfoResponse loadData = null;

                try
                {
                    loadData = SendRequest(new ProjectInfoRequest {
                        SolutionDirectory = solutionDirectory, FullPath = projectFile, TargetFramework = targetFramework
                    });
                }
                catch (Exception)
                {
                    return (null, null, null);
                }

                requestComplete.WaitOne();

                if (loadData.CscCommandLine != null && loadData.CscCommandLine.Count > 0)
                {
                    var projectOptions = ParseArguments(loadData.CscCommandLine.Skip(1));

                    var projectInfo = ProjectInfo.Create(
                        ProjectId.CreateNewId(),
                        VersionStamp.Create(),
                        name: Path.GetFileNameWithoutExtension(projectFile),
                        assemblyName: Path.GetFileNameWithoutExtension(projectOptions.outputFile),
                        language: LanguageNames.CSharp,
                        filePath: projectFile,
                        outputFilePath: projectOptions.outputFile,
                        compilationOptions: projectOptions.compilationOptions,
                        parseOptions: projectOptions.parseOptions,
                        metadataReferences: loadData.MetaDataReferences.Select(ar => MetadataReference.CreateFromFile(ar, documentation: IoC.Get <AvalonStudio.Projects.OmniSharp.Roslyn.DocumentationProvider>()?.GetDocumentationProvider(ar))));

                    return (projectInfo, projectReferences, loadData.TargetPath);
                }
                else
                {
                    IoC.Get <IConsole>($"Project may have failed to load correctly: {Path.GetFileNameWithoutExtension(projectFile)}");

                    var projectInfo = ProjectInfo.Create(
                        ProjectId.CreateNewId(),
                        VersionStamp.Create(),
                        Path.GetFileNameWithoutExtension(projectFile), Path.GetFileNameWithoutExtension(projectFile),
                        LanguageNames.CSharp,
                        projectFile);

                    return (projectInfo, projectReferences, loadData?.TargetPath);
                }
            }));
        }
コード例 #19
0
        public async Task <Dictionary <string, AssemblyInfo> > Execute([CallerFilePath] string sourceFile = null)
        {
            if (sourceFile == null)
            {
                throw new ArgumentNullException(nameof(sourceFile));
            }

            var builtAssemblies = new Dictionary <string, AssemblyInfo>();

            IEnumerable <AssemblyInfo> GetAssemblies()
            {
                var assemblyRegex    = new Regex(@"<\s*assembly(:\s*(?<Name>\w+))?\s*/?>");
                var endAssemblyRegex = new Regex(@"</\s*assembly\s*>");
                var typeRegex        = new Regex(@"<\s*type:\s*(?<Name>\w+)\s*/>");
                var referenceRegex   = new Regex(@"<\s*ref:\s*(?<Name>[\w_\.]+)\s*/>");
                var weaverRegex      = new Regex(@"<\s*weaver:\s*(?<Name>[\w_\.]+)\s*/>");

                using (var sr = new StreamReader(sourceFile))
                {
                    AssemblyInfo currentAssembly = null;
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        if (line == null)
                        {
                            continue;
                        }
                        string trimmed = line.Trim();
                        if (trimmed.StartsWith("//") || trimmed.StartsWith("/*"))
                        {
                            // ReSharper disable TooWideLocalVariableScope
                            Match assemblyStartMatch, typeMatch, referenceMatch, weaverMatch;
                            // ReSharper restore TooWideLocalVariableScope
                            if ((assemblyStartMatch = assemblyRegex.Match(trimmed)).Success)
                            {
                                if (currentAssembly != null)
                                {
                                    yield return(currentAssembly);
                                }
                                currentAssembly = new AssemblyInfo(assemblyStartMatch.Groups["Name"]?.Value);
                            }
                            else if (currentAssembly != null)
                            {
                                if (endAssemblyRegex.IsMatch(trimmed))
                                {
                                    yield return(currentAssembly);

                                    currentAssembly = null;
                                }
                                else if ((typeMatch = typeRegex.Match(trimmed)).Success)
                                {
                                    if (Enum.TryParse(typeMatch.Groups["Name"].Value, true, out OutputKind output))
                                    {
                                        currentAssembly.OutputKind = output;
                                    }
                                }
                                else if ((referenceMatch = referenceRegex.Match(trimmed)).Success)
                                {
                                    MetadataReference GetReference(string name)
                                    {
                                        if (builtAssemblies.TryGetValue(name, out AssemblyInfo builtAssembly))
                                        {
                                            return(MetadataReference.CreateFromFile(builtAssembly.Assembly.Location));
                                        }
                                        string filePath = $@".\{name}.dll";

                                        if (File.Exists(filePath))
                                        {
                                            return(MetadataReference.CreateFromFile(filePath));
                                        }
                                        //Assembly loadedAssembly = Assembly.Load(new AssemblyName(name));
                                        //if (loadedAssembly != null)
                                        //{
                                        //    return MetadataReference.CreateFromFile(loadedAssembly.Location);
                                        //}
                                        return(null);
                                    }

                                    MetadataReference reference = GetReference(referenceMatch.Groups["Name"].Value);
                                    if (reference != null)
                                    {
                                        currentAssembly.AddReference(reference);
                                    }
                                    //TODO: Else
                                }
                                else if ((weaverMatch = weaverRegex.Match(trimmed)).Success)
                                {
                                    Weaver weaver = Weaver.FindWeaver(weaverMatch.Groups["Name"].Value);
                                    if (weaver != null)
                                    {
                                        WeaverAdded?.Invoke(this, new WeaverAddedEventArgs(weaver));
                                        currentAssembly.AddWeaver(weaver);
                                    }
                                    //TODO: Else
                                }
                            }
                        }
                        currentAssembly?.AppendLine(line);
                    }
                    if (currentAssembly != null)
                    {
                        yield return(currentAssembly);
                    }
                }
            }

            var workspace = new AdhocWorkspace();

            foreach (AssemblyInfo assemblyInfo in GetAssemblies())
            {
                string assemblyName = $"AssemblyToTest{_instanceCount++}";

                var projectId = ProjectId.CreateNewId();

                var document = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "Generated.cs",
                                                   loader: TextLoader.From(TextAndVersion.Create(SourceText.From(assemblyInfo.GetContents()),
                                                                                                 VersionStamp.Create())));

                var project = workspace.AddProject(ProjectInfo.Create(projectId,
                                                                      VersionStamp.Create(), assemblyName, assemblyName, LanguageNames.CSharp,
                                                                      compilationOptions: new CSharpCompilationOptions(assemblyInfo.OutputKind),
                                                                      documents: new[] { document }, metadataReferences: assemblyInfo.References,
                                                                      filePath: Path.GetFullPath(
                                                                          $"{Path.GetFileNameWithoutExtension(Path.GetRandomFileName())}.csproj")));

                Compilation compile = await project.GetCompilationAsync();

                string filePath = Path.GetFullPath($"{assemblyName}.dll");
                using (var file = File.Create(filePath))
                {
                    var emitResult = compile.Emit(file);
                    if (emitResult.Success)
                    {
                        foreach (Weaver weaver in assemblyInfo.Weavers)
                        {
                            file.Position = 0;
                            weaver.ApplyToAssembly(file);
                        }
                    }
                    else
                    {
                        throw new Exception(string.Join(Environment.NewLine,
                                                        emitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error)
                                                        .Select(d => d.GetMessage())));
                    }
                }
                assemblyInfo.Assembly = Assembly.LoadFile(filePath);
                builtAssemblies.Add(assemblyInfo.Name ?? assemblyName, assemblyInfo);
            }
            return(builtAssemblies);
        }
コード例 #20
0
        private static Solution AddProject(Solution solution, string projectName)
        {
            var projectId = ProjectId.CreateNewId(debugName: projectName);

            return(solution.AddProject(ProjectInfo.Create(projectId, VersionStamp.Create(), projectName, projectName, LanguageNames.CSharp, projectName)));
        }
コード例 #21
0
        protected static void AnalyzeWithRule <T>(string input, string ruleId, string output = null, int issueToFix = -1, int actionToRun = 0, Action <int, Diagnostic> diagnosticCheck = null) where T : DiagnosticAnalyzer, new()
        {
            var text = new StringBuilder();

            var expectedDiagnosics = new List <TextSpan> ();
            int start = -1;

            for (int i = 0; i < input.Length; i++)
            {
                char ch = input [i];
                if (ch == '$')
                {
                    if (start < 0)
                    {
                        start = text.Length;
                        continue;
                    }
                    expectedDiagnosics.Add(TextSpan.FromBounds(start, text.Length));
                    start = -1;
                }
                else
                {
                    text.Append(ch);
                }
            }

            var syntaxTree = CSharpSyntaxTree.ParseText(text.ToString());

            Compilation compilation = CreateCompilationWithMscorlib(new [] { syntaxTree });

            var diagnostics = new List <Diagnostic>();
            var compilationWithAnalyzers = compilation.WithAnalyzers(System.Collections.Immutable.ImmutableArray <DiagnosticAnalyzer> .Empty.Add(new T()));

            diagnostics.AddRange(compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result);


            if (expectedDiagnosics.Count != diagnostics.Count)
            {
                Console.WriteLine("Diagnostics: " + diagnostics.Count);
                foreach (var diag in diagnostics)
                {
                    Console.WriteLine(diag.Id + "/" + diag.GetMessage());
                }
                Assert.Fail("Diagnostic count mismatch expected: " + expectedDiagnosics.Count + " but was:" + diagnostics.Count);
            }

            for (int i = 0; i < expectedDiagnosics.Count; i++)
            {
                var d         = diagnostics [i];
                var wholeSpan = GetWholeSpan(d);
                if (wholeSpan != expectedDiagnosics [i])
                {
                    Assert.Fail("Diagnostic " + i + " span mismatch expected: " + expectedDiagnosics[i] + " but was " + wholeSpan);
                }
                if (diagnosticCheck != null)
                {
                    diagnosticCheck(i, d);
                }
            }

            if (output == null)
            {
                return;
            }

            var workspace  = new TestWorkspace();
            var projectId  = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            workspace.Open(ProjectInfo.Create(
                               projectId,
                               VersionStamp.Create(),
                               "", "", LanguageNames.CSharp, null, null, null, null,
                               new [] {
                DocumentInfo.Create(
                    documentId,
                    "a.cs",
                    null,
                    SourceCodeKind.Regular,
                    TextLoader.From(TextAndVersion.Create(SourceText.From(text.ToString()), VersionStamp.Create())))
            }
                               ));
            if (issueToFix < 0)
            {
                diagnostics.Reverse();
                foreach (var v in diagnostics)
                {
                    RunFix(workspace, projectId, documentId, v);
                }
            }
            else
            {
                RunFix(workspace, projectId, documentId, diagnostics.ElementAt(issueToFix), actionToRun);
            }

            var txt = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId).GetTextAsync().Result.ToString();

            if (output != txt)
            {
                Console.WriteLine("expected:");
                Console.WriteLine(output);
                Console.WriteLine("got:");
                Console.WriteLine(txt);
                Assert.Fail();
            }
        }
コード例 #22
0
        public async Task <VisualStudioProject> CreateAndAddToWorkspaceAsync(
            string projectSystemName, string language, VisualStudioProjectCreationInfo creationInfo, CancellationToken cancellationToken)
        {
            // HACK: Fetch this service to ensure it's still created on the UI thread; once this is
            // moved off we'll need to fix up it's constructor to be free-threaded.

            await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            _visualStudioWorkspaceImpl.Services.GetRequiredService <VisualStudioMetadataReferenceManager>();

            _visualStudioWorkspaceImpl.SubscribeExternalErrorDiagnosticUpdateSourceToSolutionBuildEvents();

            // Since we're on the UI thread here anyways, use that as an opportunity to grab the
            // IVsSolution object and solution file path.
            //
            // ConfigureAwait(true) as we have to come back to the UI thread to do the cast to IVsSolution2.
            var solution = (IVsSolution2?)await _serviceProvider.GetServiceAsync(typeof(SVsSolution)).ConfigureAwait(true);

            var solutionFilePath = solution != null && ErrorHandler.Succeeded(solution.GetSolutionInfo(out _, out var filePath, out _))
                ? filePath
                : null;

            await _visualStudioWorkspaceImpl.EnsureDocumentOptionProvidersInitializedAsync(cancellationToken).ConfigureAwait(true);

            // From this point on, we start mutating the solution.  So make us non cancellable.
            cancellationToken = CancellationToken.None;

            var id           = ProjectId.CreateNewId(projectSystemName);
            var assemblyName = creationInfo.AssemblyName ?? projectSystemName;

            // We will use the project system name as the default display name of the project
            var project = new VisualStudioProject(
                _visualStudioWorkspaceImpl,
                _dynamicFileInfoProviders,
                _hostDiagnosticUpdateSource,
                id,
                displayName: projectSystemName,
                language,
                assemblyName: assemblyName,
                compilationOptions: creationInfo.CompilationOptions,
                filePath: creationInfo.FilePath,
                parseOptions: creationInfo.ParseOptions);

            var versionStamp = creationInfo.FilePath != null?VersionStamp.Create(File.GetLastWriteTimeUtc(creationInfo.FilePath))
                                   : VersionStamp.Create();

            await _visualStudioWorkspaceImpl.ApplyChangeToWorkspaceAsync(w =>
            {
                _visualStudioWorkspaceImpl.AddProjectToInternalMaps_NoLock(project, creationInfo.Hierarchy, creationInfo.ProjectGuid, projectSystemName);

                var projectInfo = ProjectInfo.Create(
                    id,
                    versionStamp,
                    name: projectSystemName,
                    assemblyName: assemblyName,
                    language: language,
                    filePath: creationInfo.FilePath,
                    compilationOptions: creationInfo.CompilationOptions,
                    parseOptions: creationInfo.ParseOptions)
                                  .WithTelemetryId(creationInfo.ProjectGuid);

                // If we don't have any projects and this is our first project being added, then we'll create a new SolutionId
                if (w.CurrentSolution.ProjectIds.Count == 0)
                {
                    var solutionSessionId = GetSolutionSessionId();

                    w.OnSolutionAdded(
                        SolutionInfo.Create(
                            SolutionId.CreateNewId(solutionFilePath),
                            VersionStamp.Create(),
                            solutionFilePath,
                            projects: new[] { projectInfo },
                            analyzerReferences: w.CurrentSolution.AnalyzerReferences)
                        .WithTelemetryId(solutionSessionId));
                }
                else
                {
                    w.OnProjectAdded(projectInfo);
                }
            }).ConfigureAwait(false);

            // Ensure that other VS contexts get accurate information that the UIContext for this language is now active.
            // This is not cancellable as we have already mutated the solution.
            await _visualStudioWorkspaceImpl.RefreshProjectExistsUIContextForLanguageAsync(language, CancellationToken.None).ConfigureAwait(false);

            return(project);
コード例 #23
0
ファイル: GeneralWorkspaceTests.cs プロジェクト: znatz/roslyn
            public Project AddProject(string name, string language)
            {
                var info = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), name, name, language);

                return(this.AddProject(info));
            }
コード例 #24
0
        public async Task 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
            ");

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

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

            var prj = sln.GetProject(prj1Id).WithCompilationOptions(new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication, embedVbCoreRuntime: true));

            tree = await prj.GetDocument(docId).GetSyntaxTreeAsync();

            var comp = await prj.GetCompilationAsync();

            var 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 = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

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

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());
        }
コード例 #25
0
 public void TestProjectId()
 {
     VerifyJsonSerialization(ProjectId.CreateNewId("project"));
 }
コード例 #26
0
        public async Task 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()
        {
        }
    }
                ");

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

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

            var prj = sln.GetProject(prj1Id).WithCompilationOptions(new CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication));

            tree = await prj.GetDocument(docId).GetSyntaxTreeAsync();

            var comp = await prj.GetCompilationAsync();

            var semanticModel = comp.GetSemanticModel(tree);

            var        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 = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

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

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(2, references.ElementAt(0).Locations.Count());
        }
コード例 #27
0
        public void Initalize()
        {
            var solutionFilePath = _env.SolutionFilePath;

            if (string.IsNullOrEmpty(solutionFilePath))
            {
                var solutions = Directory.GetFiles(_env.Path, "*.sln");
                var result    = SolutionPicker.ChooseSolution(_env.Path, solutions);

                if (result.Message != null)
                {
                    _logger.WriteInformation(result.Message);
                }

                if (result.Solution == null)
                {
                    return;
                }

                solutionFilePath = result.Solution;
            }

            SolutionFile solutionFile = null;

            _context.SolutionPath = solutionFilePath;

            using (var stream = File.OpenRead(solutionFilePath))
            {
                using (var reader = new StreamReader(stream))
                {
                    solutionFile = SolutionFile.Parse(reader);
                }
            }

            _logger.WriteInformation(string.Format("Detecting projects in '{0}'.", solutionFilePath));

            foreach (var block in solutionFile.ProjectBlocks)
            {
                if (!_supportsProjectTypes.Contains(block.ProjectTypeGuid))
                {
                    if (UnityTypeGuid(block.ProjectName) != block.ProjectTypeGuid)
                    {
                        _logger.WriteWarning("Skipped unsupported project type '{0}'", block.ProjectPath);
                        continue;
                    }
                }

                if (_context.ProjectGuidToWorkspaceMapping.ContainsKey(block.ProjectGuid))
                {
                    continue;
                }

                var projectFilePath = Path.GetFullPath(Path.GetFullPath(Path.Combine(_env.Path, block.ProjectPath.Replace('\\', Path.DirectorySeparatorChar))));

                _logger.WriteInformation(string.Format("Loading project from '{0}'.", projectFilePath));

                var projectFileInfo = CreateProject(projectFilePath);

                if (projectFileInfo == null)
                {
                    continue;
                }

                var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectFileInfo.Name),
                                                     VersionStamp.Create(),
                                                     projectFileInfo.Name,
                                                     projectFileInfo.AssemblyName,
                                                     LanguageNames.CSharp,
                                                     projectFileInfo.ProjectFilePath);

                _workspace.AddProject(projectInfo);

                projectFileInfo.WorkspaceId = projectInfo.Id;

                _context.Projects[projectFileInfo.ProjectFilePath]        = projectFileInfo;
                _context.ProjectGuidToWorkspaceMapping[block.ProjectGuid] = projectInfo.Id;

                _watcher.Watch(projectFilePath, OnProjectChanged);
            }

            foreach (var projectFileInfo in _context.Projects.Values)
            {
                UpdateProject(projectFileInfo);
            }
        }
コード例 #28
0
        async Task InitializeAsync(ITextBuffer buffer, string code, MetadataReference[] refs, string languageName, ISynchronousTagger <IClassificationTag> tagger, CompilationOptions compilationOptions, ParseOptions parseOptions)
        {
            using (var workspace = new AdhocWorkspace(RoslynMefHostServices.DefaultServices)) {
                var documents = new List <DocumentInfo>();
                var projectId = ProjectId.CreateNewId();
                documents.Add(DocumentInfo.Create(DocumentId.CreateNewId(projectId), "main.cs", null, SourceCodeKind.Regular, TextLoader.From(buffer.AsTextContainer(), VersionStamp.Create())));

                var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), "compilecodeproj", Guid.NewGuid().ToString(), languageName,
                                                     compilationOptions: compilationOptions
                                                     .WithOptimizationLevel(OptimizationLevel.Release)
                                                     .WithPlatform(Platform.AnyCpu)
                                                     .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default),
                                                     parseOptions: parseOptions,
                                                     documents: documents,
                                                     metadataReferences: refs,
                                                     isSubmission: false, hostObjectType: null);
                workspace.AddProject(projectInfo);
                foreach (var doc in documents)
                {
                    workspace.OpenDocument(doc.Id);
                }

                buffer.Replace(new Span(0, buffer.CurrentSnapshot.Length), code);

                {
                    // Initialize classification code paths
                    var spans = new NormalizedSnapshotSpanCollection(new SnapshotSpan(buffer.CurrentSnapshot, 0, buffer.CurrentSnapshot.Length));
                    foreach (var tagSpan in tagger.GetTags(spans, CancellationToken.None))
                    {
                    }
                }

                {
                    // Initialize completion code paths
                    var info = CompletionInfo.Create(buffer.CurrentSnapshot);
                    Debug.Assert(info != null);
                    if (info != null)
                    {
                        var completionTrigger = CompletionTrigger.Default;
                        var completionList    = await info.Value.CompletionService.GetCompletionsAsync(info.Value.Document, 0, completionTrigger);
                    }
                }

                {
                    // Initialize signature help code paths
                    var info = SignatureHelpInfo.Create(buffer.CurrentSnapshot);
                    Debug.Assert(info != null);
                    if (info != null)
                    {
                        int sigHelpIndex = code.IndexOf("sighelp");
                        Debug.Assert(sigHelpIndex >= 0);
                        var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
                        var items       = await info.Value.SignatureHelpService.GetItemsAsync(info.Value.Document, sigHelpIndex, triggerInfo);
                    }
                }

                {
                    // Initialize quick info code paths
                    var info = QuickInfoState.Create(buffer.CurrentSnapshot);
                    Debug.Assert(info != null);
                    if (info != null)
                    {
                        int quickInfoIndex = code.IndexOf("Equals");
                        Debug.Assert(quickInfoIndex >= 0);
                        var item = await info.Value.QuickInfoService.GetItemAsync(info.Value.Document, quickInfoIndex);
                    }
                }
            }
        }
        internal void VerifyRudeDiagnostics(
            EditScript <SyntaxNode> editScript,
            ActiveStatementsDescription description,
            RudeEditDiagnosticDescription[] expectedDiagnostics)
        {
            var oldActiveStatements = description.OldStatements;

            if (description.OldTrackingSpans != null)
            {
                Assert.Equal(oldActiveStatements.Length, description.OldTrackingSpans.Length);
            }

            var newSource = editScript.Match.NewRoot.SyntaxTree.ToString();
            var oldSource = editScript.Match.OldRoot.SyntaxTree.ToString();

            var oldText = SourceText.From(oldSource);
            var newText = SourceText.From(newSource);

            var diagnostics = new List <RudeEditDiagnostic>();
            var actualNewActiveStatements  = new ActiveStatement[oldActiveStatements.Length];
            var actualNewExceptionRegions  = new ImmutableArray <LinePositionSpan> [oldActiveStatements.Length];
            var updatedActiveMethodMatches = new List <UpdatedMemberInfo>();
            var editMap = BuildEditMap(editScript);

            var documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument");

            var spanTracker = Assert.IsType <TestActiveStatementSpanTracker>(Analyzer.GetTestAccessor().ActiveStatementSpanTracker);

            spanTracker.Spans = (description.OldTrackingSpans != null) ? new Dictionary <DocumentId, TextSpan?[]> {
                { documentId, description.OldTrackingSpans }
            } : null;

            Analyzer.GetTestAccessor().AnalyzeSyntax(
                editScript,
                editMap,
                oldText,
                newText,
                documentId,
                oldActiveStatements.AsImmutable(),
                actualNewActiveStatements,
                actualNewExceptionRegions,
                updatedActiveMethodMatches,
                diagnostics);

            diagnostics.Verify(newSource, expectedDiagnostics);

            // check active statements:
            AssertSpansEqual(description.NewSpans, actualNewActiveStatements.Select(s => s.Span), newSource, newText);

            if (diagnostics.Count == 0)
            {
                // check old exception regions:
                for (var i = 0; i < oldActiveStatements.Length; i++)
                {
                    var actualOldExceptionRegions = Analyzer.GetExceptionRegions(
                        oldText,
                        editScript.Match.OldRoot,
                        oldActiveStatements[i].Span,
                        isNonLeaf: oldActiveStatements[i].IsNonLeaf,
                        out _);

                    AssertSpansEqual(description.OldRegions[i], actualOldExceptionRegions, oldSource, oldText);
                }

                // check new exception regions:
                Assert.Equal(description.NewRegions.Length, actualNewExceptionRegions.Length);
                for (var i = 0; i < description.NewRegions.Length; i++)
                {
                    AssertSpansEqual(description.NewRegions[i], actualNewExceptionRegions[i], newSource, newText);
                }
            }
            else
            {
                for (var i = 0; i < oldActiveStatements.Length; i++)
                {
                    Assert.Equal(0, description.NewRegions[i].Length);
                }
            }
        }
コード例 #30
0
        /*
         *
         * private void FinishLoad()
         * {
         *  // Check that the set of analyzers is complete and consistent.
         *  GetAnalyzerDependencyCheckingService()?.ReanalyzeSolutionForConflicts();
         * }
         *
         * private AnalyzerDependencyCheckingService GetAnalyzerDependencyCheckingService()
         * {
         *  var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
         *
         *  return componentModel.GetService<AnalyzerDependencyCheckingService>();
         * }
         *
         */

        public ProjectId GetOrCreateProjectIdForPath(string filePath, string projectDisplayName)
        {
            // HACK: to keep F# working, we will ensure we return the ProjectId if there is a project that matches this path. Otherwise, we'll just return
            // a random ProjectId, which is sufficient for their needs. They'll simply observe there is no project with that ID, and then go and create a
            // new project. Then they call this function again, and fetch the real ID.
            return(_workspace.CurrentSolution.Projects.FirstOrDefault(p => p.FilePath == filePath)?.Id ?? ProjectId.CreateNewId("ProjectNotFound"));
        }