本文整理汇总了C#中Compilation.ReplaceSyntaxTree方法的典型用法代码示例。如果您正苦于以下问题:C# Compilation.ReplaceSyntaxTree方法的具体用法?C# Compilation.ReplaceSyntaxTree怎么用?C# Compilation.ReplaceSyntaxTree使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Compilation
的用法示例。
在下文中一共展示了Compilation.ReplaceSyntaxTree方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SpiltReadOnlyFieldDeclarations
/// <summary>
/// walk the syntax trees and replace each field declaration like int x,y,z
/// with int x; int y; int z;
/// if one of those has a readonly suggestion
/// </summary>
/// <param name="compilation"></param>
/// <param name="annotations"></param>
/// <returns></returns>
private static Compilation SpiltReadOnlyFieldDeclarations(Compilation compilation, IEnumerable<ReadonlyField> annotations)
{
#region CodeContracts
Contract.Requires(compilation != null);
Contract.Requires(annotations != null);
Contract.Ensures(Contract.Result<Compilation>() != null);
#endregion CodeContracts
// this is probably terribly ineffiecient, but once you modify the syntaxTree in anyway you have to get a new semantic model
foreach(var annotation in annotations)
{
var st = compilation.SyntaxTrees.First(x => x.FilePath.Equals(annotation.FileName, StringComparison.OrdinalIgnoreCase));
var fsr = new FieldSplitterRewriter(annotation, st, compilation);
var newroot = fsr.Visit(st.GetRoot()).SyntaxTree.GetRoot();
compilation = compilation.ReplaceSyntaxTree(st, SyntaxFactory.SyntaxTree(newroot, null, st.FilePath));
}
//foreach (var annotationGroup in annotations.GroupBy(x => x.FileName))
//{
// if (annotationGroup.Any())
// {
// var first = annotationGroup.First();
// RBLogger.Info("Splitting fields in {0}", first.FileName);
// var st = compilation.SyntaxTrees.First(x => x.FilePath.Equals(first.FileName, StringComparison.OrdinalIgnoreCase));
// var fsr = new FieldSplitterRewriter(annotationGroup, st, compilation);
// var newroot = fsr.Visit(st.GetRoot()).SyntaxTree.GetRoot();
// compilation = compilation.ReplaceSyntaxTree(st, SyntaxFactory.SyntaxTree(newroot, st.FilePath));
// }
//}
return compilation;
}
示例2: IsSelectingADifferentMethod
private static bool IsSelectingADifferentMethod(IEnumerable<SyntaxNode> childNodes, SimpleNameSyntax methodName, SyntaxTree tree, IMethodSymbol methodSymbol, ExpressionSyntax invocationExpression, Compilation compilation)
{
var parameterExpressions = GetParameterExpressions(childNodes);
var firstArgument = parameterExpressions.FirstOrDefault();
var argumentList = CreateArgumentListSyntaxFrom(parameterExpressions.Skip(1));
var newInvocationStatement = CreateInvocationExpression(firstArgument, methodName, argumentList)
.WithAdditionalAnnotations(introduceExtensionMethodAnnotation);
var extensionMethodNamespaceUsingDirective = SyntaxFactory.UsingDirective(methodSymbol.ContainingNamespace.ToNameSyntax());
var speculativeRootWithExtensionMethod = tree.GetCompilationUnitRoot()
.ReplaceNode(invocationExpression, newInvocationStatement)
.AddUsings(extensionMethodNamespaceUsingDirective);
var speculativeModel = compilation.ReplaceSyntaxTree(tree, speculativeRootWithExtensionMethod.SyntaxTree)
.GetSemanticModel(speculativeRootWithExtensionMethod.SyntaxTree);
var speculativeInvocationStatement = speculativeRootWithExtensionMethod.SyntaxTree.GetCompilationUnitRoot().GetAnnotatedNodes(introduceExtensionMethodAnnotation).Single() as InvocationExpressionSyntax;
var speculativeExtensionMethodSymbol = speculativeModel.GetSymbolInfo(speculativeInvocationStatement.Expression).Symbol as IMethodSymbol;
var speculativeNonExtensionFormOfTheMethodSymbol = speculativeExtensionMethodSymbol?.GetConstructedReducedFrom();
return speculativeNonExtensionFormOfTheMethodSymbol == null || !speculativeNonExtensionFormOfTheMethodSymbol.Equals(methodSymbol);
}
示例3: IsSelectingADifferentMethod
private static bool IsSelectingADifferentMethod(IEnumerable<SyntaxNode> childNodes, SimpleNameSyntax methodName, SyntaxTree tree, IMethodSymbol methodSymbol, ExpressionSyntax invocationExpression, Compilation compilation)
{
var parameterExpressions = GetParameterExpressions(childNodes);
var firstArgument = parameterExpressions.FirstOrDefault();
var argumentList = CreateArgumentListSyntaxFrom(parameterExpressions.Skip(1));
var newInvocationStatement = CreateInvocationExpression(firstArgument, methodName, argumentList)
.WithAdditionalAnnotations(introduceExtensionMethodAnnotation);
var extensionMethodNamespaceUsingDirective = SyntaxFactory.UsingDirective(methodSymbol.ContainingNamespace.ToNameSyntax());
var speculativeRootWithExtensionMethod = tree.GetCompilationUnitRoot()
.ReplaceNode(invocationExpression, newInvocationStatement)
.AddUsings(extensionMethodNamespaceUsingDirective);
var speculativeTree = speculativeRootWithExtensionMethod.SyntaxTree;
var speculativeTreeOptions = (CSharpParseOptions)speculativeTree.Options;
var speculativeTreeWithCorrectLanguageVersion = speculativeTree.WithRootAndOptions(speculativeRootWithExtensionMethod, speculativeTreeOptions.WithLanguageVersion(((CSharpParseOptions)tree.Options).LanguageVersion));
var speculativeModel = compilation.ReplaceSyntaxTree(tree, speculativeTreeWithCorrectLanguageVersion)
.GetSemanticModel(speculativeTreeWithCorrectLanguageVersion);
var speculativeInvocationStatement = speculativeTreeWithCorrectLanguageVersion.GetCompilationUnitRoot().GetAnnotatedNodes(introduceExtensionMethodAnnotation).Single() as InvocationExpressionSyntax;
var speculativeExtensionMethodSymbol = speculativeModel.GetSymbolInfo(speculativeInvocationStatement.Expression).Symbol as IMethodSymbol;
var speculativeNonExtensionFormOfTheMethodSymbol = speculativeExtensionMethodSymbol?.GetConstructedReducedFrom();
return speculativeNonExtensionFormOfTheMethodSymbol == null || speculativeNonExtensionFormOfTheMethodSymbol.ToString() != methodSymbol.ToString();//can't compare equality, as speculative symbol might be different
}
示例4: UpdateDocumentInCompilationAsync
private static async Task<Compilation> UpdateDocumentInCompilationAsync(
Compilation compilation,
DocumentState oldDocument,
DocumentState newDocument,
CancellationToken cancellationToken)
{
return compilation.ReplaceSyntaxTree(
await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false),
await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false));
}
示例5: ObjectInvariantPass
/// <summary>
/// Find each object invariant if it exists, otherwise create it, update the annotations
/// </summary>
/// <param name="compilation"></param>
/// <param name="annotations"></param>
/// <param name="newannotations">modified annotations with method/file names in the new compilation</param>
/// <returns>modified compilation with missing object invariants added</returns>
public static Compilation ObjectInvariantPass(Compilation compilation,
IEnumerable<BaseAnnotation> annotations,
out IEnumerable<BaseAnnotation> newannotations)
{
#region CodeContracts
Contract.Requires(compilation != null);
Contract.Requires(annotations != null);
Contract.Ensures(Contract.Result<Compilation>() != null);
Contract.Ensures(Contract.ValueAtReturn(out newannotations) != null);
Contract.Ensures(Contract.ValueAtReturn(out newannotations).Count() == annotations.Count());
#endregion CodeContracts
Output.WriteLine("Adding object invariants");
var objectInvariants = annotations.OfType<UnresolvedObjectInvariant>();
var newanns = annotations.Except(objectInvariants);
// with partial classes we can have annotations that refer to that same class in different files
//foreach (var fileGroup in objectInvariants.GroupBy(x => x.FileName))
//{
// var fileName = fileGroup.First().FileName;
// var syntaxTree = compilation.SyntaxTrees.First(x => x.FilePath.Equals(fileName, StringComparison.OrdinalIgnoreCase));
// foreach (var typeGroup in fileGroup.GroupBy(x => x.TypeName))
// {
// var typeName = typeGroup.First().TypeName;
// var typeNode = FindClassNode(compilation, syntaxTree, typeName);
// var method = FindObjectInvariantMethod(compilation.GetSemanticModel(syntaxTree), typeNode);
// if (method == null)
// {
// method = AddObjectInvariantMethod(typeNode);
// var newTypeNode = method.Parent;
// var newSyntaxTreeRoot = syntaxTree.GetRoot().ReplaceNode(typeNode, newTypeNode);
// var newSyntaxTree = SyntaxFactory.SyntaxTree(newSyntaxTreeRoot, syntaxTree.FilePath);
// compilation = compilation.ReplaceSyntaxTree(syntaxTree, newSyntaxTree);
// //syntaxTree = newSyntaxTree;
// // the next call is necessary when we change the compilation inside the loop
// syntaxTree = compilation.SyntaxTrees.First(x => x.FilePath.Equals(fileName, StringComparison.OrdinalIgnoreCase));
// } // else do nothing, the object invariant method exists
// newanns = newanns.Concat(UpdateMethodNames(compilation, typeGroup));
// }
//}
foreach (var typeGroup in objectInvariants.GroupBy(x => x.TypeName))
{
var typeName = typeGroup.First().TypeName;
var files = typeGroup.Select(annotation => annotation.FileName).Distinct();
//ClassDeclarationSyntax typeNode;
TypeDeclarationSyntax typeNode;
SyntaxTree syntaxTree;
// we need multiple files because of partial classes
if (!DoesObjectInvariantExist(typeName, files, compilation, out typeNode, out syntaxTree))
{
var method = AddObjectInvariantMethod(typeNode);
var newTypeNode = method.Parent;
var newSyntaxTreeRoot = syntaxTree.GetRoot().ReplaceNode(typeNode, newTypeNode);
var newSyntaxTree = SyntaxFactory.SyntaxTree(newSyntaxTreeRoot, null, syntaxTree.FilePath);
compilation = compilation.ReplaceSyntaxTree(syntaxTree, newSyntaxTree);
// the next call is necessary when we change the compilation inside the loop
//syntaxTree = compilation.SyntaxTrees.First(x => x.FilePath.Equals(syntaxTree.FilePath, StringComparison.OrdinalIgnoreCase));
}
newanns = newanns.Concat(ResolveObjectInvariants(compilation, typeGroup));
}
newannotations = newanns.ToImmutableArray();
return compilation;
}
示例6: MakeContractsClassFor
private static Compilation MakeContractsClassFor(Project project, Compilation original, string interfacename, string filename, string parameters)
{
#region CodeContracts
Contract.Requires(project != null);
Contract.Requires(original != null);
Contract.Requires(interfacename != null);
Contract.Requires(filename != null);
Contract.Ensures(Contract.Result<Compilation>() != null);
#endregion CodeContracts
var st = original.SyntaxTrees.Where(x => x.FilePath.Equals(filename, StringComparison.OrdinalIgnoreCase)).First();
var doc = project.GetDocument(st);
var sm = original.GetSemanticModel(st);
var node = st.GetRoot().DescendantNodes().Where(x => x.CSharpKind() == SyntaxKind.InterfaceDeclaration
&& sm.GetDeclaredSymbol(x).GetDocumentationCommentId().Equals(interfacename)).First() as InterfaceDeclarationSyntax;
var parent = node.Parent;
var newclass = MakeContractsClassForNode(interfacename, parameters);
var mem = newclass as MemberDeclarationSyntax;
SyntaxNode newnode = null;
if (parent.CSharpKind() == SyntaxKind.ClassDeclaration)
{
var classdecl = parent as ClassDeclarationSyntax;
var newdecl = classdecl.AddMembers(mem);
newnode = parent.Parent.ReplaceNode(parent, newdecl);
}
if (parent.CSharpKind() == SyntaxKind.NamespaceDeclaration)
{
var namedecl = parent as NamespaceDeclarationSyntax;
var newdecl = namedecl.AddMembers(mem);
newnode = parent.Parent.ReplaceNode(parent, newdecl);
}
var newst = CSharpSyntaxTree.Create(newnode.SyntaxTree.GetRoot() as CSharpSyntaxNode, null, st.FilePath, null);
return original.ReplaceSyntaxTree(st, newst);
}
示例7: ImplementContractsClass
private static Compilation ImplementContractsClass(Project project, Compilation original, string filename, string interfacename, string contractname)
{
#region CodeContracts
Contract.Requires(project != null);
Contract.Requires(original != null);
Contract.Requires(filename != null);
Contract.Requires(interfacename != null);
Contract.Requires(contractname != null);
Contract.Ensures(Contract.Result<Compilation>() != null);
#endregion CodeContracts
var interfaceShortName = InterfaceAnnotationHelpers.GetUnqualifiedName(interfacename);
var doc = project.Documents.First(x => x.FilePath.Equals(filename, StringComparison.OrdinalIgnoreCase));
var orig_st = original.SyntaxTrees.First(x => x.FilePath.Equals(filename, StringComparison.OrdinalIgnoreCase));
doc = doc.WithSyntaxRoot(orig_st.GetRoot());
var st = doc.GetSyntaxTreeAsync().Result;
Contract.Assert(st != null);
//var st = CSharpSyntaxTree.Create(doc.GetSyntaxRootAsync().Result as CSharpSyntaxNode, orig_st.FilePath, null);
var newcomp = original.ReplaceSyntaxTree(orig_st, st);
var sm = newcomp.GetSemanticModel(st);
//Console.WriteLine(doc.GetTextAsync().Result);
var classes = st.GetRoot().DescendantNodesAndSelf().Where(x => x.CSharpKind().Equals(SyntaxKind.ClassDeclaration));
var node = classes.First(x => sm.GetDeclaredSymbol(x).GetDocumentationCommentId().Equals(contractname));
//var node = st.GetRoot().DescendantNodesAndSelf().First(x => x.CSharpKind().Equals(SyntaxKind.ClassDeclaration)
// && sm.GetDeclaredSymbol(x).GetDocumentationCommentId().Equals(contractname));
var baselist = node.DescendantNodes().First(x => x.CSharpKind().Equals(SyntaxKind.BaseList));
var inode = baselist.DescendantTokens().First(x => x.Text.Equals(interfaceShortName));
//var assembly = Assembly.LoadFrom(@"C:\cci\Microsoft.Research\Imported\Tools\Roslyn\v4.5.1\Microsoft.CodeAnalysis.CSharp.Features.dll");
//var assembly = Assembly.LoadFrom(@"C:\Users\t-scottc\Desktop\Signed_20140201.1\Microsoft.CodeAnalysis.CSharp.Features.dll");
//var assembly = Assembly.LoadFrom(@"C:\cci\Microsoft.Research\CCTools\ReviewBot\bin\Debug\Microsoft.CodeAnalysis.CSharp.Features.dll");
Assembly assembly;
if (UsingHelpers.TryGetMicrosoftCodeAnalysisCSharpFeatures(out assembly))
{
try
{
var type = assembly.GetType("Microsoft.CodeAnalysis.CSharp.ImplementInterface.CSharpImplementInterfaceService");
var method = type.GetMethod("ImplementInterfaceAsync");
var service = Activator.CreateInstance(type);
var result = method.Invoke(service, new object[] { doc, inode.Parent, CancellationToken.None }) as Task<Document>;
var newdoc = result.Result;
return newcomp.ReplaceSyntaxTree(st, newdoc.GetSyntaxTreeAsync().Result);
}
catch(Exception e)
{
Output.WriteWarning("Something went wrong while trying to invoke Roslyn refactoring engine. Details: {0}", e.Message);
Output.WriteLine("We continue skipping this interface");
return original;
}
}
else
{
Output.WriteWarning("Can't add the interface contract to {0} as we failed loading the Roslyn refactoring engine", interfacename);
return original;
}
}
示例8: AddContractsClassAttributeToInterface
private static Compilation AddContractsClassAttributeToInterface(Project project, Compilation original, string filename, string interfacename, string parameterstring)
{
#region CodeContracts
Contract.Requires(project != null);
Contract.Requires(original != null);
Contract.Requires(filename != null);
Contract.Requires(interfacename != null);
Contract.Ensures(Contract.Result<Compilation>() != null);
#endregion CodeContracts
var interfaceShortName = InterfaceAnnotationHelpers.GetUnqualifiedName(interfacename);
var st = original.SyntaxTrees.Where(x => x.FilePath.Equals(filename, StringComparison.OrdinalIgnoreCase)).First();
var doc = project.GetDocument(st);
var sm = original.GetSemanticModel(st);
var node = st.GetRoot().DescendantNodes().Where(x => x.CSharpKind() == SyntaxKind.InterfaceDeclaration
&& sm.GetDeclaredSymbol(x).GetDocumentationCommentId().Equals(interfacename)).First() as InterfaceDeclarationSyntax;
Contract.Assert(node != null);
var parameters = "";
var numberparams = GetNumberParameters(parameterstring);
if (numberparams > 0)
{
parameters = "<";
var commas = new String(',', numberparams - 1);
parameters += commas;
parameters += ">";
}
var attr_name = SyntaxFactory.ParseName("ContractClass");
var attr_args = SyntaxFactory.ParseAttributeArgumentList(String.Format("(typeof({0}Contracts{1}))", interfaceShortName, parameters));
var attr = SyntaxFactory.Attribute(attr_name, attr_args);
var attributes = SyntaxFactory.SeparatedList<AttributeSyntax>().Add(attr);
var attr_list = SyntaxFactory.AttributeList(attributes);
var newnode = node.AddAttributeLists(attr_list) as SyntaxNode;
newnode = node.SyntaxTree.GetRoot().ReplaceNode(node, newnode);
var newst = CSharpSyntaxTree.Create(newnode.SyntaxTree.GetRoot() as CSharpSyntaxNode, null, st.FilePath, null);
return original.ReplaceSyntaxTree(st, newst);
}
示例9: CreateOrFindContractsClasses
/// <summary>
/// Take all the annotations, select only the interface annotations, create their contract classes (if necessary),
/// resolve the contract class name and contract class method names
/// </summary>
/// <param name="annotations"></param>
/// <param name="project"></param>
/// <param name="compilation"></param>
/// <param name="resolvedannotations">All the annotations with the interface annotation fields completed</param>
/// <returns>The compilation with potentially new empty contract classes</returns>
internal static Compilation CreateOrFindContractsClasses(IEnumerable<BaseAnnotation> annotations,
Project project,
Compilation compilation,
out IEnumerable<BaseAnnotation> resolvedannotations)
{
#region CodeContracts
Contract.Requires(annotations != null);
Contract.Requires(project != null);
Contract.Requires(compilation != null);
Contract.Ensures(Contract.ValueAtReturn<IEnumerable<BaseAnnotation>>(out resolvedannotations) != null);
Contract.Ensures(Contract.Result<Compilation>() != null);
#endregion CodeContracts
Output.WriteLine("Gathering (and creating) contract classes for interfaces and abstract classes");
var resolvedList = annotations.Where(x => !(x is UnresolvedInterfaceAnnotation)).ToList();
foreach (var interfaceGroup in annotations.OfType<UnresolvedInterfaceAnnotation>().GroupBy(x => x.InterfaceName))
{
var first = interfaceGroup.First();
var interfaceSymbol = InterfaceAnnotationHelpers.GetInterfaceSymbol(project, compilation, first.InterfaceName, first.InterfaceShortName);
string contractName, fileName, interfaceName;
interfaceName = first.InterfaceName;
if (!InterfaceAnnotationHelpers.TryFindContractsClass(compilation, interfaceSymbol, out contractName, out fileName))
{
//fileName = first.FileName;
fileName = interfaceSymbol.Locations[0].SourceTree.FilePath; // hopefully index 0 is where the declaration is?
var interfaceMethod = first.InterfaceMethod;
contractName = GetCreatedContractClassName(interfaceName, interfaceMethod);
compilation = InterfaceAnnotationHelpers.MakeContractsClassFor(project, compilation, interfaceName, fileName, first.ParametersString);
compilation = InterfaceAnnotationHelpers.ImplementContractsClass(project, compilation, fileName, interfaceName, contractName);
var syntaxTree = compilation.SyntaxTrees.First(x => x.FilePath.Equals(fileName, StringComparison.OrdinalIgnoreCase));
var newSyntaxTree = Replacer.AddUsingsContracts(syntaxTree);
compilation = compilation.ReplaceSyntaxTree(syntaxTree, SyntaxFactory.SyntaxTree(newSyntaxTree.GetRoot(), null, fileName));
compilation = InterfaceAnnotationHelpers.AddContractsClassAttributeToInterface(project, compilation, fileName, interfaceName, first.ParametersString);
}
foreach (var methodgroup in interfaceGroup.GroupBy(annotation => annotation.InterfaceMethod))
{
first = methodgroup.First();
var methodName = InterfaceAnnotationHelpers.GetMethodName(first.InterfaceName, first.InterfaceMethod, contractName);
resolvedList.AddRange(methodgroup.Select(x => new ResolvedInterfaceAnnotation(fileName, methodName, x.Annotation, x.Squiggle, x.Kind, x)));
}
//var methodName = InterfaceAnnotationHelpers.GetMethodName(first.InterfaceName, first.InterfaceMethod, contractName);
//resolvedList.AddRange(interfaceGroup.Select(x => new ResolvedInterfaceAnnotation(fileName, methodName, x.Annotation, x.Squiggle, x.Kind, x)));
//return compilation;
//compilation = first.MakeOrFindContractsClass(project, compilation);
//foreach (var intf in interfaceGroup)
//{
// //intf.CopyFileNameAndContractsClass(first);
//
//}
//foreach (var grp in interfaceGroup.GroupBy(x => x.MethodName))
//{
// first = grp.First();
// first.FindMethodName(compilation);
// foreach (var intf in grp)
// {
// intf.CopyMethodName(first);
// }
//}
}
resolvedannotations = resolvedList.AsReadOnly();
return compilation;
}
示例10: InsertNodeInCompilation
public Compilation InsertNodeInCompilation(Compilation compilation, SyntaxNode node, SyntaxNode newNode)
{
var syntaxTree = node.SyntaxTree;
var root = syntaxTree.GetRoot();
var newRoot = root.InsertNodesBefore(node, new[] { newNode });
var newSyntaxTree = syntaxTree.WithRootAndOptions(newRoot, syntaxTree.Options);
var newCompilation = compilation.ReplaceSyntaxTree(syntaxTree, newSyntaxTree);
return newCompilation;
}