public Tristate EvaluateExpression(CSharpSyntaxNode expression)
        {
            var it = _expressionEvaluators.GetEnumerator();

            if (!it.MoveNext())
            {
                Debug.Assert(false, "We should have at least one expression evaluator");
            }

            Tristate result = expression.Accept(it.Current);

            if (result == Tristate.Varying)
            {
                return(Tristate.Varying);
            }

            while (it.MoveNext())
            {
                if (expression.Accept(it.Current) != result)
                {
                    return(Tristate.Varying);
                }
            }

            return(result);
        }
        public static List <ApexMemberDeclarationSyntax> GetApexSyntaxNodes(CSharpSyntaxNode node)
        {
            var builder = new ApexSyntaxBuilder();

            node?.Accept(builder);
            return(builder.ApexClasses);
        }
Beispiel #3
0
        private void AnalyzeCodeBlock(CodeBlockAnalysisContext context, PXContext pxContext)
        {
            context.CancellationToken.ThrowIfCancellationRequested();

            // Get body from a method or property
            CSharpSyntaxNode body = context.CodeBlock?.GetBody();

            if (body == null)
            {
                return;
            }

            // Collect all PXGraph-typed method parameters passed to BQL queries
            var walker = new BqlGraphArgWalker(context.SemanticModel, pxContext);

            body.Accept(walker);
            if (walker.GraphArguments.IsEmpty)
            {
                return;
            }

            // Collect all available PXGraph instances (@this, method parameters, local variables)
            var existingGraphs = GetExistingGraphInstances(body, context.SemanticModel, pxContext);

            if (existingGraphs.IsEmpty)
            {
                return;
            }

            // Determine if available PXGraph instance is used outside of BQL queries
            var usedGraphs = GetSymbolUsages(body, existingGraphs, context.SemanticModel, walker.GraphArguments)
                             .ToImmutableHashSet();
            var availableGraphs = existingGraphs.Except(usedGraphs).ToArray();

            // Analyze each PXGraph-typed parameter in BQL queries
            foreach (var graphArgSyntax in walker.GraphArguments)
            {
                var instantiationType = graphArgSyntax.GetGraphInstantiationType(context.SemanticModel, pxContext);

                // New PXGraph() / new TGraph() / PXGraph.CreateInstance<TGraph> are reported at all times
                // All other usages are reported only if:
                // 1. There is at least one existing PXGraph instance available
                // 2. PXGraph parameter is not used in any way because its modifications might affect the BQL query results
                if (instantiationType != GraphInstantiationType.None)
                {
                    context.ReportDiagnosticWithSuppressionCheck(Diagnostic.Create(Descriptors.PX1072_PXGraphCreationForBqlQueries,
                                                                                   graphArgSyntax.GetLocation(),
                                                                                   CreateDiagnosticProperties(availableGraphs, pxContext)),
                                                                 pxContext.CodeAnalysisSettings);
                }
                else if (availableGraphs.Length > 0 && context.SemanticModel.GetSymbolInfo(graphArgSyntax).Symbol is ILocalSymbol localVar &&
                         !usedGraphs.Contains(localVar))
                {
                    context.ReportDiagnosticWithSuppressionCheck(Diagnostic.Create(Descriptors.PX1072_PXGraphCreationForBqlQueries,
                                                                                   graphArgSyntax.GetLocation(),
                                                                                   CreateDiagnosticProperties(availableGraphs.Where(g => !Equals(g, localVar)), pxContext)),
                                                                 pxContext.CodeAnalysisSettings);
                }
            }
        }
 private static void VisitFilterLambdaExpression(CSharpSyntaxNode body, StringBuilder sb,
                                                 string lambdaParamter, ServiceCodeGenerator visitor)
 {
     visitor.cqlFilterLambdaParameter = lambdaParamter;
     sb.Append(body.Accept(visitor));
     visitor.cqlFilterLambdaParameter = null;
 }
Beispiel #5
0
        public static MultiDictionary <Info, Object> ExtractInfo(CSharpSyntaxNode node)
        {
            InfoExtractor ext = new InfoExtractor(node);

            node.Accept(ext);
            return(ext.Information);
        }
