private static async Task <Document> ReplaceStringComparisonArgumentAsync(Document document, InvocationExpressionSyntax invocation, string expressionValue, CancellationToken cancellationToken) { var arguments = invocation.ArgumentList.Arguments; var newArguments = arguments.Replace(arguments.Last(), Argument(ParseExpression(expressionValue).WithAdditionalAnnotations(Simplifier.Annotation))); var newArgumentList = invocation.ArgumentList.WithArguments(newArguments); var root = (await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)) .ReplaceNode(invocation.ArgumentList, newArgumentList); return(await Simplifier.ReduceAsync(document.WithSyntaxRoot(root), cancellationToken : cancellationToken).ConfigureAwait(false)); }
/// <summary> /// Given a document, turn it into a string based on the syntax root. /// </summary> /// <param name="document">The <see cref="Document"/> to be converted to a string.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param> /// <returns>A string containing the syntax of the <see cref="Document"/> after formatting.</returns> private static async Task <string> GetStringFromDocumentAsync(Document document, CancellationToken cancellationToken) { var simplifiedDoc = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); var formatted = await Formatter.FormatAsync(simplifiedDoc, Formatter.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); var sourceText = await formatted.GetTextAsync(cancellationToken).ConfigureAwait(false); return(sourceText.ToString()); }
private string GenerateInsertionText(Document memberContainingDocument, CancellationToken cancellationToken) { memberContainingDocument = Simplifier.ReduceAsync(memberContainingDocument, Simplifier.Annotation, null, cancellationToken).WaitAndGetResult(cancellationToken); memberContainingDocument = Formatter.FormatAsync(memberContainingDocument, Formatter.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); var root = memberContainingDocument.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken); var members = root.GetAnnotatedNodesAndTokens(_annotation).AsImmutable().Select(nOrT => nOrT.AsNode().ToString().Trim()); return(string.Join("\r\n", members)); }
protected override async Task <Document> PostProcessChangesAsync(Document document, CancellationToken cancellationToken) { document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); document = await CaseCorrector.CaseCorrectAsync(document, CaseCorrector.Annotation, cancellationToken).ConfigureAwait(false); return(document); }
private static Solution GetSolutionWithFormattedInterfaceDocument(Document unformattedInterfaceDocument, CancellationToken cancellationToken) { Solution solutionWithInterfaceDocument; var formattedRoot = Formatter.Format(unformattedInterfaceDocument.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken), unformattedInterfaceDocument.Project.Solution.Workspace, cancellationToken: cancellationToken); var rootToSimplify = formattedRoot.WithAdditionalAnnotations(Simplifier.Annotation); var finalInterfaceDocument = Simplifier.ReduceAsync(unformattedInterfaceDocument.WithSyntaxRoot(rootToSimplify), cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); solutionWithInterfaceDocument = finalInterfaceDocument.Project.Solution; return(solutionWithInterfaceDocument); }
private static async Task <string> GetActualAsync(Document document) { document = await Simplifier.ReduceAsync(document); document = await Formatter.FormatAsync(document, Formatter.Annotation); document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation); return((await document.GetSyntaxRootAsync()).ToFullString()); }
public async Task <Document> AddSourceToAsync( Document document, Compilation symbolCompilation, ISymbol symbol, CleanCodeGenerationOptions options, CancellationToken cancellationToken) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var newSemanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var rootNamespace = newSemanticModel.GetEnclosingNamespace(position: 0, cancellationToken); Contract.ThrowIfNull(rootNamespace); var context = new CodeGenerationSolutionContext( document.Project.Solution, new CodeGenerationContext( contextLocation: newSemanticModel.SyntaxTree.GetLocation(new TextSpan()), generateMethodBodies: false, generateDocumentationComments: true, mergeAttributes: false, autoInsertionLocation: false), new CodeAndImportGenerationOptions(options.GenerationOptions, options.CleanupOptions.AddImportOptions).CreateProvider()); // Add the interface of the symbol to the top of the root namespace document = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( context, rootNamespace, CreateCodeGenerationSymbol(document, symbol), cancellationToken).ConfigureAwait(false); document = await AddNullableRegionsAsync(document, cancellationToken).ConfigureAwait(false); var docCommentFormattingService = document.GetRequiredLanguageService <IDocumentationCommentFormattingService>(); var docWithDocComments = await ConvertDocCommentsToRegularCommentsAsync(document, docCommentFormattingService, cancellationToken).ConfigureAwait(false); var docWithAssemblyInfo = await AddAssemblyInfoRegionAsync(docWithDocComments, symbolCompilation, symbol.GetOriginalUnreducedDefinition(), cancellationToken).ConfigureAwait(false); var node = await docWithAssemblyInfo.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formattedDoc = await Formatter.FormatAsync( docWithAssemblyInfo, SpecializedCollections.SingletonEnumerable(node.FullSpan), options.CleanupOptions.FormattingOptions, GetFormattingRules(docWithAssemblyInfo), cancellationToken).ConfigureAwait(false); var reducers = GetReducers(); return(await Simplifier.ReduceAsync(formattedDoc, reducers, options.CleanupOptions.SimplifierOptions, cancellationToken).ConfigureAwait(false)); }
/// <summary> /// General verifier for codefixes. /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes. /// Then gets the string after the codefix is applied and compares it with the expected result. /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true. /// </summary> /// <param name="analyzer">The analyzer to be applied to the source code</param> /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param> /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="newSource">A class in the form of a string after the CodeFix was applied to it</param> private void VerifyFix(TAnalyzer analyzer, TCodeFix codeFixProvider, string oldSource, string newSource) { var document = GetDocument(); var analyzerDiagnostics = GetSortedDiagnosticsFromDocument(analyzer, document); var compilerDiagnostics = GetCompilerDiagnostics(document); var attempts = analyzerDiagnostics.Length; for (int i = 0; i < attempts; ++i) { var actions = new List <CodeAction>(); var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); codeFixProvider.RegisterCodeFixesAsync(context).Wait(); if (!actions.Any()) { break; } document = ApplyFix(document, actions.ElementAt(0)); analyzerDiagnostics = GetSortedDiagnosticsFromDocument(analyzer, document); //check if there are analyzer diagnostics left after the code fix if (!analyzerDiagnostics.Any()) { break; } } //after applying all of the code fixes, compare the resulting string to the inputted one var actual = GetStringFromDocument(document); Assert.Equal(newSource, actual); Document ApplyFix(Document document, CodeAction codeAction) { var operations = codeAction.GetOperationsAsync(CancellationToken.None).Result; var solution = operations.OfType <ApplyChangesOperation>().Single().ChangedSolution; return(solution.GetDocument(document.Id)); } string GetStringFromDocument(Document document) { var simplifiedDoc = Simplifier.ReduceAsync(document, Simplifier.Annotation).Result; var root = simplifiedDoc.GetSyntaxRootAsync().Result; root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace); return(root.GetText().ToString()); } IEnumerable <Diagnostic> GetCompilerDiagnostics(Document document) { return(document.GetSemanticModelAsync().Result.GetDiagnostics()); } }
// public static IUnresolvedMember AddCodeDomMember (MonoDevelop.Projects.Project project, IUnresolvedTypeDefinition type, CodeTypeMember newMember) // { // bool isOpen; // var data = TextFileProvider.Instance.GetTextEditorData (type.Region.FileName, out isOpen); // var parsedDocument = IdeApp.TypeSystemService.ParseFile (data.FileName, data.MimeType, data.Text); // // var insertionPoints = GetInsertionPoints (data, parsedDocument, type); // // var suitableInsertionPoint = GetSuitableInsertionPoint (insertionPoints, type, newMember); // // var dotNetProject = project as DotNetProject; // if (dotNetProject == null) { // LoggingService.LogError ("Only .NET projects are supported."); // return null; // } // // var generator = dotNetProject.LanguageBinding.GetCodeDomProvider (); // StringWriter sw = new StringWriter (); // var options = new CodeGeneratorOptions (); // options.IndentString = data.GetLineIndent (type.Region.BeginLine) + "\t"; // if (newMember is CodeMemberMethod) // options.BracingStyle = "C"; // generator.GenerateCodeFromMember (newMember, sw, options); // // var code = sw.ToString (); // if (!string.IsNullOrEmpty (code)) // suitableInsertionPoint.Insert (data, code); // if (!isOpen) { // try { // File.WriteAllText (type.Region.FileName, data.Text); // } catch (Exception e) { // LoggingService.LogError (string.Format ("Failed to write file '{0}'.", type.Region.FileName), e); // MessageService.ShowError (GettextCatalog.GetString ("Failed to write file '{0}'.", type.Region.FileName)); // } // } // var newDocument = IdeApp.TypeSystemService.ParseFile (data.FileName, data.MimeType, data.Text); // return newDocument.ParsedFile.GetMember (suitableInsertionPoint.Location.Line, int.MaxValue); // } public static async Task AddNewMember(Projects.Project project, ITypeSymbol type, Location part, SyntaxNode newMember, CancellationToken cancellationToken = default(CancellationToken)) { if (project == null) { throw new ArgumentNullException(nameof(project)); } if (type == null) { throw new ArgumentNullException(nameof(type)); } if (newMember == null) { throw new ArgumentNullException(nameof(newMember)); } if (!type.IsDefinedInSource()) { throw new ArgumentException("The given type needs to be defined in source code.", nameof(type)); } var ws = IdeApp.TypeSystemService.GetWorkspace(project.ParentSolution); var projectId = ws.GetProjectId(project); var docId = ws.GetDocumentId(projectId, part.SourceTree.FilePath); var document = ws.GetDocument(docId, cancellationToken); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var typeDecl = (ClassDeclarationSyntax)root.FindNode(part.SourceSpan); // for some reason the reducer doesn't reduce this var systemVoid = newMember.DescendantNodesAndSelf().OfType <QualifiedNameSyntax> ().FirstOrDefault(ma => ma.ToString() == "System.Void"); if (systemVoid != null) { newMember = newMember.ReplaceNode(systemVoid, SyntaxFactory.ParseTypeName("void")); } var newRoot = root.ReplaceNode(typeDecl, typeDecl.AddMembers((MemberDeclarationSyntax)newMember.WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation))); document = document.WithSyntaxRoot(newRoot); var projectOptions = await document.GetOptionsAsync(cancellationToken); document = await Formatter.FormatAsync(document, Formatter.Annotation, projectOptions, cancellationToken).ConfigureAwait(false); document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, projectOptions, cancellationToken).ConfigureAwait(false); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newSolution = ws.CurrentSolution.WithDocumentText(docId, text); await Runtime.RunInMainThread(() => { ws.TryApplyChanges(newSolution); }); }
private string SimplifyGeneratedCode(string docName, SyntaxNode node) { // Generate document to simplify generated code var document = mProject.AddDocument(docName, node.GetText()); var annotatedDocument = document.WithSyntaxRoot(document.GetSyntaxRootAsync().Result.WithAdditionalAnnotations(Simplifier.Annotation)); var reducedDocument = Simplifier.ReduceAsync(annotatedDocument).Result; var reducedDocumentText = reducedDocument.GetTextAsync().Result; return(reducedDocumentText.ToString()); }
/// <summary> /// Gets the simplified and formatted text from the document. /// </summary> /// <param name="document">The document to extract the source code from.</param> /// <param name="format">If null the whole document is formatted, for fixed code use <see cref="Formatter.Annotation"/>.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A <see cref="Task"/> with the source text for the document.</returns> internal static string GetStringFromDocument(Document document, SyntaxAnnotation format, CancellationToken cancellationToken) { var simplifiedDoc = Simplifier.ReduceAsync(document, cancellationToken: cancellationToken).ConfigureAwait(false).GetAwaiter().GetResult(); var formatted = format == null ? Formatter.FormatAsync(simplifiedDoc, cancellationToken : cancellationToken).GetAwaiter().GetResult() : Formatter.FormatAsync(simplifiedDoc, format, cancellationToken: cancellationToken).GetAwaiter().GetResult(); var sourceText = formatted.GetTextAsync(cancellationToken).GetAwaiter().GetResult(); return(sourceText.ToString()); }
private static async Task <string> GetStringFromDocumentAsync(Document document) { var simplifiedDoc = await Simplifier.ReduceAsync(document, Simplifier.Annotation); var root = await simplifiedDoc.GetSyntaxRootAsync(); Assert.NotNull(root); root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace); return(root.GetText().ToString()); }
private async Task <string> GenerateInsertionTextAsync( Document memberContainingDocument, CancellationToken cancellationToken) { memberContainingDocument = await Simplifier.ReduceAsync(memberContainingDocument, Simplifier.Annotation, optionSet : null, cancellationToken).ConfigureAwait(false); memberContainingDocument = await Formatter.FormatAsync(memberContainingDocument, Formatter.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); var root = await memberContainingDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return(root.GetAnnotatedNodesAndTokens(_annotation).Single().AsNode().ToString().Trim()); }
private async Task<string> GenerateInsertionTextAsync( Document memberContainingDocument, CancellationToken cancellationToken) { memberContainingDocument = await Simplifier.ReduceAsync(memberContainingDocument, Simplifier.Annotation, null, cancellationToken).ConfigureAwait(false); memberContainingDocument = await Formatter.FormatAsync(memberContainingDocument, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var root = await memberContainingDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var members = root.GetAnnotatedNodesAndTokens(_annotation).AsImmutable().Select(nOrT => nOrT.AsNode().ToString().Trim()); return string.Join("\r\n", members); }
protected override async Task <Document> GetChangedDocumentAsync( CancellationToken cancellationToken ) { var changedDocument = await GetChangedDocumentCoreAsync(cancellationToken) .ConfigureAwait(false); return(await Simplifier .ReduceAsync(changedDocument, cancellationToken : cancellationToken) .ConfigureAwait(false)); }
private static async Task <Document> AddParameterAsync(Document document, MemberAccessExpressionSyntax memberAccess, MethodDeclarationSyntax containingMethod, CancellationToken cancellationToken) { var parameterIdentifier = SyntaxUtility.GetHoistableIdentifier("workState", containingMethod); var root = (await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)) .ReplaceNode(containingMethod, containingMethod .ReplaceNode(memberAccess, IdentifierName(parameterIdentifier)) .AddParameterListParameters(Parameter(parameterIdentifier) .WithType(s_iworkStateTypeName))); return(await Simplifier.ReduceAsync(document.WithSyntaxRoot(root), cancellationToken : cancellationToken).ConfigureAwait(false)); }
private async Task <SyntaxNode> SimplifyAsync(Solution solution, DocumentId documentId, SyntaxNode root, CancellationToken cancellationToken) { Document document = solution.GetDocument(documentId); document = document.WithSyntaxRoot(root); DocumentOptionSet options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); document = await Simplifier.ReduceAsync(document, options, cancellationToken).ConfigureAwait(false); return(await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)); }
protected override async Task <Document> PostProcessChangesAsync(Document document, CancellationToken cancellationToken) { var optionSet = document.Project.Solution.Workspace.Options.WithChangedOption(FormattingOptions.AllowDisjointSpanMerging, true); document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); document = await CaseCorrector.CaseCorrectAsync(document, CaseCorrector.Annotation, cancellationToken).ConfigureAwait(false); return(document); }
public static async Task <(Document containingDocument, SyntaxAnnotation typeAnnotation)> AddTypeToNewFileAsync( Solution solution, string containingNamespaceDisplay, string fileName, ProjectId projectId, IEnumerable <string> folders, INamedTypeSymbol newSymbol, Document hintDocument, CancellationToken cancellationToken) { var newDocumentId = DocumentId.CreateNewId(projectId, debugName: fileName); var newDocumentPath = PathUtilities.CombinePaths(PathUtilities.GetDirectoryName(hintDocument.FilePath), fileName); var solutionWithInterfaceDocument = solution.AddDocument(newDocumentId, fileName, text: "", folders: folders, filePath: newDocumentPath); var newDocument = solutionWithInterfaceDocument.GetRequiredDocument(newDocumentId); var newSemanticModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var options = new CodeGenerationOptions( contextLocation: newSemanticModel.SyntaxTree.GetLocation(new TextSpan()), generateMethodBodies: true, options: await newDocument.GetOptionsAsync(cancellationToken).ConfigureAwait(false)); var namespaceParts = containingNamespaceDisplay.Split('.').Where(s => !string.IsNullOrEmpty(s)); var newTypeDocument = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( newDocument.Project.Solution, newSemanticModel.GetEnclosingNamespace(0, cancellationToken), newSymbol.GenerateRootNamespaceOrType(namespaceParts.ToArray()), options : options, cancellationToken : cancellationToken).ConfigureAwait(false); var formattingSerivce = newTypeDocument.GetLanguageService <INewDocumentFormattingService>(); if (formattingSerivce is not null) { newTypeDocument = await formattingSerivce.FormatNewDocumentAsync(newTypeDocument, hintDocument, cancellationToken).ConfigureAwait(false); } var syntaxRoot = await newTypeDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var typeAnnotation = new SyntaxAnnotation(); var syntaxFacts = newTypeDocument.GetRequiredLanguageService <ISyntaxFactsService>(); var declarationNode = syntaxRoot.DescendantNodes().First(syntaxFacts.IsTypeDeclaration); var annotatedRoot = syntaxRoot.ReplaceNode(declarationNode, declarationNode.WithAdditionalAnnotations(typeAnnotation)); newTypeDocument = newTypeDocument.WithSyntaxRoot(annotatedRoot); var simplified = await Simplifier.ReduceAsync(newTypeDocument, cancellationToken : cancellationToken).ConfigureAwait(false); var formattedDocument = await Formatter.FormatAsync(simplified, cancellationToken : cancellationToken).ConfigureAwait(false); return(formattedDocument, typeAnnotation); }
/// <summary> /// Gets the simplified and formatted text from the document. /// </summary> /// <param name="document">The document to extract the source code from.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A <see cref="Task"/> with the source text for the document.</returns> internal static async Task <string> GetStringFromDocumentAsync(Document document, CancellationToken cancellationToken) { document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation, cancellationToken : cancellationToken).ConfigureAwait(false); var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); return(sourceText.ToString()); }
/// <summary> /// Given a document, turn it into a string based on the syntax root /// </summary> /// <param name="document">The Document to be converted to a string</param> /// <returns>A string containing the syntax of the Document after formatting</returns> private static async Task <string> GetStringFromDocument(Document document, CancellationToken cancellationToken) { var simplifiedDoc = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken : cancellationToken) .ConfigureAwait(false); var root = await simplifiedDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace); return(root.GetText().ToString()); }
private static async Task <Document> ConvertToToListAsReadOnlyAsync(Document document, InvocationExpressionSyntax invocation, CancellationToken cancellationToken) { var root = (await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)) .ReplaceNode(invocation, InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ReplaceInvocation(invocation), IdentifierName("AsReadOnly"))) .NormalizeWhitespace()); return(await Simplifier.ReduceAsync(document.WithSyntaxRoot(root), cancellationToken : cancellationToken).ConfigureAwait(false)); }
async Task <Document> CreateStunt(IEnumerable <INamedTypeSymbol> symbols, SyntaxGenerator generator, StuntGenerator stunts, CancellationToken cancellationToken) { var(name, syntax) = stunts.CreateStunt(symbols, generator); // TODO: F# var extension = document.Project.Language == LanguageNames.CSharp ? ".cs" : ".vb"; var file = Path.Combine(Path.GetDirectoryName(document.Project.FilePath), naming.Namespace, name + extension); var folders = naming.Namespace.Split('.'); var stuntDoc = document.Project.Documents.FirstOrDefault(d => d.Name == Path.GetFileName(file) && d.Folders.SequenceEqual(folders)); if (stuntDoc == null) { if (document.Project.Solution.Workspace is AdhocWorkspace workspace) { stuntDoc = workspace.AddDocument(DocumentInfo .Create( DocumentId.CreateNewId(document.Project.Id), Path.GetFileName(file), folders: naming.Namespace.Split('.'), filePath: file)) .WithSyntaxRoot(syntax); } else { stuntDoc = document.Project.AddDocument( Path.GetFileName(file), syntax, folders, file); } } else { stuntDoc = stuntDoc.WithSyntaxRoot(syntax); } stuntDoc = await stunts.ApplyProcessors(stuntDoc, cancellationToken).ConfigureAwait(false); // This is somewhat expensive, but since we're adding it to the user' solution, we might // as well make it look great ;) stuntDoc = await Simplifier.ReduceAsync(stuntDoc).ConfigureAwait(false); if (document.Project.Language != LanguageNames.VisualBasic) { stuntDoc = await Formatter.FormatAsync(stuntDoc, Formatter.Annotation).ConfigureAwait(false); } syntax = await stuntDoc.GetSyntaxRootAsync().ConfigureAwait(false); return(stuntDoc.WithSyntaxRoot(syntax)); }
private async Task <Document> UseAwait(Document document, MemberAccessExpressionSyntax memberAccessExpression, SyntaxNode root, CancellationToken x) { if (memberAccessExpression == null) { return(document); } var newExpression = ParenthesizedExpression(AwaitExpression(memberAccessExpression.Expression)).WithAdditionalAnnotations(Simplifier.Annotation); var newRoot = root.ReplaceNode(memberAccessExpression, newExpression); var newDocument = await Simplifier.ReduceAsync(document.WithSyntaxRoot(newRoot)); return(newDocument); }
private static async Task <Document> WithReducedRootAsync(this Document doc, SyntaxNode syntaxRoot = null) { var root = syntaxRoot ?? await doc.GetSyntaxRootAsync(); var withSyntaxRoot = doc.WithSyntaxRoot(root); try { return(await Simplifier.ReduceAsync(withSyntaxRoot)); } catch (Exception ex) { var warningText = "Conversion warning: Qualified name reduction failed for this file. " + ex; return(doc.WithSyntaxRoot(WithWarningAnnotation(root, warningText))); } }
/// <summary> /// Given a document, turn it into a string based on the syntax root /// </summary> /// <param name="document">The Document to be converted to a string</param> /// <returns>A string containing the syntax of the Document after formatting</returns> public static string GetStringFromDocument(this Document document) { if (document == null) { throw new ArgumentNullException("document"); } var simplifiedDoc = Simplifier.ReduceAsync(document, Simplifier.Annotation).Result; var root = simplifiedDoc.GetSyntaxRootAsync().Result; root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace); return(root.GetText().ToString()); }
public async Task <ProgramComposition> ProcessAsync(ProgramComposition composition, MDKProjectProperties config) { var newDocument = await Simplifier.ReduceAsync(composition.Document).ConfigureAwait(false); composition = await(composition.WithDocumentAsync(newDocument).ConfigureAwait(false)); _externallyReferencedMembers.Clear(); var root = composition.RootNode; root = Visit(root); return(await composition.WithNewDocumentRootAsync(root)); }
/// <summary> /// Given a document, turn it into a string based on the syntax root /// </summary> /// <param name="document">The Document to be converted to a string</param> /// <returns>A string containing the syntax of the Document after formatting</returns> private static async Task <string> GetStringFromDocumentAsync(Document document) { var simplifiedDoc = await Simplifier.ReduceAsync(document, Simplifier.Annotation); var root = await simplifiedDoc.GetSyntaxRootAsync(); root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace); return(Environment.NewLine switch { "\r\n" => Regex.Replace(root.GetText().ToString(), "[^\r]\n", Environment.NewLine), _ => root.GetText().ToString().Replace("\r\n", Environment.NewLine), });
/// <summary> /// Given a document, turn it into a string based on the syntax root. /// </summary> /// <param name="document">The Document to be converted to a string.</param> /// <returns>A string containing the syntax of the Document after formatting.</returns> private static string GetStringFromDocument(Document document) { var simplifiedDoc = Simplifier.ReduceAsync(document, Simplifier.Annotation).Result; var root = simplifiedDoc.GetSyntaxRootAsync().Result; if (root is null) { throw new InvalidOperationException("The root node for the document is null."); } root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace); return(root.GetText().ToString()); }
private static async Task TestAsync( string initialText, string importsAddedText, string simplifiedText, bool useSymbolAnnotations, bool placeSystemNamespaceFirst = true, bool placeImportsInsideNamespaces = false, bool performCheck = true) { var doc = await GetDocument(initialText, useSymbolAnnotations); var addImportOptions = new AddImportPlacementOptions() { PlaceSystemNamespaceFirst = placeSystemNamespaceFirst, UsingDirectivePlacement = new CodeStyleOption2 <AddImportPlacement>(placeImportsInsideNamespaces ? AddImportPlacement.InsideNamespace : AddImportPlacement.OutsideNamespace, NotificationOption2.None), }; var formattingOptions = CSharpSyntaxFormattingOptions.Default; var simplifierOptions = CSharpSimplifierOptions.Default; var imported = useSymbolAnnotations ? await ImportAdder.AddImportsFromSymbolAnnotationAsync(doc, addImportOptions, CancellationToken.None) : await ImportAdder.AddImportsFromSyntaxesAsync(doc, addImportOptions, CancellationToken.None); if (importsAddedText != null) { var formatted = await Formatter.FormatAsync(imported, SyntaxAnnotation.ElasticAnnotation, formattingOptions, CancellationToken.None); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(importsAddedText, actualText); } if (simplifiedText != null) { var reduced = await Simplifier.ReduceAsync(imported, simplifierOptions, CancellationToken.None); var formatted = await Formatter.FormatAsync(reduced, SyntaxAnnotation.ElasticAnnotation, formattingOptions, CancellationToken.None); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(simplifiedText, actualText); } if (performCheck) { if (initialText == importsAddedText && importsAddedText == simplifiedText) { throw new Exception($"use {nameof(TestNoImportsAddedAsync)}"); } } }