private async Task <Document> AppendIgnoreList( Document document, ObjectCreationExpressionSyntax wholeMappingCreation, ObjectCreationExpressionSyntax existingIgnoreList, string mappingSideType, string membersToAppend, string typeName, CancellationToken cancellationToken) { var parsedMembersToAppend = membersToAppend .Split(';') .Where(x => string.IsNullOrWhiteSpace(x) == false) .ToArray(); var lambdasToAppend = parsedMembersToAppend .Select(x => $"({mappingSideType}) => {mappingSideType}.{x}") .Select(x => SF.ParseExpression(x) as LambdaExpressionSyntax) .Select(x => SF.Argument(x).WithLeadingTrivia(SF.LineFeed)) .ToArray(); if (existingIgnoreList == null) { AddEmptyIgnoreList( ref document, wholeMappingCreation, out existingIgnoreList, typeName, mappingSideType, cancellationToken); } var existingIgnoreLambdas = existingIgnoreList .ArgumentList .Arguments .Select(x => x.Expression.WithoutTrivia()) .Select(x => SF.Argument(x).WithLeadingTrivia(SF.LineFeed)) .ToArray(); var combinedLambdas = new SeparatedSyntaxList <ArgumentSyntax>(); combinedLambdas = combinedLambdas.AddRange(existingIgnoreLambdas); combinedLambdas = combinedLambdas.AddRange(lambdasToAppend); var newArgumentList = SF.ArgumentList(combinedLambdas); var newIgnoreList = existingIgnoreList .WithArgumentList(newArgumentList); document = await ParseSyntaxTextAndReplaceNode(document, existingIgnoreList, newIgnoreList, cancellationToken); return(document); }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var typesList = new List <TypeSyntax> { _baseTypeSyntax }; if (node.BaseList != null) { typesList.AddRange(node.BaseList.Types); } var types = new SeparatedSyntaxList <TypeSyntax>(); types = types.AddRange(typesList); var identifier = SyntaxFactory.Identifier(FurnaceTypeIdentifier + _typeName); var newNode = node.Update( node.AttributeLists, node.Modifiers, node.Keyword, identifier, node.TypeParameterList, SyntaxFactory.BaseList(types), node.ConstraintClauses, node.OpenBraceToken, node.Members, node.CloseBraceToken, node.SemicolonToken).NormalizeWhitespace(); return(base.VisitClassDeclaration(newNode)); }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var typesList = new List<TypeSyntax> { _baseTypeSyntax }; if (node.BaseList != null) typesList.AddRange(node.BaseList.Types); var types = new SeparatedSyntaxList<TypeSyntax>(); types = types.AddRange(typesList); var identifier = SyntaxFactory.Identifier(FurnaceTypeIdentifier + _typeName); var newNode = node.Update( node.AttributeLists, node.Modifiers, node.Keyword, identifier, node.TypeParameterList, SyntaxFactory.BaseList(types), node.ConstraintClauses, node.OpenBraceToken, node.Members, node.CloseBraceToken, node.SemicolonToken).NormalizeWhitespace(); return base.VisitClassDeclaration(newNode); }
public override SyntaxNode VisitArgumentList(ArgumentListSyntax node) { //注意:相关Query.XXXJoin(join, (u, j1) => u.ID == j1.OtherID)不处理,因本身需要之前的参数 if (queryMethodCtx.HasAny && !queryMethodCtx.Current.HoldLambdaArgs && !queryMethodCtx.Current.InLambdaExpression) { var args = new SeparatedSyntaxList <ArgumentSyntax>(); //eg: q.Where(join1, (u, j1) => u.ID == j1.OtherID) //注意:只处理最后一个参数,即移除之前的参数,如上示例中的join1参数,最后的Lambda由VisitQueryMethodLambdaExpresssion处理 var newArgNode = node.Arguments[node.Arguments.Count - 1].Expression.Accept(this); //eg: q.ToList(join1, (t, j1) => new {t.ID, t.Name, j1.Address}) //需要处理 new {XX,XX,XX}为参数列表 if ((queryMethodCtx.Current.MethodName == TypeHelper.SqlQueryToScalarMethod || queryMethodCtx.Current.MethodName == TypeHelper.SqlQueryToListMethod || queryMethodCtx.Current.MethodName == TypeHelper.SqlUpdateOutputMethod) && newArgNode is ArgumentListSyntax argList) { //已被VisitQueryMethodLambdaExpresssion转换为ArgumentListSyntax args = args.AddRange(argList.Arguments); } else { args = args.Add(SyntaxFactory.Argument((ExpressionSyntax)newArgNode)); } return(SyntaxFactory.ArgumentList(args)); } return(base.VisitArgumentList(node)); }
private static ArgumentListSyntax BuildArgumentList( ExpressionSyntax expression, SeparatedSyntaxList <ArgumentSyntax>?additionalArguments) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } ArgumentListSyntax argumentList; if (additionalArguments.HasValue && additionalArguments.Value.Any()) { var args = new SeparatedSyntaxList <ArgumentSyntax>(); args = args.Add(SyntaxFactory.Argument(expression)); args = args.AddRange(additionalArguments.Value); argumentList = SyntaxFactory.ArgumentList(args); } else { argumentList = SyntaxFactory.ArgumentList( SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(expression))); } return(argumentList); }
private static async Task <Document> PopulateMissingAssignmentsAsync(Document document, InitializerExpressionSyntax objectInitializer, string[] unassignedMemberNames, CancellationToken ct) { // Can't manipulate syntax without a syntax root SyntaxNode oldRoot = await document.GetSyntaxRootAsync(ct).ConfigureAwait(false); if (oldRoot == null) { return(document); } SeparatedSyntaxList <ExpressionSyntax> expressions = objectInitializer.Expressions; // Add missing member assignments in object initializer SeparatedSyntaxList <ExpressionSyntax> newExpressions = expressions.AddRange( unassignedMemberNames.Select( memberName => SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(memberName), SyntaxFactory.IdentifierName(string.Empty)))); InitializerExpressionSyntax newObjectInitializer = objectInitializer.WithExpressions( newExpressions); // Reformat fails due to the codefix code not compiling.. // newObjectInitializer = // (InitializerExpressionSyntax) Formatter.Format(newObjectInitializer, MSBuildWorkspace.Create()); SyntaxNode newRoot = oldRoot.ReplaceNode(objectInitializer, newObjectInitializer); return(document.WithSyntaxRoot(newRoot)); }
private static async Task <Document> PopulateMissingAssignmentsAsync(Document document, InitializerExpressionSyntax objectInitializer, string[] unassignedMemberNames, CancellationToken ct) { // Can't manipulate syntax without a syntax root SyntaxNode oldRoot = await document.GetSyntaxRootAsync(ct).ConfigureAwait(false); if (oldRoot == null) { return(document); } SeparatedSyntaxList <ExpressionSyntax> expressions = objectInitializer.Expressions; // Add missing member assignments in object initializer. // End of line honors .editorconfig and/or system preferences, but it does NOT honor if a different EOL used in the file. SeparatedSyntaxList <ExpressionSyntax> newExpressions = expressions .AddRange(unassignedMemberNames.Select(CreateEmptyMemberAssignmentExpression)); InitializerExpressionSyntax newObjectInitializer = objectInitializer.WithExpressions(newExpressions); SyntaxNode newRoot = oldRoot.ReplaceNode(objectInitializer, newObjectInitializer); return(document.WithSyntaxRoot(newRoot)); }
public void SomeTest() { var tree = CSharpSyntaxTree.ParseFile("Roslyn/FurnaceItem.cs"); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType <ClassDeclarationSyntax>().First(); var tt = SyntaxFactory.ParseTypeName("TestClass"); var typesList = new List <TypeSyntax> { tt }; typesList.AddRange(node.BaseList.Types); var types = new SeparatedSyntaxList <TypeSyntax>(); types = types.AddRange(typesList); //SyntaxFactory.BaseList(); var updated = node.Update(node.AttributeLists, node.Modifiers, node.Keyword, node.Identifier, node.TypeParameterList, SyntaxFactory.BaseList(types), node.ConstraintClauses, node.OpenBraceToken, node.Members, node.CloseBraceToken, node.SemicolonToken).NormalizeWhitespace(); System.Console.WriteLine(updated.ToFullString()); }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var tt = SyntaxFactory.ParseTypeName(_baseClass); var typesList = new List <TypeSyntax> { tt }; typesList.AddRange(node.BaseList.Types); var types = new SeparatedSyntaxList <TypeSyntax>(); types = types.AddRange(typesList); //SyntaxFactory.BaseList(); var updated = node.Update(node.AttributeLists, node.Modifiers, node.Keyword, node.Identifier, node.TypeParameterList, SyntaxFactory.BaseList(types), node.ConstraintClauses, node.OpenBraceToken, node.Members, node.CloseBraceToken, node.SemicolonToken).NormalizeWhitespace(); return(updated); }
private void DoTestAddInsertRemoveOnEmptyList(SeparatedSyntaxList <SyntaxNode> list) { Assert.Equal(0, list.Count); SyntaxNode nodeD = SyntaxFactory.ParseExpression("D"); SyntaxNode nodeE = SyntaxFactory.ParseExpression("E"); var newList = list.Add(nodeD); Assert.Equal(1, newList.Count); Assert.Equal("D", newList.ToFullString()); newList = list.AddRange(new[] { nodeD, nodeE }); Assert.Equal(2, newList.Count); Assert.Equal("D,E", newList.ToFullString()); newList = list.Insert(0, nodeD); Assert.Equal(1, newList.Count); Assert.Equal("D", newList.ToFullString()); newList = list.InsertRange(0, new[] { nodeD, nodeE }); Assert.Equal(2, newList.Count); Assert.Equal("D,E", newList.ToFullString()); newList = list.Remove(nodeD); Assert.Equal(0, newList.Count); Assert.Equal(-1, list.IndexOf(nodeD)); Assert.Throws <ArgumentOutOfRangeException>(() => list.RemoveAt(0)); Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(1, nodeD)); Assert.Throws <ArgumentOutOfRangeException>(() => list.Insert(-1, nodeD)); Assert.Throws <ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { nodeD })); Assert.Throws <ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { nodeD })); Assert.Throws <ArgumentNullException>(() => list.Add(null)); Assert.Throws <ArgumentNullException>( () => list.AddRange((IEnumerable <SyntaxNode>)null) ); Assert.Throws <ArgumentNullException>(() => list.Insert(0, null)); Assert.Throws <ArgumentNullException>( () => list.InsertRange(0, (IEnumerable <SyntaxNode>)null) ); }
public static InvocationExpressionSyntax CreateInvocationExpression( ExpressionSyntax leftPart, string rightPart, params ArgumentSyntax[] argument) { var expression = CreateMemberAccessExpression(leftPart, rightPart); var separatedSyntaxList = new SeparatedSyntaxList <ArgumentSyntax>(); separatedSyntaxList = separatedSyntaxList.AddRange(argument); return(SyntaxFactory.InvocationExpression(expression, SyntaxFactory.ArgumentList(separatedSyntaxList))); }
private StatementSyntax CreateAssert(ExpressionSyntax test, bool isIsTrue, ArgumentSyntax[] additionalArguments) { SeparatedSyntaxList <ArgumentSyntax> newArguments = new SeparatedSyntaxList <ArgumentSyntax>(); newArguments = newArguments.Add(SyntaxFactory.Argument(test)); newArguments = newArguments.AddRange(additionalArguments); return(SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("Assert"), SyntaxFactory.IdentifierName(isIsTrue ? "IsTrue" : "IsFalse") ).WithOperatorToken(SyntaxFactory.Token(SyntaxKind.DotToken))).WithArgumentList(SyntaxFactory.ArgumentList(arguments: newArguments)))); }
public static ArgumentListSyntax ToArgumentList(this IEnumerable <ExpressionSyntax> parameters) { var argumentList = SyntaxFactory.ArgumentList(); if (parameters.Any()) { var arguments = new SeparatedSyntaxList <ArgumentSyntax>(); arguments = arguments.AddRange(parameters.Select(SyntaxFactory.Argument)); argumentList = SyntaxFactory.ArgumentList(arguments); } return(argumentList); }
public static ExpressionSyntax CreateInstance(string identifierName, params ArgumentSyntax[] arguments) { var result = SyntaxFactory.ObjectCreationExpression(SyntaxFactory.IdentifierName(identifierName)); if (arguments != null && arguments.Length > 0) { var argList = new SeparatedSyntaxList <ArgumentSyntax>(); argList = argList.AddRange(arguments); result = result.WithArgumentList(SyntaxFactory.ArgumentList(argList)); } return(result); }
private static SeparatedSyntaxList <ParameterSyntax> RemoveDefaultValuesFromComplexTypeParameters(SeparatedSyntaxList <ParameterSyntax> parameters) { // asp.net web api does not support controller method parameters that are: // 1) reference types with default values set to 'null' // 2) enums with any default values // therefore remove all default values from complex type parameters // also the auto gen client files will include the default values so ok to remove them for enums // otherwise perhaps need to auto gen enum as a string (and parse it) or as a nullable type bool IsComplexTypeWithDefaultValue(ParameterSyntax parameter) { var param = new SeparatedSyntaxList <ParameterSyntax>().Add(parameter); var isComplexType = ComplexTypesGenerator.FindComplexTypes(param).Any(); var hasDefaultValue = parameter.Default != null; return(isComplexType && hasDefaultValue); } // split up complex type parameters into two lists: 1) has default values 2) all others var parametersGroupByDefaults = parameters.ToLookup(IsComplexTypeWithDefaultValue); var defaultValParameters = parametersGroupByDefaults[true].ToList(); var otherParameters = parametersGroupByDefaults[false]; if (!defaultValParameters.Any()) { return(parameters); } // remove default values var removedDefaultParameters = defaultValParameters .Select(parameter => { parameter = IsComplexTypeWithDefaultValue(parameter) ? parameter.WithDefault(null) : parameter; return(parameter); }); // combine modified parameters no longer with default values back with other params var newParameters = new SeparatedSyntaxList <ParameterSyntax>(); newParameters = newParameters.AddRange(otherParameters); var insertIndex = ParametersGenerator.FindIndexBeforeFirstOptionalParam(newParameters); newParameters = newParameters.InsertRange(insertIndex, removedDefaultParameters); return(newParameters); }
public ExpressionSyntax Construct(IEnumerable <ExpressionSyntax> parameters, params AssignmentExpressionSyntax[] initializer) { var expression = SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName(Name), parameters.ToArgumentList(), null); //Add initializer if provided if (initializer != null && initializer.Any()) { var list = new SeparatedSyntaxList <ExpressionSyntax>(); list = list.AddRange(initializer); expression = expression.WithInitializer(SyntaxFactory.InitializerExpression(SyntaxKind.ObjectInitializerExpression, list)); } return(expression); }
private TypeArgumentListSyntax ParameterToArgumentListSyntax(TypeParameterListSyntax typeParameters) { var list = new SeparatedSyntaxList <TypeSyntax>(); list = list.AddRange(typeParameters.Parameters.Select(p => SyntaxFactory.ParseName(p.ToString()).WithTriviaFrom(p))); for (int i = 0; i < list.SeparatorCount; i++) { var separator = list.GetSeparator(i); // Make sure the parameter list looks nice list = list.ReplaceSeparator(separator, separator.WithTrailingTrivia(SyntaxFactory.Whitespace(" "))); } return(SyntaxFactory.TypeArgumentList(list)); }
private ArgumentListSyntax DecomposeEqualsFunction(ArgumentListSyntax argumentList, out bool isNotEquals) { ArgumentSyntax first = argumentList.Arguments[0]; List <ArgumentSyntax> rest = argumentList.Arguments.Skip(1).ToList(); ExtractEqualsFunction(first, out ArgumentSyntax areEqualsExpected, out ArgumentSyntax areEqualsActual, out isNotEquals); SeparatedSyntaxList <ArgumentSyntax> newArguments = new SeparatedSyntaxList <ArgumentSyntax>(); newArguments = newArguments.Add(areEqualsExpected); newArguments = newArguments.Add(areEqualsActual); newArguments = newArguments.AddRange(rest); return(SyntaxFactory.ArgumentList(newArguments)); }
private static TypeArgumentListSyntax ParameterToArgumentListSyntax(TypeParameterListSyntax typeParameters) { var list = new SeparatedSyntaxList <TypeSyntax>(); list = list.AddRange(typeParameters.Parameters.Select(p => SyntaxFactory.ParseName(p.ToString()).WithTriviaFrom(p))); for (int i = 0; i < list.SeparatorCount; i++) { var separator = list.GetSeparator(i); // Make sure the parameter list looks nice // Cannot use ReplaceSeparator due to dotnet/roslyn#2630: https://github.com/dotnet/roslyn/issues/2630 list = SyntaxFactory.SeparatedList <TypeSyntax>(list.GetWithSeparators().Replace(separator, separator.WithTrailingTrivia(SyntaxFactory.Space))); } return(SyntaxFactory.TypeArgumentList(list)); }
private ArgumentListSyntax DecomposeEqualsEquals(SyntaxKind kind, ArgumentListSyntax argumentList, out bool isNotEquals, out bool isNullArgument) { ArgumentSyntax first = argumentList.Arguments[0]; List <ArgumentSyntax> rest = argumentList.Arguments.Skip(1).ToList(); switch (kind) { case SyntaxKind.EqualsExpression: isNotEquals = false; break; case SyntaxKind.NotEqualsExpression: isNotEquals = true; break; default: throw new ArgumentException("kind is not supported", nameof(kind)); } ExtractEqualsEquals(first, out ArgumentSyntax areEqualsExpected, out ArgumentSyntax areEqualsActual); SeparatedSyntaxList <ArgumentSyntax> newArguments = new SeparatedSyntaxList <ArgumentSyntax>(); if (areEqualsActual.Expression.Kind() == SyntaxKind.NullLiteralExpression) { isNullArgument = true; newArguments = newArguments.Add(areEqualsExpected); } else if (areEqualsExpected.Expression.Kind() == SyntaxKind.NullLiteralExpression) { isNullArgument = true; newArguments = newArguments.Add(areEqualsActual); } else { isNullArgument = false; newArguments = newArguments.Add(areEqualsExpected); newArguments = newArguments.Add(areEqualsActual); } newArguments = newArguments.AddRange(rest); return(SyntaxFactory.ArgumentList(newArguments)); }
public static SeparatedSyntaxList <ParameterSyntax> TransformMultipleComplexTypeParameters(SeparatedSyntaxList <ParameterSyntax> originalParameters, string methodName) { // handle if parameters have more two or more (i.e. multiple) complex types var complexParameters = MultipleComplexTypesGenerator.FindMultipleComplexTypesOrOutKeyword(originalParameters); if (!complexParameters.Any()) { return(originalParameters); } var parameters = new SeparatedSyntaxList <ParameterSyntax>(); // remove all complex types from parameters var complexNames = complexParameters .Select(complex => complex.Identifier.ToFullString()); var filteredParameters = originalParameters .Where(parameter => { var name = parameter.Identifier.ToFullString(); return(complexNames.All(complexName => complexName != name)); }); parameters = parameters.AddRange(filteredParameters); // add single complex class type parameter var complexType = ComplexTypeNamesMapper.MapToServiceComplexClassType(methodName); var complexParameterName = ComplexTypeNamesMapper.MapToComplexClassParameterName(methodName); var complexTypeClass = SyntaxFactory.Parameter(SyntaxFactory.Identifier(complexParameterName)) .WithType(SyntaxFactory.IdentifierName(complexType)); // insert complex type before any optional parameters with default values // otherwise insert at the end var insertIndex = ParametersGenerator.FindIndexBeforeFirstOptionalParam(parameters); parameters = parameters.Insert(insertIndex, complexTypeClass); return(parameters); }
private async Task <Solution> HoistAssignment(Document document, InvocationExpressionSyntax paramsInvocation, CancellationToken cancellationToken) { var originalSolution = document.Project.Solution; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var method = semanticModel.GetSymbolInfo(paramsInvocation).Symbol as IMethodSymbol; var typeDisplayString = method.Parameters.Last().Type.ToMinimalDisplayString(semanticModel, method.Parameters.Last().Locations.First().SourceSpan.Start); var bracketedSyntax = SyntaxFactory.BracketedArgumentList(); var updatedParameters = new SeparatedSyntaxList <ExpressionSyntax>(); var actualArguments = paramsInvocation.ArgumentList.Arguments.Skip(method.Parameters.Length - 1).Select(x => x.Expression).ToArray(); updatedParameters = updatedParameters.AddRange(actualArguments); var newArray = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, updatedParameters); var typeSyntax = SyntaxFactory.ParseTypeName(typeDisplayString); var objectCreationExpression = SyntaxFactory.ObjectCreationExpression(typeSyntax, null, newArray).WithAdditionalAnnotations(Formatter.Annotation); var equalsValueClause = SyntaxFactory.EqualsValueClause(objectCreationExpression); var declarator = new SeparatedSyntaxList <VariableDeclaratorSyntax>(); declarator = declarator.Add(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier("hoisted"), null, equalsValueClause)); var variableAssignment = SyntaxFactory.VariableDeclaration(typeSyntax, declarator).WithAdditionalAnnotations(Formatter.Annotation); var assignmentExpression = SyntaxFactory.LocalDeclarationStatement(variableAssignment); var forStatement = IsInSyntax <ForStatementSyntax>(paramsInvocation); var invocationParameterReplacement = new SeparatedSyntaxList <ArgumentSyntax>(); invocationParameterReplacement = invocationParameterReplacement.AddRange(paramsInvocation.ArgumentList.Arguments.Take(method.Parameters.Length - 1)); invocationParameterReplacement = invocationParameterReplacement.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName("hoisted"))); var newArgListSyntax = SyntaxFactory.ArgumentList(invocationParameterReplacement); var newDeclaration = paramsInvocation.WithArgumentList(newArgListSyntax); var documentEditor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); documentEditor.InsertBefore(forStatement, assignmentExpression); documentEditor.ReplaceNode(paramsInvocation, newDeclaration); var newDocument = documentEditor.GetChangedDocument(); var finalRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); finalRoot = Formatter.Format(finalRoot, Formatter.Annotation, document.Project.Solution.Workspace); return(originalSolution.WithDocumentSyntaxRoot(document.Id, finalRoot)); }
private MethodDeclarationSyntax GenerateSignature(MethodDeclarationSyntax originalMethod) { // Apply a suffix to the name of a copy of the class. var newMethod = originalMethod.WithIdentifier(SyntaxFactory.Identifier($"{Settings.Prefix}{originalMethod.Identifier.ValueText}")); var sessionParameter = SyntaxFactory.Parameter(new SyntaxList <AttributeListSyntax>(), new SyntaxTokenList(), SyntaxFactory.IdentifierName("TensorFlow.TFSession"), SyntaxFactory.Identifier("session"), null); //session = session.AddModifiers(SyntaxFactory.Token(SyntaxKind.ThisKeyword)); var parameters = new SeparatedSyntaxList <ParameterSyntax>(); parameters = parameters.AddRange(originalMethod.ParameterList.Parameters); parameters = parameters.Add(sessionParameter); var methodParameters = SyntaxFactory.ParameterList(parameters); newMethod = newMethod.WithParameterList(methodParameters); return(newMethod); }
private AttributeListSyntax CreateInternalVisibleToAttributeList(Project project, Project[] allProjects) { var testProjects = allProjects.Where(x => x.ProjectReferences.Any(y => y.ProjectId == project.Id)).ToArray(); if (testProjects.Length == 0) return null; List<AttributeSyntax> attrs = testProjects.Select(CreateInternalVisibleToAttribute).ToList(); var attributeList = new SeparatedSyntaxList<AttributeSyntax>(); attributeList = attributeList.AddRange(attrs); var assemblyLevelSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)); return SyntaxFactory.AttributeList(assemblyLevelSpecifier, attributeList); }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var tt = SyntaxFactory.ParseTypeName(_baseClass); var typesList = new List<TypeSyntax> { tt }; typesList.AddRange(node.BaseList.Types); var types = new SeparatedSyntaxList<TypeSyntax>(); types = types.AddRange(typesList); //SyntaxFactory.BaseList(); var updated = node.Update(node.AttributeLists, node.Modifiers, node.Keyword, node.Identifier, node.TypeParameterList, SyntaxFactory.BaseList(types), node.ConstraintClauses, node.OpenBraceToken, node.Members, node.CloseBraceToken, node.SemicolonToken).NormalizeWhitespace(); return updated; }
private static TypeArgumentListSyntax ParameterToArgumentListSyntax(TypeParameterListSyntax typeParameters) { var list = new SeparatedSyntaxList<TypeSyntax>(); list = list.AddRange(typeParameters.Parameters.Select(p => SyntaxFactory.ParseName(p.ToString()).WithTriviaFrom(p))); for (int i = 0; i < list.SeparatorCount; i++) { // Make sure the parameter list looks nice var separator = list.GetSeparator(i); list = list.ReplaceSeparator(separator, separator.WithTrailingTrivia(SyntaxFactory.Space)); } return SyntaxFactory.TypeArgumentList(list); }
public void SomeTest() { var tree = CSharpSyntaxTree.ParseFile("Roslyn/FurnaceItem.cs"); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); var tt = SyntaxFactory.ParseTypeName("TestClass"); var typesList = new List<TypeSyntax> {tt}; typesList.AddRange(node.BaseList.Types); var types = new SeparatedSyntaxList<TypeSyntax>(); types = types.AddRange(typesList); //SyntaxFactory.BaseList(); var updated = node.Update(node.AttributeLists, node.Modifiers, node.Keyword, node.Identifier, node.TypeParameterList, SyntaxFactory.BaseList(types), node.ConstraintClauses, node.OpenBraceToken, node.Members, node.CloseBraceToken, node.SemicolonToken).NormalizeWhitespace(); System.Console.WriteLine(updated.ToFullString()); }
MethodDeclarationSyntax CreateMethod(WaylandProtocol protocol, WaylandProtocolInterface iface, WaylandProtocolRequest request, int index) { var newIdArgument = request.Arguments?.FirstOrDefault(a => a.Type == WaylandArgumentTypes.NewId); if (newIdArgument != null && newIdArgument.Interface == null) { return(null); } var ctorType = newIdArgument?.Interface; var dotNetCtorType = ctorType == null ? "void" : GetWlInterfaceTypeName(ctorType); var method = MethodDeclaration( ParseTypeName(dotNetCtorType), Pascalize(request.Name)); var plist = new SeparatedSyntaxList <ParameterSyntax>(); var arglist = new SeparatedSyntaxList <ExpressionSyntax>(); var statements = new SeparatedSyntaxList <StatementSyntax>(); var callStatements = new SeparatedSyntaxList <StatementSyntax>(); var fixedDeclarations = new List <VariableDeclarationSyntax>(); if (request.Since > 0) { statements = statements.Add(IfStatement( BinaryExpression(SyntaxKind.LessThanExpression, IdentifierName("Version"), MakeLiteralExpression(request.Since)) , request.Type == "destructor" ? (StatementSyntax)ReturnStatement() : ThrowStatement(ObjectCreationExpression(ParseTypeName("System.InvalidOperationException")) .WithArgumentList( ArgumentList(SingletonSeparatedList(Argument(MakeLiteralExpression( $"Request {request.Name} is only supported since version {request.Since}")))))))); } if (request.Arguments != null) { foreach (var arg in request.Arguments ?? Array.Empty <WaylandProtocolArgument>()) { TypeSyntax parameterType = null; var nullCheck = false; var argName = "@" + Pascalize(arg.Name, true); if (arg.Type == WaylandArgumentTypes.Int32 || arg.Type == WaylandArgumentTypes.Fixed || arg.Type == WaylandArgumentTypes.FileDescriptor || arg.Type == WaylandArgumentTypes.Uint32) { var nativeType = arg.Type == WaylandArgumentTypes.Uint32 ? "uint" : "int"; var managedType = TryGetEnumTypeReference(protocol.Name, iface.Name, request.Name, arg.Name, arg.Enum) ?? nativeType; parameterType = ParseTypeName(managedType); if (nativeType != managedType) { arglist = arglist.Add(CastExpression(ParseTypeName(nativeType), IdentifierName(argName))); } else { arglist = arglist.Add(IdentifierName(argName)); } } else if (arg.Type == WaylandArgumentTypes.NewId) { arglist = arglist.Add(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("WlArgument"), IdentifierName("NewId"))); } else if (arg.Type == WaylandArgumentTypes.String) { nullCheck = true; parameterType = ParseTypeName("System.String"); var tempName = "__marshalled__" + argName.TrimStart('@'); var bufferType = ParseTypeName("NWayland.Interop.NWaylandMarshalledString"); statements = statements.Add(LocalDeclarationStatement( new SyntaxTokenList(Token(SyntaxKind.UsingKeyword)), VariableDeclaration(ParseTypeName("var")) .WithVariables(SingletonSeparatedList( VariableDeclarator(tempName) .WithInitializer(EqualsValueClause(ObjectCreationExpression(bufferType) .WithArgumentList( ArgumentList( SingletonSeparatedList(Argument(IdentifierName(argName))))))) )))); arglist = arglist.Add(IdentifierName(tempName)); } else if (arg.Type == WaylandArgumentTypes.Object) { nullCheck = true; parameterType = ParseTypeName(GetWlInterfaceTypeName(arg.Interface)); arglist = arglist.Add(IdentifierName(argName)); } else if (arg.Type == WaylandArgumentTypes.Array) { if (arg.AllowNull) { throw new NotSupportedException( "Wrapping nullable arrays is currently not supported"); } var arrayElementType = _hints.GetTypeNameForArray(protocol.Name, iface.Name, request.Name, arg.Name); parameterType = ParseTypeName("ReadOnlySpan<" + arrayElementType + ">"); var pointerName = "__pointer__" + argName.TrimStart('@'); var tempName = "__marshalled__" + argName.TrimStart('@'); fixedDeclarations.Add(VariableDeclaration(ParseTypeName(arrayElementType + "*"), SingletonSeparatedList(VariableDeclarator(pointerName) .WithInitializer(EqualsValueClause(IdentifierName(argName)))))); callStatements = callStatements.Add(LocalDeclarationStatement(VariableDeclaration(ParseTypeName("var")) .WithVariables(SingletonSeparatedList(VariableDeclarator(tempName) .WithInitializer(EqualsValueClause( InvocationExpression(MemberAccess(ParseTypeName("NWayland.Interop.WlArray"), "FromPointer"), ArgumentList(SeparatedList(new[] { Argument(IdentifierName(pointerName)), Argument(MemberAccess(IdentifierName(argName), "Length")) } )))) ))))); arglist = arglist.Add(PrefixUnaryExpression(SyntaxKind.AddressOfExpression, IdentifierName(tempName))); } if (parameterType != null) { plist = plist.Add(Parameter(Identifier(argName)).WithType(parameterType)); } if (nullCheck) { statements = statements.Insert(0, IfStatement( BinaryExpression(SyntaxKind.EqualsExpression, IdentifierName(argName), MakeNullLiteralExpression()), ThrowStatement(ObjectCreationExpression(ParseTypeName("System.ArgumentNullException")) .WithArgumentList( ArgumentList( SingletonSeparatedList( Argument(MakeLiteralExpression(argName.TrimStart('@'))))))))); } } } callStatements = callStatements.Add(LocalDeclarationStatement(VariableDeclaration(ParseTypeName("WlArgument*")) .WithVariables(SingletonSeparatedList(VariableDeclarator("__args") .WithInitializer(EqualsValueClause(StackAllocArrayCreationExpression( ArrayType(ParseTypeName("WlArgument[]")), InitializerExpression(SyntaxKind.ArrayInitializerExpression, arglist)))))))); var marshalArgs = SeparatedList(new[] { Argument(MemberAccess(IdentifierName("this"), "Handle")), Argument(MakeLiteralExpression(index)), Argument(IdentifierName("__args")) }); if (ctorType != null) { marshalArgs = marshalArgs.Add(Argument(GetWlInterfaceRefFor(ctorType))); } var callExpr = InvocationExpression(MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("LibWayland"), IdentifierName(ctorType == null ? "wl_proxy_marshal_array" : "wl_proxy_marshal_array_constructor")), ArgumentList(marshalArgs)); if (ctorType == null) { callStatements = callStatements.Add(ExpressionStatement(callExpr)); } else { callStatements = callStatements.Add(LocalDeclarationStatement(VariableDeclaration(ParseTypeName("var")) .WithVariables(SingletonSeparatedList( VariableDeclarator("__ret").WithInitializer(EqualsValueClause(callExpr)))))); callStatements = callStatements.Add(ReturnStatement(ConditionalExpression(BinaryExpression( SyntaxKind.EqualsExpression, IdentifierName("__ret"), MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("IntPtr"), IdentifierName("Zero"))), MakeNullLiteralExpression(), ObjectCreationExpression(ParseTypeName(dotNetCtorType)).WithArgumentList( ArgumentList(SeparatedList(new[] { Argument(IdentifierName("__ret")), Argument(IdentifierName("Version")), Argument(IdentifierName("Display")) })))))); } if (fixedDeclarations.Count == 0) { statements = statements.AddRange(callStatements); } else { var callBlock = (StatementSyntax)Block(callStatements); fixedDeclarations.Reverse(); foreach (var fd in fixedDeclarations) { callBlock = FixedStatement(fd, callBlock); } statements = statements.Add(callBlock); } method = WithSummary(method.WithParameterList(ParameterList(plist)) .WithBody(Block(statements)) .WithModifiers(TokenList(Token(SyntaxKind.PublicKeyword))), request.Description); if (request.Type == "destructor") { method = method .WithIdentifier(Identifier("CallWaylandDestructor")) .WithModifiers(TokenList( Token(SyntaxKind.ProtectedKeyword), Token(SyntaxKind.SealedKeyword), Token(SyntaxKind.OverrideKeyword) )); } return(method); }
private SyntaxNode MkStaticAppConstructor(string testName) { var stmtList = new List <StatementSyntax>(); //Initialize types and events var nodes = dependsOn.Keys.Select(s => s.ToLower()).ToList(); foreach (var files in dependsOn.Values) { foreach (var f in files) { if (!nodes.Contains(f)) { nodes.Add(f); } } } var edges = new List <Tuple <string, string> >(); foreach (var file in dependsOn) { foreach (var dep in file.Value) { if (file.Key != dep) { edges.Add(new Tuple <string, string>(dep.ToLower(), file.Key.ToLower())); } } } List <string> topoOrder = TopologicalSortFiles <string>(nodes, edges); //make invocations to the initialization of all types foreach (var fName in topoOrder) { stmtList.Add( SyntaxFactory.ExpressionStatement(CSharpHelper.MkCSharpInvocationExpression( SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("Types"), SyntaxFactory.IdentifierName("Types_" + fName)) ))); } //make invocation to the initialization of all events foreach (var fName in topoOrder) { stmtList.Add( SyntaxFactory.ExpressionStatement(CSharpHelper.MkCSharpInvocationExpression( SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("Events"), SyntaxFactory.IdentifierName("Events_" + fName)) ))); } //Initialize all the maps //safe map foreach (var sm in allTests[testName].isSafeMap) { var safeadd = CSharpHelper.MkCSharpInvocationExpression( CSharpHelper.MkCSharpDot("isSafeMap", "Add"), CSharpHelper.MkCSharpStringLiteralExpression(sm.Key), sm.Value ? CSharpHelper.MkCSharpTrueLiteralExpression() : CSharpHelper.MkCSharpFalseLiteralExpression() ); stmtList.Add(SyntaxFactory.ExpressionStatement(safeadd)); } //rename map foreach (var rename in allTests[testName].renameMap) { var renameadd = CSharpHelper.MkCSharpInvocationExpression( CSharpHelper.MkCSharpDot("renameMap", "Add"), CSharpHelper.MkCSharpStringLiteralExpression(rename.Key), CSharpHelper.MkCSharpStringLiteralExpression(rename.Value) ); stmtList.Add(SyntaxFactory.ExpressionStatement(renameadd)); } //create map var listOfSpecMachineNames = allTests[testName].renameMap.Where(item => allTests[testName].specMachineMap.ContainsKey(item.Key)).Select(item => item.Value).Distinct(); var listOfMachineNames = allTests[testName].renameMap.Where(item => !allTests[testName].specMachineMap.ContainsKey(item.Key)).Select(item => item.Value).Distinct(); foreach (var specMachine in listOfSpecMachineNames) { var createadd = CSharpHelper.MkCSharpInvocationExpression( CSharpHelper.MkCSharpDot("createSpecMap", "Add"), CSharpHelper.MkCSharpStringLiteralExpression(specMachine), SyntaxFactory.IdentifierName(string.Format("CreateSpecMachine_{0}", specMachine))); stmtList.Add(SyntaxFactory.ExpressionStatement(createadd)); } foreach (var machine in listOfMachineNames) { //its a machine var createadd = CSharpHelper.MkCSharpInvocationExpression( CSharpHelper.MkCSharpDot("createMachineMap", "Add"), CSharpHelper.MkCSharpStringLiteralExpression(machine), SyntaxFactory.IdentifierName(string.Format("CreateMachine_{0}", machine)) ); stmtList.Add(SyntaxFactory.ExpressionStatement(createadd)); } //interface map foreach (var it in allTests[testName].interfaceMap) { var eventsParams = new SeparatedSyntaxList <ExpressionSyntax>(); foreach (var ev in it.Value) { eventsParams = eventsParams.Add(GetEventVar(ev)); } var initStmt = CSharpHelper.MkCSharpSimpleAssignmentExpressionStatement( SyntaxFactory.ElementAccessExpression( SyntaxFactory.IdentifierName("interfaceMap"), SyntaxFactory.BracketedArgumentList(SyntaxFactory.SingletonSeparatedList <ArgumentSyntax>(SyntaxFactory.Argument(CSharpHelper.MkCSharpStringLiteralExpression(it.Key)))) ), SyntaxFactory.ObjectCreationExpression( SyntaxFactory.GenericName(SyntaxFactory.Identifier("List"), SyntaxFactory.TypeArgumentList(SyntaxFactory.SingletonSeparatedList <TypeSyntax>(SyntaxFactory.IdentifierName("PrtEventValue")))), SyntaxFactory.ArgumentList(), SyntaxFactory.InitializerExpression(SyntaxKind.CollectionInitializerExpression, eventsParams)) ); stmtList.Add(initStmt); } //send actions { var eventsParams = new SeparatedSyntaxList <ExpressionSyntax>(); foreach (var ev in allTests[testName].sendActions) { eventsParams = eventsParams.Add(CSharpHelper.MkCSharpStringLiteralExpression(ev)); } var initStmt = CSharpHelper.MkCSharpSimpleAssignmentExpressionStatement( SyntaxFactory.IdentifierName("visibleEvents"), SyntaxFactory.ObjectCreationExpression( SyntaxFactory.GenericName(SyntaxFactory.Identifier("List"), SyntaxFactory.TypeArgumentList(SyntaxFactory.SingletonSeparatedList <TypeSyntax>(SyntaxFactory.IdentifierName("string")))), SyntaxFactory.ArgumentList(), SyntaxFactory.InitializerExpression(SyntaxKind.CollectionInitializerExpression, eventsParams)) ); stmtList.Add(initStmt); } //interface actions { var interfaceParams = new SeparatedSyntaxList <ExpressionSyntax>(); foreach (var it in allTests[testName].createActions) { interfaceParams = interfaceParams.Add(CSharpHelper.MkCSharpStringLiteralExpression(it)); } var initStmt = CSharpHelper.MkCSharpSimpleAssignmentExpressionStatement( SyntaxFactory.IdentifierName("visibleInterfaces"), SyntaxFactory.ObjectCreationExpression( SyntaxFactory.GenericName(SyntaxFactory.Identifier("List"), SyntaxFactory.TypeArgumentList(SyntaxFactory.SingletonSeparatedList <TypeSyntax>(SyntaxFactory.IdentifierName("string")))), SyntaxFactory.ArgumentList(), SyntaxFactory.InitializerExpression(SyntaxKind.CollectionInitializerExpression, interfaceParams)) ); stmtList.Add(initStmt); } //initialize the interface types foreach (var it in allTests[testName].interfaceMap) { var initStmt = CSharpHelper.MkCSharpSimpleAssignmentExpressionStatement( SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParenthesizedExpression( CSharpHelper.MkCSharpCastExpression("PrtInterfaceType", SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.IdentifierName("Types"), SyntaxFactory.IdentifierName(String.Format("type_{0}", it.Key))))), SyntaxFactory.IdentifierName("permissions")), SyntaxFactory.ElementAccessExpression( SyntaxFactory.IdentifierName("interfaceMap"), SyntaxFactory.BracketedArgumentList(SyntaxFactory.SingletonSeparatedList <ArgumentSyntax>(SyntaxFactory.Argument(CSharpHelper.MkCSharpStringLiteralExpression(it.Key)))) ) ); stmtList.Add(initStmt); } //spec machine map foreach (var specMachine in allTests[testName].specMachineMap) { SeparatedSyntaxList <ExpressionSyntax> machines = new SeparatedSyntaxList <ExpressionSyntax>(); machines = machines.AddRange(specMachine.Value.Select(x => CSharpHelper.MkCSharpStringLiteralExpression(x))); var addstmt = CSharpHelper.MkCSharpInvocationExpression( CSharpHelper.MkCSharpDot("specMachineMap", "Add"), CSharpHelper.MkCSharpStringLiteralExpression(specMachine.Key), SyntaxFactory.ObjectCreationExpression( CSharpHelper.MkCSharpGenericListType(SyntaxFactory.IdentifierName("string")), SyntaxFactory.ArgumentList(), SyntaxFactory.InitializerExpression(SyntaxKind.CollectionInitializerExpression, machines)) ); stmtList.Add(SyntaxFactory.ExpressionStatement(addstmt)); } //link map //declare temp variable var dictStringString = SyntaxFactory.GenericName( SyntaxFactory.Identifier("Dictionary"), SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList <TypeSyntax>( new SyntaxNodeOrToken[] { SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.StringKeyword)), SyntaxFactory.Token(SyntaxKind.CommaToken), SyntaxFactory.PredefinedType( SyntaxFactory.Token(SyntaxKind.StringKeyword)) })) ); stmtList.Add( SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration( dictStringString, SyntaxFactory.SingletonSeparatedList <VariableDeclaratorSyntax>( SyntaxFactory.VariableDeclarator( SyntaxFactory.Identifier("_temp")) ) ) ) ); foreach (var creatorM in allTests[testName].linkMap) { var tempInit = CSharpHelper.MkCSharpSimpleAssignmentExpressionStatement( SyntaxFactory.IdentifierName("_temp"), CSharpHelper.MkCSharpObjectCreationExpression(dictStringString) ); stmtList.Add(tempInit); foreach (var linkmapitem in creatorM.Value) { stmtList.Add( SyntaxFactory.ExpressionStatement( CSharpHelper.MkCSharpInvocationExpression( CSharpHelper.MkCSharpDot("_temp", "Add"), CSharpHelper.MkCSharpStringLiteralExpression(linkmapitem.Key), CSharpHelper.MkCSharpStringLiteralExpression(linkmapitem.Value) )) ); } var addLinkItem = SyntaxFactory.ExpressionStatement( CSharpHelper.MkCSharpInvocationExpression( CSharpHelper.MkCSharpDot("linkMap", "Add"), CSharpHelper.MkCSharpStringLiteralExpression(creatorM.Key), SyntaxFactory.IdentifierName("_temp")) ); stmtList.Add(addLinkItem); } var staticConstrutor = SyntaxFactory.ConstructorDeclaration( SyntaxFactory.Identifier("Application")) .WithModifiers( SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.StaticKeyword))) .WithBody(SyntaxFactory.Block(stmtList)) .NormalizeWhitespace(); return(staticConstrutor); }
private void DoTestAddInsertRemoveOnEmptyList(SeparatedSyntaxList<SyntaxNode> list) { Assert.Equal(0, list.Count); SyntaxNode nodeD = SyntaxFactory.ParseExpression("D"); SyntaxNode nodeE = SyntaxFactory.ParseExpression("E"); var newList = list.Add(nodeD); Assert.Equal(1, newList.Count); Assert.Equal("D", newList.ToFullString()); newList = list.AddRange(new[] { nodeD, nodeE }); Assert.Equal(2, newList.Count); Assert.Equal("D,E", newList.ToFullString()); newList = list.Insert(0, nodeD); Assert.Equal(1, newList.Count); Assert.Equal("D", newList.ToFullString()); newList = list.InsertRange(0, new[] { nodeD, nodeE }); Assert.Equal(2, newList.Count); Assert.Equal("D,E", newList.ToFullString()); newList = list.Remove(nodeD); Assert.Equal(0, newList.Count); Assert.Equal(-1, list.IndexOf(nodeD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, nodeD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, nodeD)); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { nodeD })); Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { nodeD })); Assert.Throws<ArgumentNullException>(() => list.Add(null)); Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxNode>)null)); Assert.Throws<ArgumentNullException>(() => list.Insert(0, null)); Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxNode>)null)); }