public async Task <string> GenerateStubs(string testProjectPath) { MSBuildWorkspace workspace = MSBuildWorkspace.Create(); Project currentProject = await workspace.OpenProjectAsync(testProjectPath); if (currentProject == null) { throw new ArgumentException("Could not open the project located at " + testProjectPath); } CompilationUnitSyntax cu = SF.CompilationUnit(); var usings = new HashSet <string>(); usings.Add("System"); usings.Add("System.Runtime.CompilerServices"); usings.Add("Etg.SimpleStubs"); foreach (ProjectReference projectRef in currentProject.ProjectReferences) { Project project = workspace.CurrentSolution.GetProject(projectRef.ProjectId); if (_config.IgnoredProjects.Contains(project.Name)) { continue; } var res = await _projectStubber.StubProject(project, cu); cu = res.CompilationUnit; usings.UnionWith(res.Usings); } cu = cu.AddUsings(usings.Select(@using => SF.UsingDirective(SF.IdentifierName(@using))).ToArray()); return(Formatter.Format(cu, workspace).ToString()); }
private async Task <Document> AddAnnotation(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync().ConfigureAwait(false); var methodDeclaration = root.FindToken(diagnostic.Location.SourceSpan.Start).Parent .AncestorsAndSelf() .OfType <MethodDeclarationSyntax>() .First(); if (methodDeclaration == null) { return(document); } var attributesList = methodDeclaration.AttributeLists[0]; var annotationValidate = SF.AttributeList() .AddAttributes(SF.Attribute(SF.IdentifierName("ValidateAntiForgeryToken"))) .WithLeadingTrivia(CodeFixUtil.KeepLastLine(attributesList.GetLeadingTrivia())); var nodes = new List <SyntaxNode> { annotationValidate }; var newRoot = root.InsertNodesAfter(attributesList, nodes); return(document.WithSyntaxRoot(newRoot)); }
public async Task <string> GenerateStubs(string testProjectPath) { MSBuildWorkspace workspace = MSBuildWorkspace.Create(); Project currentProject = await workspace.OpenProjectAsync(testProjectPath); if (currentProject == null) { throw new ArgumentException("Could not open the project located at " + testProjectPath); } List <Project> projectsToStub = GetListOfProjectsToStub(workspace, currentProject); if (!projectsToStub.Any()) { return(string.Empty); } CompilationUnitSyntax cu = SF.CompilationUnit(); var usings = new HashSet <string>(); usings.Add("System"); usings.Add("System.Runtime.CompilerServices"); usings.Add("Etg.SimpleStubs"); foreach (Project project in projectsToStub) { var res = await _projectStubber.StubProject(project, cu); cu = res.CompilationUnit; usings.UnionWith(res.Usings); } cu = cu.AddUsings(usings.Select(@using => SF.UsingDirective(SF.IdentifierName(@using))).ToArray()); return(Formatter.Format(cu, workspace).ToString()); }
private ExpressionSyntax MaybeReplaceLambda(LambdaExpressionSyntax node) { if (_lambdaNumbersDict.TryGetValue(node, out var index)) { return(SyntaxFactory.IdentifierName($"lambda__{index}")); } return(null); }
public CompileContext(Type baseType, Type modelType, string templateNamespace = null, string templateName = null, string templatePath = null, LogHandler logHandler = null) { _templateBaseType = baseType; _location = new TemplateLocation(templatePath); _macroManager = new MacroManager(baseType); _modelTypeName = ClassContext.GetTypeName(modelType); _stateTypeName = $"TxMark.Template.IState<{_modelTypeName}>"; _nameTagManager = new NameTagManager(); _bagsByReference = new Bag <object>(); _variableTypeByName = new Dictionary <string, VariableTypes>(); if (templateNamespace == null) { templateNamespace = DEFAULT_NAMESPACE; } if (templateName == null) { templateName = "Template_" + Guid.NewGuid().ToString().Replace('-', '_'); } _logHandler = logHandler ?? DefaultLogHandler; _codeContextStack = new Stack <ICodeContext>(); _metadataReferenceManager = new MetadataReferenceManager(); AddNamespaceFor(typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)); AddNamespaceFor(typeof(DynamicObject)); AddNamespaceFor(typeof(string)); AddNamespaceFor(baseType); AddNamespaceFor(modelType); AddNamespaceFor(typeof(TemplateState <object>)); AddNamespaceFor(typeof(Dictionary <string, object>)); _namespace = SF.NamespaceDeclaration(SF.IdentifierName(templateNamespace)); _codeContext = new ClassContext(templateName, baseType, modelType, (classDeclaration) => { _namespace = _namespace.AddMembers(classDeclaration); List <UsingDirectiveSyntax> usingDirectives = new List <UsingDirectiveSyntax>(); foreach (var namespaceName in _usingNamespaces) { //usingDirectives.Add(SF.UsingDirective(SF.IdentifierName(namespaceName))); } _compilationUnit = SF.CompilationUnit(); //.AddUsings(usingDirectives.ToArray()); _compilationUnit = _compilationUnit.AddMembers(_namespace); }); }
public SymbolicMemoryState(SeparatedSyntaxList <ParameterSyntax> parameters) { Variables = new Dictionary <string, ExpressionSyntax>(); foreach (var p in parameters) { Variables.Add(p.Identifier.Text, SF.IdentifierName(p.Identifier)); } }
public static InvocationExpressionSyntax ToNameof(this string name) { return(SF.InvocationExpression( SF.IdentifierName("nameof")) .WithArgumentList( SF.ArgumentList( SF.SingletonSeparatedList <ArgumentSyntax>( SF.Argument( SF.IdentifierName("C")))))); }
public ExpressionSyntax?BuildArgumentListWithOriginalNames() { if (Count == 0) { return(null); } return(IsMultiDimensional ? (ExpressionSyntax)F.TupleExpression(F.SeparatedList(this.Select(a => F.Argument(F.IdentifierName(a.OriginalName))).ToArray())) : F.IdentifierName(this[0].OriginalName)); }
/// <inheritdoc /> public override ClassDeclarationSyntax Apply(ClassDeclarationSyntax node, INamedTypeSymbol symbol, CancellationToken cancellationToken) { var parameters = ImmutableArray.CreateBuilder <ParameterSyntax>(); var arguments = ImmutableArray.CreateBuilder <ArgumentSyntax>(); var ctorStmts = ImmutableArray.CreateBuilder <StatementSyntax>(); // Generate all parameters and statements var members = symbol.GetMembers(); for (int i = 0; i < members.Length; i++) { IPropertySymbol member = members[i] as IPropertySymbol; if (member == null || !member.IsReadOnly || !member.CanBeReferencedByName) { continue; } // Read-only prop, we good string propName = member.Name; string paramName = $"{char.ToLower(propName[0]).ToString()}{propName.Substring(1)}"; TypeSyntax paramType = ((PropertyDeclarationSyntax)member.DeclaringSyntaxReferences[0] .GetSyntax(cancellationToken)).Type; MemberAccessExpressionSyntax propAccess = F.MemberAccessExpression( K.SimpleMemberAccessExpression, F.ThisExpression(), F.IdentifierName(propName) ); // Make parameter & argument parameters.Add(F.Parameter(F.Identifier(paramName)).WithType(paramType)); arguments.Add(F.Argument(propAccess)); // Make ctor stmt ctorStmts.Add(F.ExpressionStatement( F.AssignmentExpression(K.SimpleAssignmentExpression, propAccess, F.IdentifierName(paramName) ) )); } // The ctor is full, make all the 'with' methods TypeSyntax returnType = F.IdentifierName(symbol.Name); MemberDeclarationSyntax[] additionalMethods = new MemberDeclarationSyntax[parameters.Count + 1]; arguments.Capacity = arguments.Count; ImmutableArray <ArgumentSyntax> args = arguments.MoveToImmutable(); for (int i = 0; i < parameters.Count; i++) { ParameterSyntax parameter = parameters[i]; string parameterName = parameter.Identifier.Text; ArgumentSyntax name = F.Argument(F.IdentifierName(parameterName)); SeparatedSyntaxList <ArgumentSyntax> allArguments = F.SeparatedList(args.Replace(args[i], name)); StatementSyntax returnStmt = F.ReturnStatement( F.ObjectCreationExpression(returnType).WithArgumentList(F.ArgumentList(allArguments)) ); additionalMethods[i] = F.MethodDeclaration(returnType, $"With{char.ToUpper(parameterName[0]).ToString()}{parameterName.Substring(1)}") .AddModifiers(F.Token(K.PublicKeyword), F.Token(K.NewKeyword)) .AddParameterListParameters(parameter) .AddBodyStatements(returnStmt); } // Add the private ctor additionalMethods[parameters.Count] = F.ConstructorDeclaration(symbol.Name) .AddModifiers(F.Token(K.PrivateKeyword)) .AddParameterListParameters(parameters.ToArray()) .AddBodyStatements(ctorStmts.ToArray()); return(node.AddMembers(additionalMethods)); }
UsingDirectiveSyntax ToUsingDirective(string nameSpace) { return(SF.UsingDirective(SF.IdentifierName(nameSpace)).WithLeadingTrivia()); }