コード例 #1
0
ファイル: MethodAnalisysWalker.cs プロジェクト: meogol/Diplom
        /// <summary>
        /// токены- имена филдов. соответственно первый зависит от последнего.
        /// Так же берем параметр первого объекта, и запоминаем его имя.
        /// переменные fild...хранят имена переменных
        /// переменные nameFild... хранят названия типов
        /// </summary>
        /// <param name="node">узел представляет строку операции(fild1.fild2 = fild2;) разбивается на токены, которые мы запоминаем</param>
        public override void VisitExpressionStatement(ExpressionStatementSyntax node)
        {
            var nameFilds = node.DescendantNodes().OfType <IdentifierNameSyntax>().ToList();

            if (nameFilds.Count() == 3)
            {
                var fildOne      = nameFilds[0];
                var fildOneParam = nameFilds[1];
                var fildTwo      = nameFilds[2];


                string nameFildOne = GetInterfacesNames(model, fildOne);
                string nameFildTwo = GetInterfacesNames(model, fildTwo);

                if (nameFildOne != null && nameFildTwo != null)
                {
                    ParamInfo paramInfo = new ParamInfo(fildTwo.ToString(), fildOneParam.ToString(), nameFildTwo);

                    if (entityInfo.lFieldInfo.Where(f => f.Name == fildOne.ToString()).LastOrDefault() != null)
                    {
                        entityInfo.lFieldInfo.Where(f => f.Name == fildOne.ToString()).LastOrDefault().lParamInfo.Add(paramInfo);
                    }

                    var fieldInfo = new FieldInfo(fildOne.ToString(), nameFildOne);
                    fieldInfo.lParamInfo.Add(paramInfo);
                    entityInfo.lFieldInfo.Add(fieldInfo);

                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    System.IO.StreamWriter textFile = new System.IO.StreamWriter(@projectPath + "text.txt", true);
                    textFile.WriteLine(nameFildOne + " зависит от " + nameFildTwo);
                    textFile.Close();
                }
            }
        }
        private async Task <Solution> AddIsEnabledGuardAsync(Document document, ExpressionStatementSyntax expression,
                                                             CancellationToken cancellationToken)
        {
            var memberAccessExpression = expression.DescendantNodes().OfType <MemberAccessExpressionSyntax>().First();

            if (memberAccessExpression.Expression is IdentifierNameSyntax identifierNameSyntax)
            {
                if (expression.Expression is InvocationExpressionSyntax invocation)
                {
                    var leadingTrivia = expression.GetLeadingTrivia();
                    var arg           = invocation.ArgumentList.Arguments.First();
                    var source        = identifierNameSyntax.Identifier.Text;
                    var isEnabled     =
                        SyntaxFactory.ParseExpression($"{source}.IsEnabled()") as InvocationExpressionSyntax;
                    isEnabled = isEnabled.ReplaceNode(isEnabled.ArgumentList, isEnabled.ArgumentList.AddArguments(arg));
                    SyntaxFactory.Token(SyntaxKind.IfKeyword);
                    var ifStatement = SyntaxFactory.IfStatement(
                        SyntaxFactory.Token(SyntaxKind.IfKeyword),
                        SyntaxFactory.Token(SyntaxKind.OpenParenToken),
                        isEnabled,
                        SyntaxFactory.Token(SyntaxKind.CloseParenToken).WithTrailingTrivia(NewLine),
                        Indent(expression), null).WithLeadingTrivia(leadingTrivia);

                    // Produce a new solution that has all references to that type renamed, including the declaration.
                    var originalSolution = document.Project.Solution;
                    var syntaxRoot       = await document.GetSyntaxRootAsync(cancellationToken);

                    syntaxRoot = syntaxRoot.ReplaceNode(expression, ifStatement);
                    var newSolution = originalSolution.WithDocumentSyntaxRoot(document.Id, syntaxRoot);
                    return(newSolution);
                }
            }

            return(document.Project.Solution);
        }