Beispiel #6
0
        public static bool HasClosedVariables(CSharpSyntaxNode node)
        {
            var checker = new LambdaClosedVariablesChecker(node);

            node.Accept(checker);
            return(checker.hasClosedVariables);
        }
Beispiel #7
0
        public static ILocalSymbol FirstValidSymbolOccuranceOfVariable(SemanticModel model, CSharpSyntaxNode context, string identifier)
        {
            var outerForLoop     = context.FirstAncestorOrSelf <ForStatementSyntax>();
            var outerCatchClause = context.FirstAncestorOrSelf <CatchClauseSyntax>();
            var foreachLoop      = context.FirstAncestorOrSelf <ForEachStatementSyntax>();
            var usings           = context.FirstAncestorOrSelf <UsingStatementSyntax>();

            if (outerForLoop != null && outerForLoop.Declaration.Variables.Any(x => x.Identifier.ToString() == identifier))
            {
                context = outerForLoop;
            }
            else if (outerCatchClause != null && outerCatchClause.Declaration.Identifier.ToString() == identifier)
            {
                context = outerCatchClause;
            }
            else if (foreachLoop != null && foreachLoop.Identifier.ToString() == identifier)
            {
                context = foreachLoop;
            }
            else if (usings.Declaration.Variables.Any(x => x.Identifier.ToString() == identifier))
            {
                context = usings;
            }
            else
            {
                context = context.FirstAncestorOrSelf <BlockSyntax>();
            }

            var walker = new VariableUsageFinder(model, context, identifier);

            context.Accept(walker);
            return((ILocalSymbol)walker.symbols.FirstOrDefault());
        }
        private LuaExpressionSyntax VisitLambdaExpression(IEnumerable <ParameterSyntax> parameters, CSharpSyntaxNode body)
        {
            IMethodSymbol symbol = (IMethodSymbol)semanticModel_.GetSymbolInfo(body.Parent).Symbol;

            methodInfos_.Push(new MethodInfo(symbol));

            LuaFunctionExpressionSyntax function = new LuaFunctionExpressionSyntax();

            PushFunction(function);

            foreach (var parameter in parameters)
            {
                var luaParameter = (LuaParameterSyntax)parameter.Accept(this);
                function.ParameterList.Parameters.Add(luaParameter);
            }

            LuaExpressionSyntax resultExpression = function;

            if (body.IsKind(SyntaxKind.Block))
            {
                var block = (LuaBlockSyntax)body.Accept(this);
                function.AddStatements(block.Statements);
            }
            else
            {
                var type = (INamedTypeSymbol)semanticModel_.GetTypeInfo(body.Parent).ConvertedType;
                var delegateInvokeMethod = type.DelegateInvokeMethod;

                blocks_.Push(function.Body);
                var expression = (LuaExpressionSyntax)body.Accept(this);
                blocks_.Pop();
                if (delegateInvokeMethod.ReturnsVoid)
                {
                    function.AddStatement(expression);
                }
                else
                {
                    function.AddStatement(new LuaReturnStatementSyntax(expression));
                }
            }

            PopFunction();
            methodInfos_.Pop();

            return(resultExpression);
        }
