示例#1
0
        private static SyntaxNode Normalize(SyntaxNode root, IEnumerable <SyntaxNode> members, Scope scope)
        {
            var appClass = root
                           .DescendantNodes()
                           .OfType <ClassDeclarationSyntax>()
                           .Where(@class => @class.Identifier.ToString() == "testclass")
                           .FirstOrDefault();

            if (appClass == null)
            {
                appClass = CSharp.ClassDeclaration("testclass");
            }

            return(CSharp.CompilationUnit()
                   .WithMembers(CSharp.List(new[] { (MemberDeclarationSyntax)
                                                    appClass
                                                    .WithMembers(CSharp.List(
                                                                     members.Select(
                                                                         member => {
                    var method = member as MethodDeclarationSyntax;
                    if (method == null)
                    {
                        return member;
                    }

                    return method.WithParameterList(
                        method
                        .ParameterList
                        .AddParameters(CSharp.Parameter(
                                           CSharp.ParseToken("result"))
                                       .WithType(CSharp.ParseTypeName("Dictionary<string, object>"))));
                }))) })));
        }
示例#2
0
        private ExpressionSyntax ReplaceWithMessage(ExpressionSyntax expression, string whichOrAnd, string renameMethod, string prefix = "", string postfix = "")
        {
            var replacements = new[]
            {
                NodeReplacement.Remove(whichOrAnd),
                NodeReplacement.Remove("Message"),
                NodeReplacement.RemoveOccurrence("Should", occurrence: 2)
            };
            var newExpression = GetNewExpression(expression, replacements);
            var rename        = NodeReplacement.RenameAndExtractArguments(renameMethod, "WithMessage");

            newExpression = GetNewExpression(newExpression, rename);

            ArgumentSyntax newArgument = null;

            switch (rename.Arguments[0].Expression)
            {
            case IdentifierNameSyntax identifier:
                newArgument = SF.Argument(SF.ParseExpression($"$\"{prefix}{{{identifier.Identifier.Text}}}{postfix}\""));
                break;

            case LiteralExpressionSyntax literal:
                newArgument = SF.Argument(SF.ParseExpression($"\"{prefix}{literal.Token.ValueText}{postfix}\""));
                break;
            }

            var replacement = NodeReplacement.WithArguments("WithMessage", rename.Arguments.Replace(rename.Arguments[0], newArgument));

            return(GetNewExpression(newExpression, replacement));
        }
        public static SyntaxNode ArrayCreationExpression(this SyntaxGenerator generator, SyntaxNode type, IEnumerable <SyntaxNode> sizeExpression)
        {
            if (generator.NullLiteralExpression() is CS.ExpressionSyntax)
            {
                CS.TypeSyntax typeSyntax = type as CS.TypeSyntax;
                if (typeSyntax == null)
                {
                    throw new ArgumentException($"Invalid syntax node type; Expected {typeof(CS.TypeSyntax).FullName}.", "type");
                }

                IEnumerable <CS.ExpressionSyntax> csSizeExpressions = sizeExpression.Select(exp => exp as CS.ExpressionSyntax);
                if (csSizeExpressions.Any(exp => exp == null))
                {
                    throw new ArgumentException($"Invalid syntax node type; Expected {typeof(CS.ExpressionSyntax).FullName}.", "sizeExpression");
                }

                return(CSSF.ArrayCreationExpression(
                           CSSF.ArrayType(
                               typeSyntax,
                               CSSF.SingletonList(
                                   CSSF.ArrayRankSpecifier(
                                       CSSF.SeparatedList(csSizeExpressions)
                                       )
                                   )
                               )
                           ));
            }
            else
            {
                throw new ArgumentException("Not a CSharp ExpressionSyntax");
            }
        }
        public static void MapTypeName(this ISymbolMap symbols, string fullyQualifiedName, string frameworkName, TypeKind kind)
        {
            var proxyName = $"{frameworkName}Proxy";

            switch (kind)
            {
            case TypeKind.Interface:
                var defaultName = frameworkName;

                symbols
                .GetInterfaceProxyName(Arg.Is <InterfaceType>(t => t.FullyQualifiedName == fullyQualifiedName), disambiguate: Arg.Any <bool>())
                .Returns(proxyName);
                symbols
                .GetInterfaceDefaultName(Arg.Is <InterfaceType>(t => t.FullyQualifiedName == fullyQualifiedName), disambiguate: Arg.Any <bool>())
                .Returns(defaultName);
                symbols
                .GetInterfaceProxyNameSyntaxToken(Arg.Is <InterfaceType>(t => t.FullyQualifiedName == fullyQualifiedName), disambiguate: Arg.Any <bool>())
                .Returns(SF.ParseToken(proxyName));
                symbols
                .GetInterfaceDefaultNameSyntaxToken(Arg.Is <InterfaceType>(t => t.FullyQualifiedName == fullyQualifiedName), disambiguate: Arg.Any <bool>())
                .Returns(SF.ParseToken(defaultName));
                symbols
                .GetInterfaceProxyNameSyntax(Arg.Is <InterfaceType>(t => t.FullyQualifiedName == fullyQualifiedName), disambiguate: Arg.Any <bool>())
                .Returns(SF.ParseName(proxyName));
                symbols
                .GetInterfaceDefaultNameSyntax(Arg.Is <InterfaceType>(t => t.FullyQualifiedName == fullyQualifiedName), disambiguate: Arg.Any <bool>())
                .Returns(SF.ParseName(defaultName));

                frameworkName = $"I{frameworkName}";
                break;

            case TypeKind.Class:
                symbols
                .GetAbstractClassProxyName(Arg.Is <ClassType>(t => t.FullyQualifiedName == fullyQualifiedName), disambiguate: Arg.Any <bool>())
                .Returns(proxyName);
                break;
            }

            symbols
            .GetName(Arg.Is <Type>(t => t.FullyQualifiedName == fullyQualifiedName), disambiguate: Arg.Any <bool>())
            .Returns(frameworkName);
            symbols
            .GetName(Arg.Is <string>(fqn => fqn == fullyQualifiedName), disambiguate: Arg.Any <bool>())
            .Returns(frameworkName);
            symbols
            .GetNameSyntaxToken(Arg.Is <Type>(t => t.FullyQualifiedName == fullyQualifiedName), disambiguate: Arg.Any <bool>())
            .Returns(SF.ParseToken(frameworkName));
            symbols
            .GetNameSyntaxToken(Arg.Is <string>(fqn => fqn == fullyQualifiedName), disambiguate: Arg.Any <bool>())
            .Returns(SF.ParseToken(frameworkName));
            symbols
            .GetNameSyntax(Arg.Is <Type>(t => t.FullyQualifiedName == fullyQualifiedName), disambiguate: Arg.Any <bool>())
            .Returns(SF.ParseName(frameworkName));
            symbols
            .GetNameSyntax(Arg.Is <string>(fqn => fqn == fullyQualifiedName), disambiguate: Arg.Any <bool>())
            .Returns(SF.ParseName(frameworkName));
            symbols
            .GetTypeSyntax(Arg.Is <TypeReference>(t => t.FullyQualifiedName == fullyQualifiedName), false)
            .Returns(SF.ParseTypeName(frameworkName));
        }