コード例 #3
0
        private void ProcessConstant(
            ExpressionStatementSyntax expressionNode,
            GenericNameSyntax bindGenericNode,
            ArgumentSyntax?whenArgumentClause
            )
        {
            var genericNodes = expressionNode
                               .DescendantNodes()
                               .OfType <GenericNameSyntax>()
                               .ToList();


            var withScopeSyntax = expressionNode
                                  .DescendantNodes()
                                  .Where(s => s.GetText().ToString() == nameof(IToOrConstantBinding.WithConstScope))
                                  .First();

            var constTypeSymbol = (_semanticModel.GetSymbolInfo(withScopeSyntax).Symbol as IMethodSymbol) !.TypeArguments[0];

            var constantClause = DetermineArgumentSubClause(
                expressionNode,
                nameof(IToOrConstantBinding.WithConstScope)
                );

            if (constantClause is null)
            {
                throw new DpdtException(DpdtExceptionTypeEnum.InternalError, $"Cannot find constant clause");
            }

            var bindFromTypeSemantics = GetBindFromTypes(
                bindGenericNode
                );

            var bindingContainer = new ConstantBindingContainer(
                bindFromTypeSemantics,
                constTypeSymbol,
                constantClause,
                BindScopeEnum.Constant,
                whenArgumentClause
                );

            _bindingContainers.Add(bindingContainer);
        }
コード例 #4
0
        public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node)
        {
            var        newNode      = base.VisitExpressionStatement(node);
            SyntaxNode modifiedNode = newNode;

            var invocationExpressionNodes = node.DescendantNodes().OfType <InvocationExpressionSyntax>().ToList();

            if (invocationExpressionNodes.Count <= 0)
            {
                return(newNode);
            }
            var invocationExpressionNode = invocationExpressionNodes.First();

            var symbol = SemanticHelper.GetSemanticSymbol(invocationExpressionNode, _semanticModel, _preportSemanticModel);

            if (symbol == null)
            {
                return(newNode);
            }
            var nodeKey = symbol.OriginalDefinition.ToString();

            foreach (var action in _allActions.OfType <ExpressionAction>())
            {
                if (nodeKey == action.Key)
                {
                    var actionExecution = new GenericActionExecution(action, _filePath)
                    {
                        TimesRun = 1
                    };
                    try
                    {
                        modifiedNode = action.ExpressionActionFunc(_syntaxGenerator, newNode);
                        LogHelper.LogInformation(string.Format("{0}: {1}", node.SpanStart, action.Description));
                    }
                    catch (Exception ex)
                    {
                        var actionExecutionException = new ActionExecutionException(action.Name, action.Key, ex);
                        actionExecution.InvalidExecutions = 1;
                        LogHelper.LogError(actionExecutionException);
                    }
                    allExecutedActions.Add(actionExecution);
                }
            }
            return(modifiedNode);
        }
コード例 #5
0
        private ArgumentSyntax?DetermineArgumentSubClause(
            ExpressionStatementSyntax expressionNode,
            string identifierName
            )
        {
            if (expressionNode is null)
            {
                throw new ArgumentNullException(nameof(expressionNode));
            }

            if (identifierName is null)
            {
                throw new ArgumentNullException(nameof(identifierName));
            }

            var ednodes = expressionNode
                          .DescendantNodes()
                          .ToList()
            ;

            var index = ednodes.FindIndex(n =>
                                          n is IdentifierNameSyntax ins &&
                                          ins.Identifier.Text == identifierName
                                          );

            if (index < 0)
            {
                return(null);
            }
            if (ednodes.Count == index + 1)
            {
                return(null);
            }

            var ai = ednodes[index + 1];

            if (ai is not ArgumentListSyntax als)
            {
                return(null);
            }

            var argument0 = als.Arguments[0];

            return(argument0);
        }