Beispiel #9
0
        public static IList <ExpressionSyntax> Collect(SemanticModel semanticModel, CSharpSyntaxNode block)
        {
            var collected = new List <ExpressionSyntax>();

            block.Accept(new MemberAccessOnValueTypeCollectorVisitor(semanticModel, collected));

            return(collected);
        }
        public LambdaExpressionSyntax ConvertLambdaExpression(AnonymousFunctionExpressionSyntax node, CSharpSyntaxNode body, IEnumerable <ParameterSyntax> parameters, SyntaxTokenList modifiers)
        {
            var symbol        = (IMethodSymbol)ModelExtensions.GetSymbolInfo(_semanticModel, node).Symbol;
            var parameterList = SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Select(p => (Microsoft.CodeAnalysis.VisualBasic.Syntax.ParameterSyntax)p.Accept(_nodesVisitor))));
            LambdaHeaderSyntax      header;
            EndBlockStatementSyntax endBlock;
            SyntaxKind multiLineExpressionKind;
            SyntaxKind singleLineExpressionKind;

            if (symbol.ReturnsVoid)
            {
                header = SyntaxFactory.SubLambdaHeader(SyntaxFactory.List <AttributeListSyntax>(),
                                                       ConvertModifiers(modifiers, TokenContext.Local), parameterList, null);
                endBlock = SyntaxFactory.EndBlockStatement(SyntaxKind.EndSubStatement,
                                                           SyntaxFactory.Token(SyntaxKind.SubKeyword));
                multiLineExpressionKind  = SyntaxKind.MultiLineSubLambdaExpression;
                singleLineExpressionKind = SyntaxKind.SingleLineSubLambdaExpression;
            }
            else
            {
                header = CreateFunctionHeader(modifiers, parameterList, out endBlock, out multiLineExpressionKind);
                singleLineExpressionKind = SyntaxKind.SingleLineFunctionLambdaExpression;
            }

            SyntaxList <StatementSyntax> statements;

            if (body is BlockSyntax block)
            {
                statements = ConvertStatements(block.Statements);
            }
            else if (body.Kind() == CSSyntaxKind.ThrowExpression)
            {
                var csThrowExpression = (ThrowExpressionSyntax)body;
                var vbThrowExpression = (ExpressionSyntax)csThrowExpression.Expression.Accept(_nodesVisitor);
                var vbThrowStatement  = SyntaxFactory.ThrowStatement(SyntaxFactory.Token(SyntaxKind.ThrowKeyword), vbThrowExpression);

                return(SyntaxFactory.MultiLineFunctionLambdaExpression(header,
                                                                       SyntaxFactory.SingletonList <StatementSyntax>(vbThrowStatement), endBlock));
            }
            else
            {
                statements = InsertRequiredDeclarations(
                    SyntaxFactory.SingletonList <StatementSyntax>(
                        SyntaxFactory.ReturnStatement((ExpressionSyntax)body.Accept(_nodesVisitor))),
                    body);
            }

            if (statements.Count == 1 && UnpackExpressionFromStatement(statements[0], out var expression))
            {
                return(SyntaxFactory.SingleLineLambdaExpression(singleLineExpressionKind, header, expression));
            }

            return(SyntaxFactory.MultiLineLambdaExpression(multiLineExpressionKind, header, statements, endBlock));
        }
Beispiel #11
0
        private JsExpression VisitLambdaExpression(ExpressionSyntax node, ParameterSyntax[] parameters, CSharpSyntaxNode body)
        {
            var expressionType = (INamedTypeSymbol)model.GetTypeInfo(node).ConvertedType;
            INamedTypeSymbol delegateType;

            if (Equals(expressionType.OriginalDefinition, Context.Instance.ExpressionGeneric))
            {
                delegateType = (INamedTypeSymbol)expressionType.TypeArguments[0];
            }
            else
            {
                delegateType = expressionType;
            }
            var lambdaParameters = parameters.ToArray();
            var delegateMethod   = (IMethodSymbol)delegateType.GetMembers("Invoke")[0];
//            Compiler.CsCompilation.FindType()
            var lambdaMethods   = Context.Instance.Expression.GetMembers("Lambda").OfType <IMethodSymbol>().ToArray();
            var lambdaMethods2  = lambdaMethods.Where(x => x.TypeParameters.Count() == 1 && x.Parameters.Count() == 2 && Equals(x.Parameters[0].Type, Context.Instance.Expression) && Equals(x.Parameters[1].Type, Context.Instance.ParameterExpressionArray)).ToArray();
            var lambdaMethod    = lambdaMethods2.Single();
            var parameterMethod = Context.Instance.Expression.GetMembers("Parameter").OfType <IMethodSymbol>().Single(x => x.Parameters.Count() == 2 && Equals(x.Parameters[0].Type, Context.Instance.TypeType) && Equals(x.Parameters[1].Type, Context.Instance.String));

            lambdaMethod = lambdaMethod.Construct(delegateType);

            var jsLambda = idioms.InvokeStatic(lambdaMethod);

            // Convert parameters
            var workspace    = new JsBlockStatement();
            var jsParameters = Js.Array();

            for (var i = 0; i < delegateMethod.Parameters.Count(); i++)
            {
                var delegateParameter     = delegateMethod.Parameters[i];
                var lambdaParameter       = lambdaParameters[i];
                var jsParameter           = idioms.InvokeStatic(parameterMethod, idioms.TypeOf(delegateParameter.Type), Js.Primitive(lambdaParameter.Identifier.ToString()));
                var parameterVariableName = "$lambdaparam$" + lambdaParameter.Identifier;
                parameterVariables[lambdaParameter.Identifier.ToString()] = parameterVariableName;

                // Declare a variable to hold the parameter object in the parenthetical's scope
                workspace.Local(parameterVariableName, jsParameter);

                // Add a reference to this variable (a ParameterExpression) as one of the
                // parameters to the lambda.
                jsParameters.Elements.Add(Js.Reference(parameterVariableName));
            }

            var jsBody = body.Accept(this);

            jsLambda.AddArgument(jsBody);
            jsLambda.AddArgument(jsParameters);
            workspace.Return(jsLambda);

            return(idioms.Wrap(workspace));
        }