示例#5
0
        public SyntaxTree CreateSyntaxTree()
        {
            // The call to CreateType must come before the call to namespaces.GetUsings.
            // This is because CreateType builds the list of referenced namespaces.
            MemberDeclarationSyntax typeDeclaration = CreateType();

            if (Type.Docs != null)
            {
                DocCommentGeneratorBase <Type> generator = new TypeDocCommentGenerator(Type);
                SyntaxTriviaList trivia = SF.TriviaList(generator.CreateDocComment());

                typeDeclaration = typeDeclaration.WithLeadingTrivia(trivia);
            }

            NamespaceDeclarationSyntax namespaceDeclaration = SF.NamespaceDeclaration(
                Symbols.GetNamespaceSyntax(Type),
                SF.List <ExternAliasDirectiveSyntax>(),
                SF.List <UsingDirectiveSyntax>(),
                SF.List(new[] { typeDeclaration })
                );

            return(SF.SyntaxTree(
                       SF.CompilationUnit(
                           SF.List <ExternAliasDirectiveSyntax>(),
                           Namespaces.GetUsings(),
                           SF.List <AttributeListSyntax>(),
                           SF.List <MemberDeclarationSyntax>(new[] { namespaceDeclaration })
                           ).NormalizeWhitespace(elasticTrivia: true)
                       ));
        }