コード例 #6
0
        private BindScopeEnum DetermineScope(
            ExpressionStatementSyntax expressionNode
            )
        {
            var dnodes = expressionNode
                         .DescendantNodes()
                         .ToList()
            ;

            var singletonScope = dnodes.OfType <IdentifierNameSyntax>().Any(j => j.Identifier.Text == nameof(IScopeBinding.WithSingletonScope));

            if (singletonScope)
            {
                return(BindScopeEnum.Singleton);
            }

            var transientScope = dnodes.OfType <IdentifierNameSyntax>().Any(j => j.Identifier.Text == nameof(IScopeBinding.WithTransientScope));

            if (transientScope)
            {
                return(BindScopeEnum.Transient);
            }

            var constScope = dnodes.OfType <IdentifierNameSyntax>().Any(j => j.Identifier.Text == nameof(IToOrConstantBinding.WithConstScope));

            if (constScope)
            {
                return(BindScopeEnum.Constant);
            }

            var customScope = dnodes.OfType <IdentifierNameSyntax>().Any(j => j.Identifier.Text == nameof(IScopeBinding.WithCustomScope));

            if (customScope)
            {
                return(BindScopeEnum.Custom);
            }

            throw new InvalidOperationException("unknown scope");
        }
コード例 #7
0
        /// <summary>
        /// токены- имена филдов. соответственно первый зависит от последнего.
        /// Так же берем параметр первого объекта, и запоминаем его имя.
        /// переменные Namefild...хранят имена переменных
        /// переменные TypeFild... хранят названия типов
        /// </summary>
        /// <param name="node">узел представляет строку операции(fild1.fild2 = fild2;) разбивается на токены, которые мы запоминаем</param>
        public override void VisitExpressionStatement(ExpressionStatementSyntax node)
        {
            var nameFilds = node.DescendantNodes().OfType <IdentifierNameSyntax>().ToList();

            if (nameFilds.Count() != 3)
            {
                return;
            }

            var NameFildOne      = nameFilds[0];
            var NameFildOneParam = nameFilds[1];
            var NameFildTwo      = nameFilds[2];

            if (!CheckRealizeInterfase(typeof(IField), NameFildOne) && !CheckRealizeInterfase(typeof(IField), NameFildTwo))
            {
                //if (!CheckRealizeInterfase(typeof(IFieldList), NameFildOne) && !CheckRealizeInterfase(typeof(IFieldList), NameFildTwo))
                return;
            }

            var TypeFildOne = sModel.GetTypeInfo(NameFildOne).Type.Name;
            var TypeFildTwo = sModel.GetTypeInfo(NameFildTwo).Type.Name;

            ParamInfo paramInfo = new ParamInfo(NameFildTwo.ToString(), NameFildOneParam.ToString(), TypeFildTwo);

            FieldInfo fieldInfo;

            if (entityInfo.lFieldInfo.TryGetValue(NameFildOne.ToString(), out fieldInfo))
            {
                fieldInfo.lParamInfo.RemoveAll(p => p.ParamName == NameFildOneParam.ToString());
                fieldInfo.lParamInfo.Add(paramInfo);
            }
            else
            {
                fieldInfo = new FieldInfo(NameFildOne.ToString(), TypeFildOne);
                fieldInfo.lParamInfo.Add(paramInfo);
                entityInfo.lFieldInfo.Add(NameFildOne.ToString(), fieldInfo);
            }
        }