Beispiel #12
0
 public BaseStateGenerator(Func <BaseStateGenerator, JsTransformer> transformer, CSharpSyntaxNode node, JsBlockStatement stateMachineBody, Idioms idioms, IMethodSymbol method, Action <BaseStateGenerator, JsTransformer> nodeAcceptor = null)
 {
     if (nodeAcceptor == null)
     {
         nodeAcceptor = (stateGenerator, jsTransformer) => node.Accept(stateGenerator);
     }
     this.transformer      = transformer(this);
     this.node             = node;
     this.stateMachineBody = stateMachineBody;
     this.method           = method;
     this.idioms           = idioms;
     this.nodeAcceptor     = nodeAcceptor;
 }
Beispiel #13
0
Datei: Ast.cs Projekt: s0/ql
 public static void Extract(this Context cx, CSharpSyntaxNode node, IExpressionParentEntity parent, int child)
 {
     using (cx.StackGuard)
     {
         try
         {
             node.Accept(new Ast(cx, parent, child));
         }
         catch (System.Exception e)
         {
             cx.ModelError(node, "Exception processing syntax node of type {0}: {1}", node.Kind(), e);
         }
     }
 }
Beispiel #14
0
 public static void Extract(this Context cx, CSharpSyntaxNode node, IExpressionParentEntity parent, int child)
 {
     using (cx.StackGuard)
     {
         try
         {
             node.Accept(new Ast(cx, parent, child));
         }
         catch (System.Exception ex)  // lgtm[cs/catch-of-all-exceptions]
         {
             cx.ModelError(node, $"Exception processing syntax node of type {node.Kind()}: {ex.Message}");
         }
     }
 }
Beispiel #15
0
        void VisitNode(CSharpSyntaxNode node)
        {
            if (node == null)
                return;

            node.Accept(Visitor);

            var children = node.ChildNodes();
            if (children != null)
            {
                foreach (var child in children)
                    VisitNode(child as CSharpSyntaxNode);
            }
        }
Beispiel #16
0
        protected bool HandleLoadAddress(string ilVar, ITypeSymbol symbol, CSharpSyntaxNode parent, OpCode opCode, string symbolName, MemberKind memberKind, string parentName = null)
        {
            if ((symbol.IsValueType && parent.Accept(new UsageVisitor()) == UsageKind.CallTarget) || parent.IsKind(SyntaxKind.AddressOfExpression))
            {
                AddCilInstruction(ilVar, opCode, Context.DefinitionVariables.GetVariable(symbolName, memberKind, parentName).VariableName);
                if (!Context.HasFlag("fixed") && parent.IsKind(SyntaxKind.AddressOfExpression))
                {
                    AddCilInstruction(ilVar, OpCodes.Conv_U);
                }

                return(true);
            }

            return(false);
        }
Beispiel #17
0
        protected StatementSyntax[] CaptureState(CSharpSyntaxNode node, State nextState, State breakState)
        {
            var catchBatch = new State(this, true)
            {
                NextState = nextState
            };
            var oldState = currentState;

            currentState = catchBatch;
            node.Accept(this);
            // If after walking the node, it might leave the current state in an unclosed state.  We want to make sure it's closed.
            if (currentState != breakState && currentState != catchBatch && currentState != nextState && currentState != oldState)
            {
                Close(currentState);
            }
            return(catchBatch.Statements.ToArray());
        }