示例#6
0
        public static ParameterListSyntax GetParameterListSyntax(this Method method, INamespaceSet namespaces, ISymbolMap symbols)
        {
            method     = method ?? throw new ArgumentNullException(nameof(method));
            namespaces = namespaces ?? throw new ArgumentNullException(nameof(namespaces));
            symbols    = symbols ?? throw new ArgumentNullException(nameof(symbols));

            return(SF.ParameterList(SF.SeparatedList(GetParameters())));

            IEnumerable <ParameterSyntax> GetParameters()
            {
                if (method.Parameters == null)
                {
                    yield break;
                }

                foreach (Parameter parameter in method.Parameters)
                {
                    namespaces.Add(parameter.Type);

                    yield return(SF.Parameter(
                                     SF.List <AttributeListSyntax>(),
                                     SF.TokenList(),
                                     symbols.GetTypeSyntax(parameter.Type),
                                     symbols.GetNameSyntaxToken(parameter),
                                     null
                                     ));
                }
            }
        }
        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);
            }

            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());
        }
示例#9
0
        public void CreatesUsingStatementForType()
        {
            EnumType type = new EnumType
                            (
                "myEnumFqn",
                "myModule",
                "myEnum",
                "myNamespace",
                new EnumMember[] { }
                            );

            Symbols.MapNamespace("myNamespace", "MyNamespace");

            NamespaceSet namespaces = new NamespaceSet(Symbols, SF.ParseName("MyCurrentNamespace"));

            namespaces.Add(type);

            SyntaxList <UsingDirectiveSyntax> usings = namespaces.GetUsings();

            AssertUsings
            (
                usings,
                "using Amazon.JSII.Runtime.Deputy;",
                "using MyNamespace;"
            );
        }
示例#10
0
        public void RecursivelyCreatesUsingStatementForEachTypeInUnionReference()
        {
            NamespaceSet namespaces = new NamespaceSet(Symbols, SF.ParseName("MyCurrentNamespace"));

            namespaces.Add(new TypeReference(union: new UnionTypeReference(new TypeReference[] {
                new TypeReference(collection: new CollectionTypeReference(
                                      CollectionKind.Array,
                                      new TypeReference(collection: new CollectionTypeReference(
                                                            CollectionKind.Array,
                                                            new TypeReference(primitive: PrimitiveType.Json)
                                                            ))
                                      )),
                new TypeReference(primitive: PrimitiveType.Date),
            })));

            SyntaxList <UsingDirectiveSyntax> usings = namespaces.GetUsings();

            AssertUsings
            (
                usings,
                "using Amazon.JSII.Runtime.Deputy;",
                "using Newtonsoft.Json.Linq;",
                "using System;"
            );
        }