コード例 #8
0
        public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax expressionNode)
        {
            if (expressionNode is null)
            {
                throw new ArgumentNullException(nameof(expressionNode));
            }

            var genericNodes = expressionNode
                               .DescendantNodes()
                               .OfType <GenericNameSyntax>()
                               .ToList();

            if (genericNodes.Count == 0)
            {
                return(base.VisitExpressionStatement(expressionNode) !);
            }

            var bindGenericNode = genericNodes[0];
            var bindMethodName  = bindGenericNode.Identifier.Text;

            if (bindMethodName != "Bind")
            {
                return(base.VisitExpressionStatement(expressionNode) !);
            }

            var expressionText = expressionNode.GetText().ToString();

            if (!expressionText.Contains(nameof(IToOrConstantBinding.WithConstScope)))
            {
                if (!expressionText.Contains(nameof(IScopeBinding.WithSingletonScope)))
                {
                    if (!expressionText.Contains(nameof(IScopeBinding.WithTransientScope)))
                    {
                        if (!expressionText.Contains(nameof(IScopeBinding.WithCustomScope)))
                        {
                            return(base.VisitExpressionStatement(expressionNode) !);
                        }
                    }
                }
            }

            //looks like we found what we want

            var scope = DetermineScope(expressionNode);

            var whenArgumentClause = DetermineArgumentSubClause(
                expressionNode,
                nameof(IConditionalBinding.When)
                );

            switch (scope)
            {
            case BindScopeEnum.Singleton:
                ProcessSingleton(
                    expressionNode,
                    bindGenericNode,
                    whenArgumentClause
                    );
                break;

            case BindScopeEnum.Transient:
                ProcessTransient(
                    expressionNode,
                    bindGenericNode,
                    whenArgumentClause
                    );
                break;

            case BindScopeEnum.Custom:
                ProcessCustom(
                    expressionNode,
                    bindGenericNode,
                    whenArgumentClause
                    );
                break;

            case BindScopeEnum.Constant:
                ProcessConstant(
                    expressionNode,
                    bindGenericNode,
                    whenArgumentClause
                    );
                break;

            default:
                throw new DpdtException(DpdtExceptionTypeEnum.UnknownScope, $"Unknown scope {scope}");
            }

            return(expressionNode);
        }
コード例 #9
0
        private void ProcessCustom(
            ExpressionStatementSyntax expressionNode,
            GenericNameSyntax bindGenericNode,
            ArgumentSyntax?whenArgumentClause
            )
        {
            var genericNodes = expressionNode
                               .DescendantNodes()
                               .OfType <GenericNameSyntax>()
                               .ToList();

            var toGenericNode = genericNodes[1];
            var toMethodName  = toGenericNode.Identifier.Text;

            if (toMethodName.NotIn(nameof(IToOrConstantBinding.To), nameof(IToOrConstantBinding.ToFactory)))
            {
                throw new DpdtException(DpdtExceptionTypeEnum.InternalError, "Cannot find To clause for custom binding");
            }

            var factoryPayloadSemantic = GetFactoryPayloadIfExists(
                toGenericNode
                );

            var bindFromTypeSemantics = GetBindFromTypes(
                bindGenericNode
                );

            var bindToSyntax       = toGenericNode.TypeArgumentList.Arguments.First();
            var bindToTypeSemantic = _semanticModel.GetTypeInfo(bindToSyntax).Type;

            if (bindToTypeSemantic == null)
            {
                throw new DpdtException(
                          DpdtExceptionTypeEnum.InternalError,
                          $"Unknown problem to access {nameof(bindToTypeSemantic)}"
                          );
            }

            CheckForFromAndToTypes(
                bindFromTypeSemantics,
                bindToTypeSemantic,
                !(factoryPayloadSemantic is null)
                );

            var fullBindToTypeName = _typeInfoProvider.GetTypeByMetadataName(bindToTypeSemantic.ToDisplayString());

            if (fullBindToTypeName == null)
            {
                throw new DpdtException(
                          DpdtExceptionTypeEnum.InternalError,
                          $"Unknown problem to access type for {bindToTypeSemantic.ToDisplayString()}"
                          );
            }

            var caExtractor = new ConstructorArgumentExtractor(
                _typeInfoProvider,
                _semanticModel
                );

            caExtractor.Visit(expressionNode);

            var constructorArguments = GetConstructorArguments(
                caExtractor,
                fullBindToTypeName
                );

            var bindingContainer = new BindingContainerWithInstance(
                bindFromTypeSemantics,
                bindToTypeSemantic,
                constructorArguments,
                BindScopeEnum.Custom,
                whenArgumentClause,
                factoryPayloadSemantic
                );

            _bindingContainers.Add(bindingContainer);
        }