/// <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 async Task <string> GetStringFromDocumentAsync(Document document) { var simplifiedDoc = await Simplifier.ReduceAsync(document, Simplifier.Annotation).ConfigureAwait(false); var root = await simplifiedDoc.GetSyntaxRootAsync().ConfigureAwait(false); root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace); return(root.GetText().ToString()); }
public static SyntaxNode GetReducedSyntaxRoot(this Document document) { var syntaxRoot = document.GetSyntaxRootAsync().GetAwaiter().GetResult(); var documentToSimplify = document.WithSyntaxRoot(syntaxRoot.WithAdditionalAnnotations(Simplifier.Annotation)); var reducedDocument = Simplifier.ReduceAsync(documentToSimplify).GetAwaiter().GetResult(); var reducedSyntaxRoot = reducedDocument.GetSyntaxRootAsync().GetAwaiter().GetResult(); return(reducedSyntaxRoot.Simplify()); }
private static async Task TestAsync( string initialText, string importsAddedText, string simplifiedText, bool useSymbolAnnotations, Func <OptionSet, OptionSet> optionsTransform = null, bool performCheck = true ) { var doc = await GetDocument(initialText, useSymbolAnnotations); OptionSet options = await doc.GetOptionsAsync(); if (optionsTransform != null) { options = optionsTransform(options); } var imported = useSymbolAnnotations ? await ImportAdder.AddImportsFromSymbolAnnotationAsync(doc, options) : await ImportAdder.AddImportsFromSyntaxesAsync(doc, options); if (importsAddedText != null) { var formatted = await Formatter.FormatAsync( imported, SyntaxAnnotation.ElasticAnnotation, options ); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(importsAddedText, actualText); } if (simplifiedText != null) { var reduced = await Simplifier.ReduceAsync(imported, options); var formatted = await Formatter.FormatAsync( reduced, SyntaxAnnotation.ElasticAnnotation, options ); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(simplifiedText, actualText); } if (performCheck) { if (initialText == importsAddedText && importsAddedText == simplifiedText) { throw new Exception($"use {nameof(TestNoImportsAddedAsync)}"); } } }
private static Solution GetSolutionWithFormattedInterfaceDocument(Document unformattedInterfaceDocument, CancellationToken cancellationToken) { Solution solutionWithInterfaceDocument; var formattedRoot = Formatter.Format(unformattedInterfaceDocument.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken), unformattedInterfaceDocument.Project.Solution.Workspace); var rootToSimplify = formattedRoot.WithAdditionalAnnotations(Simplifier.Annotation); var finalInterfaceDocument = Simplifier.ReduceAsync(unformattedInterfaceDocument.WithSyntaxRoot(rootToSimplify), cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); solutionWithInterfaceDocument = finalInterfaceDocument.Project.Solution; return(solutionWithInterfaceDocument); }
/// <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)); }
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)); }
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()); }
private static async Task <Document> AddStringComparisonArgumentAsync(Document document, InvocationExpressionSyntax invocation, CancellationToken cancellationToken) { // TODO: find the "best" overload and map all the existing arguments to it // for now, assume that there is an overload that takes all the existing arguments and also a StringComparison enum member var root = (await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false)) .ReplaceNode(invocation.ArgumentList, invocation.ArgumentList.AddArguments(SyntaxFactory.Argument(SyntaxFactory.ParseExpression("System.StringComparison.Ordinal")))) .WithAdditionalAnnotations(Simplifier.Annotation); return(await Simplifier.ReduceAsync(document.WithSyntaxRoot(root), cancellationToken : cancellationToken).ConfigureAwait(false)); }
protected override async Task <Document> Process(Document doc) { if (!(await doc.GetSyntaxRootAsync() is SyntaxNode root)) { return(doc); } root = root.WithAdditionalAnnotations(Simplifier.Annotation); return(await Simplifier.ReduceAsync(doc.WithSyntaxRoot(root), cancellationToken : taskInterface.CancellationToken)); }
private static async Task <string> GetActualAsync(Document document) { document = await Simplifier.ReduceAsync(document); document = await Formatter.FormatAsync(document, Formatter.Annotation, CSharpSyntaxFormattingOptions.Default, CancellationToken.None); document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation, CSharpSyntaxFormattingOptions.Default, CancellationToken.None); return((await document.GetSyntaxRootAsync()).ToFullString()); }
public static async Task <string> ToSimplifiedAndFormattedFullStringAsync(this Document document) { document = await Simplifier.ReduceAsync(document, Simplifier.Annotation).ConfigureAwait(false); SyntaxNode root = await document.GetSyntaxRootAsync().ConfigureAwait(false); root = Formatter.Format(root, Formatter.Annotation, document.Project.Solution.Workspace); return(root.ToFullString()); }
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 Task <Document> GetFix(Document document, SyntaxNode root, TExpressionSyntax expression, CancellationToken cancellationToken) { // Rewrite the expression to include a .ConfigureAwait() after it. We reattach trailing trivia to the end. // This is especially important for VB, as the end-of-line may be in the trivia var fixedExpression = FixExpression(expression.WithoutTrailingTrivia(), cancellationToken) .WithTrailingTrivia(expression.GetTrailingTrivia()); var fixedDocument = document.WithSyntaxRoot(root.ReplaceNode(expression, fixedExpression)); return(Simplifier.ReduceAsync(fixedDocument, fixedExpression.FullSpan, cancellationToken: cancellationToken)); }
/// <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 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)); }
// 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); }); }
protected override async Task<SemanticDocument> ExpandAsync(SelectionResult selection, CancellationToken cancellationToken) { var lastExpression = selection.GetFirstTokenInSelection().GetCommonRoot(selection.GetLastTokenInSelection()).GetAncestors<ExpressionSyntax>().LastOrDefault(); if (lastExpression == null) { return selection.SemanticDocument; } var newExpression = await Simplifier.ExpandAsync(lastExpression, selection.SemanticDocument.Document, n => n != selection.GetContainingScope(), expandParameter: false, cancellationToken: cancellationToken).ConfigureAwait(false); return await selection.SemanticDocument.WithSyntaxRootAsync(selection.SemanticDocument.Root.ReplaceNode(lastExpression, newExpression), cancellationToken).ConfigureAwait(false); }
/// <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 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); }
public string EnsureEquationCanonizerCorrectness(string equation) { var tokenizer = new Tokenizer(); var simplifier = new Simplifier(); var prettifier = new Prettifier(); var tokens = tokenizer.SplitEquationIntoTokens(equation); var simplifiedTokens = simplifier.SimplifyEquationTokens(tokens); return(prettifier.CombineTokensToEquationString(simplifiedTokens)); }
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()); }
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 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> /// Initializes a new instance of the <see cref="Processor"/> class. /// </summary> public Processor() { Lexer = new Lexer(); Simplifier = new Simplifier(); Differentiator = new Differentiator(); Parser = new Parser(new ExpressionFactory(Differentiator, Simplifier)); TypeAnalyzer = new TypeAnalyzer(); Parameters = new ExpressionParameters(AngleMeasurement.Degree, new ParameterCollection(), new FunctionCollection()); NumeralSystem = NumeralSystem.Decimal; }
private string simplify(string[] aValueTruthTable, string[] theTruthTable, string[][] aValueKMapTable, string[][] theKMapTable) { string functionOutput = ""; int i; bool isAllZeros = true, isAllOnes = true, isAllIgnorances = true; functionOutput = "F(" + VARIABLE_NAME[0] + ", " + VARIABLE_NAME[1] + ", " + VARIABLE_NAME[2] + ", " + VARIABLE_NAME[3] + ") = "; // check if all 0s or all 1s for (i = 0; i < theTruthTable.Length; i++) { if (theTruthTable[i].Equals("1")) { isAllZeros = false; } if (theTruthTable[i].Equals("0")) { isAllOnes = false; } if (!theTruthTable[i].Equals("x")) { isAllIgnorances = false; } } if (isAllZeros || isAllIgnorances) { functionOutput += "0"; } else if (isAllOnes || isAllIgnorances) { functionOutput += "1"; } // do the simplification here else { Simplifier simplifier = new Simplifier(); String functionSimplify = ""; int[] arrMinTerms = getSubArray(theTruthTable, 1); int[] arrIgnorances = getSubArray(theTruthTable, 2); printArray(arrMinTerms); printArray(arrIgnorances); //functionOutput += getFunctionOutput(aValueKMapTable, theKMapTable); functionSimplify = simplifier.getSimplifier(arrMinTerms, arrIgnorances, VARIABLE); functionOutput += functionSimplify; } return(functionOutput); }
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); }
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); }
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)); }
public static void Main(string[] args) { ICharStream input; if ( args.Length>0 ) { input = new ANTLRFileStream(args[0]); } else { input = new ANTLRReaderStream(Console.In); } // BUILD AST PolyLexer lex = new PolyLexer(input); CommonTokenStream tokens = new CommonTokenStream(lex); PolyParser parser = new PolyParser(tokens); PolyParser.poly_return r = parser.poly(); Console.Out.WriteLine("tree="+((ITree)r.Tree).ToStringTree()); // DIFFERENTIATE CommonTreeNodeStream nodes = new CommonTreeNodeStream(r.Tree); nodes.TokenStream = tokens; PolyDifferentiator differ = new PolyDifferentiator(nodes); PolyDifferentiator.poly_return r2 = differ.poly(); Console.Out.WriteLine("d/dx="+((ITree) r2.Tree).ToStringTree()); // SIMPLIFY / NORMALIZE nodes = new CommonTreeNodeStream(r2.Tree); nodes.TokenStream = tokens; Simplifier reducer = new Simplifier(nodes); Simplifier.poly_return r3 = reducer.poly(); Console.Out.WriteLine("simplified="+((ITree) r3.Tree).ToStringTree()); // CONVERT BACK TO POLYNOMIAL nodes = new CommonTreeNodeStream(r3.Tree); nodes.TokenStream = tokens; PolyPrinter printer = new PolyPrinter(nodes); PolyPrinter.poly_return r4 = printer.poly(); Console.Out.WriteLine(r4.ST); }
private Expression TrySimplifyExpression(Expression expression) { Simplifier sim = new Simplifier(); return sim.Visit(expression) as Expression; }
static void AddSimplifier(Simplifier simplifier, params InstructionCode[] codes) { foreach (var code in codes) { Simplifiers[code] = simplifier; } }
public List<Tuple<MaybeFreeExpression, MaybeFreeExpression>> GetSimplifiedInvariants() { var simplifier = new Simplifier(Program); var wrappedInvariants = simplifier.GetSimplifiedItems(AllRemovableTypes.Invariants); var invariants = new List<Tuple<MaybeFreeExpression, MaybeFreeExpression>>(); foreach (var wrappedInvariant in wrappedInvariants) { AllRemovableTypes.AddInvariant(wrappedInvariant.Item2, AllRemovableTypes.FindMemberFromInvariantWrap(wrappedInvariant.Item1)); AllRemovableTypes.RemoveInvariant(wrappedInvariant.Item1); invariants.Add(new Tuple<MaybeFreeExpression, MaybeFreeExpression>(wrappedInvariant.Item1.Removable, wrappedInvariant.Item2.Removable)); } return invariants; }
/// <summary> /// Removes unnecessary parts of asserts (e.g. combined by && where one part is not needed) /// </summary> /// <returns></returns> public List<Tuple<Statement, Statement>> GetSimplifiedAsserts() { var simplifier = new Simplifier(Program); var wrappedAsserts = simplifier.GetSimplifiedItems(AllRemovableTypes.Asserts); var asserts = new List<Tuple<Statement, Statement>>(); foreach (var assert in wrappedAsserts) { AllRemovableTypes.AddAssert(assert.Item2, AllRemovableTypes.FindMemberFromAssertWrap(assert.Item1)); AllRemovableTypes.RemoveAssert(assert.Item1); asserts.Add(new Tuple<Statement, Statement>(assert.Item1.Removable, assert.Item2.Removable)); } return asserts; }