Beispiel #18
0
        void VisitNode(CSharpSyntaxNode node)
        {
            if (node == null)
            {
                return;
            }

            node.Accept(Visitor);

            var children = node.ChildNodes();

            if (children != null)
            {
                foreach (var child in children)
                {
                    VisitNode(child as CSharpSyntaxNode);
                }
            }
        }
Beispiel #19
0
        public static ILocalSymbol FirstValidSymbolOccuranceOfVariable(SemanticModel model, CSharpSyntaxNode context, string identifier)
        {
            var outerForLoop  = context.FirstAncestorOrSelf<ForStatementSyntax>();
            var outerCatchClause = context.FirstAncestorOrSelf<CatchClauseSyntax>();
            var foreachLoop = context.FirstAncestorOrSelf<ForEachStatementSyntax>();
            var usings = context.FirstAncestorOrSelf<UsingStatementSyntax>();

            if (outerForLoop != null && outerForLoop.Declaration.Variables.Any(x => x.Identifier.ToString() == identifier))
                context = outerForLoop;
            else if (outerCatchClause != null && outerCatchClause.Declaration.Identifier.ToString() == identifier)
                context = outerCatchClause;
            else if (foreachLoop != null && foreachLoop.Identifier.ToString() == identifier)
                context = foreachLoop;
            else if (usings.Declaration.Variables.Any(x => x.Identifier.ToString() == identifier))
                context = usings;
            else
                context = context.FirstAncestorOrSelf<BlockSyntax>();

            var walker = new VariableUsageFinder(model, context, identifier);
            context.Accept(walker);
            return (ILocalSymbol)walker.symbols.FirstOrDefault();
        }
Beispiel #20
0
        public static void NumberOfLines(this Context cx, CSharpSyntaxNode node, IEntity callable)
        {
            var lineCounts = node.Accept(new AstLineCounter());

            cx.Emit(Tuples.numlines(callable, lineCounts));
        }
Beispiel #21
0
 public InfoExtractor(CSharpSyntaxNode node)
 {
     node.Accept(this);
 }
Beispiel #22
0
 public static CSharpSyntaxNode RenameIdentifier(CSharpSyntaxNode node, SyntaxToken renameFrom, SyntaxToken renameTo)
 {
     return (CSharpSyntaxNode)node.Accept(new IdentifierRenamer(renameFrom, renameTo));
 }
Beispiel #23
0
 public static SyntaxNode StripStatements(CSharpSyntaxNode root)
 {
     return(root.Accept(new BreakStatementStripper()));
 }
 public static SyntaxNode StripStatements(CSharpSyntaxNode root)
 {
     return root.Accept(new BreakStatementStripper());
 }
 private StructureComputer(CSharpSyntaxNode node, Node root)
 {
     _roots.Push(root);
     node.Accept(this);
 }
Beispiel #26
0
 void BuildType(CSharpSyntaxNode n)
 {
     n.Accept(new TypeBuilder(this));
 }
Beispiel #27
0
 Builder TraverseNode <Builder>(CSharpSyntaxNode n, Builder builder)
     where Builder : BaseBuilder
 {
     n.Accept(builder);
     return(builder);
 }
Beispiel #28
0
 public static CSharpSyntaxNode RenameIdentifier(CSharpSyntaxNode node, SyntaxToken renameFrom,
                                                 SyntaxToken renameTo)
 {
     return((CSharpSyntaxNode)node.Accept(new IdentifierRenamer(renameFrom, renameTo)));
 }
 protected StatementSyntax[] CaptureState(CSharpSyntaxNode node, State nextState, State breakState)
 {
     var catchBatch = new State(this, true) { NextState = nextState };
     var oldState = currentState;
     currentState = catchBatch;
     node.Accept(this);
     // If after walking the node, it might leave the current state in an unclosed state.  We want to make sure it's closed.
     if (currentState != breakState && currentState != catchBatch && currentState != nextState && currentState != oldState)
     {
         Close(currentState);
     }
     return catchBatch.Statements.ToArray();
 }
Beispiel #30
0
        public static void NumberOfLines(this Context cx, TextWriter trapFile, CSharpSyntaxNode node, IEntity callable)
        {
            var lineCounts = node.Accept(new AstLineCounter());

            trapFile.numlines(callable, lineCounts);
        }