示例#11
0
        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 <UsingDirectiveSyntax>(new UsingDirectiveEqualityComparer());

            usings.Add(ToUsingDirective(" System"));
            usings.Add(ToUsingDirective(" System.Runtime.CompilerServices"));
            usings.Add(ToUsingDirective(" 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.ToArray());
            return(Formatter.Format(cu, workspace).ToString());
        }
示例#12
0
        private ExpressionSyntax Simplify(ExpressionSyntax node)
        {
            var expression = VisitExpression(node);

            try
            {
                var stringExpression = GetAsString(expression);
                var value            = CSharpScript.EvaluateAsync(stringExpression).Result;
                switch (value)
                {
                case bool bool_value:
                    return(expression);

                case byte byte_value:
                    return(SF.LiteralExpression(SK.NumericLiteralExpression, SF.Literal(byte_value)));

                case short short_value:
                    return(SF.LiteralExpression(SK.NumericLiteralExpression, SF.Literal(short_value)));

                case int int_value:
                    return(SF.LiteralExpression(SK.NumericLiteralExpression, SF.Literal(int_value)));

                case long long_value:
                    return(SF.LiteralExpression(SK.NumericLiteralExpression, SF.Literal(long_value)));

                default:
                    throw new NotImplementedException($"Unsupported type: {value.GetType().Name}.");
                }
            }
            catch (Exception)
            {
                return(expression);
            }
        }
示例#13
0
 public static StatementSyntax[] ToStatments(this string code)
 {
     return(code
            .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
            .Select(o => SF.ParseStatement(o))
            .ToArray());
 }
        IEnumerable <XmlNodeSyntax> GetParamsNodes()
        {
            if (Documentable.Parameters == null)
            {
                yield break;
            }

            foreach (Parameter parameter in Documentable.Parameters.Where(p => p.Docs != null))
            {
                string text = string.Join(Environment.NewLine, GetParamTextLines(parameter));
                if (!string.IsNullOrEmpty(text))
                {
                    yield return(SF.XmlText(" ").WithLeadingTrivia(SF.DocumentationCommentExterior(" ")));

                    yield return(SF.XmlParamElement(_symbols.GetName(parameter), GetXmlNodes(text).ToArray()));
                }
            }

            IEnumerable <string> GetParamTextLines(Parameter parameter)
            {
                if (!String.IsNullOrEmpty(parameter.Docs.Summary))
                {
                    yield return(parameter.Docs.Summary);
                }
            }
        }
 public override SyntaxList <CSSyntax.StatementSyntax> DefaultVisit(SyntaxNode node)
 {
     try {
         return(ConvertWithTrivia(node));
     } catch (Exception e) {
         return(SyntaxFactory.SingletonList(CreateErrorCommentStatement(node, e)));
     }
 }
示例#16
0
文件: Usage.cs 项目: zihotki/Excess
 private SyntaxNode typeExtension(SyntaxNode node, SyntacticalExtension <SyntaxNode> extension)
 {
     return(CSharp.ClassDeclaration(extension.Identifier)
            .WithMembers(CSharp.List <MemberDeclarationSyntax>(new[] {
         CSharp.MethodDeclaration(CSharp.ParseTypeName("int"), "myMethod")
         .WithBody((BlockSyntax)extension.Body)
     })));
 }
示例#17
0
 private ExpressionSyntax MaybeReplaceLambda(LambdaExpressionSyntax node)
 {
     if (_lambdaNumbersDict.TryGetValue(node, out var index))
     {
         return(SyntaxFactory.IdentifierName($"lambda__{index}"));
     }
     return(null);
 }
示例#18
0
        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);
            });
        }
示例#19
0
        public GeneratorTestBase()
        {
            Symbols    = Substitute.For <ISymbolMap>();
            Namespaces = Substitute.For <INamespaceSet>();

            Symbols
            .GetTypeSyntax(Arg.Is <TypeReference>(t => t.Primitive == PrimitiveType.String && t.IsOptional != true))
            .Returns(SF.ParseTypeName("string"));
        }
示例#20
0
        public static SyntaxToken GetParametersJsonSyntaxToken(this Method method)
        {
            // Strip docs before serializing.
            Parameter[] parameters = (method?.Parameters ?? Enumerable.Empty <Parameter>())
                                     .Select(p => new Parameter(p.Name, p.Type))
                                     .ToArray();

            return(SF.Literal(JsonConvert.SerializeObject(parameters)));
        }
示例#21
0
        public override ClassDeclarationSyntax Generate()
        {
            var decl = SF.ClassDeclaration(Basics.GenerateSerializerName(ClassSymbol));

            decl = decl.WithTypeParameterList(GetTypeParametersList());
            return(decl.WithBaseList(SF.BaseList(GetBaseList()))
                   .WithMembers(GenerateStaticNamesSpans())
                   .AddMembers(DeclareTryParseMethod()));
        }
        private CSSyntax.StatementSyntax CreateErrorCommentStatement(SyntaxNode node, Exception exception)
        {
            var errorDescription = node.DescribeConversionError(exception);
            var commentedText    = "/* " + errorDescription + " */";

            return(SyntaxFactory.EmptyStatement()
                   .WithTrailingTrivia(SyntaxFactory.Comment(commentedText))
                   .WithAdditionalAnnotations(new SyntaxAnnotation(AnnotationConstants.ConversionErrorAnnotationKind, exception.ToString())));
        }
示例#23
0
 public TypeDeclarationSyntax Build()
 {
     var res = (_kind switch
     {
         Kind.Class => (TypeDeclarationSyntax)SF.ClassDeclaration(_name),
         Kind.Interface => SF.InterfaceDeclaration(_name),
         Kind.Struct => SF.StructDeclaration(_name),
         _ => throw new InvalidOperationException()
     }).WithModifiers(_modifiers.Build())
示例#24
0
        public SymbolicMemoryState(SeparatedSyntaxList <ParameterSyntax> parameters)
        {
            Variables = new Dictionary <string, ExpressionSyntax>();

            foreach (var p in parameters)
            {
                Variables.Add(p.Identifier.Text, SF.IdentifierName(p.Identifier));
            }
        }
示例#25
0
        public BracketedParameterListSyntax?BuildParameterList()
        {
            if (Count == 0)
            {
                return(null);
            }

            return(F.BracketedParameterList(F.SeparatedList(this.Select(a => F.Parameter(F.Identifier(a.TupleSafeName)).WithType(a.Type)))));
        }
示例#26
0
        public static void True(bool expression)
        {
            ExpressionSyntax expr = GetExpression();

            CallBinder.StatementSyntax = MakeThrowSyntax(
                expr.GetLocation(),
                F.PrefixUnaryExpression(K.LogicalNotExpression, F.ParenthesizedExpression(expr)),
                "Expected expression to be true.", expr.ToString()
                );
        }
示例#27
0
        public static void NotNull(object expression)
        {
            ExpressionSyntax expr = GetExpression();

            CallBinder.StatementSyntax = MakeThrowSyntax(
                expr.GetLocation(),
                F.BinaryExpression(K.EqualsExpression, expr, F.LiteralExpression(K.NullLiteralExpression)),
                "Expected expression to be non-null.", expr.ToString()
                );
        }
示例#28
0
        public override TypeArgumentListSyntax GetInterfaceParameters()
        {
            var genericsParameters = new SeparatedSyntaxList <TypeSyntax>();

            for (var index = 0; index < ClassSymbol.TypeArguments.Length; index++)
            {
                genericsParameters = genericsParameters.Add(SF.ParseTypeName(ClassSymbol.TypeArguments[index].ToString()));
            }
            return(SF.TypeArgumentList().AddArguments(SF.GenericName(ClassDecl.FullName).WithTypeArgumentList(SF.TypeArgumentList(genericsParameters))));
        }
 public override SyntaxList <CSSyntax.StatementSyntax> DefaultVisit(SyntaxNode node)
 {
     try {
         return(ConvertWithTrivia(node));
     } catch (Exception e) {
         var withTrailingErrorComment = SyntaxFactory.EmptyStatement()
                                        .WithCsTrailingErrorComment <CSSyntax.StatementSyntax>((VisualBasicSyntaxNode)node, e);
         return(SyntaxFactory.SingletonList(withTrailingErrorComment));
     }
 }
示例#30
0
 public static InvocationExpressionSyntax ToNameof(this string name)
 {
     return(SF.InvocationExpression(
                SF.IdentifierName("nameof"))
            .WithArgumentList(
                SF.ArgumentList(
                    SF.SingletonSeparatedList <ArgumentSyntax>(
                        SF.Argument(
                            SF.IdentifierName("C"))))));
 }