public static Expression Parse(ParmVarDecl param, CSharpParser parser)
        {
            string dump  = param.DumpToString();
            var    lines = dump.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

            if (lines.Length < 2 || MethodsToIgnore.Contains(((CXXMethodDecl)param.DeclContext).Name))
            {
                return(null);
            }

            var defaultValueLine = lines.Last().TrimStart(' ', '-', '\t', '`');
            var words            = defaultValueLine.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            var expressionType   = words[0];

            string     defaultValue;
            Expression expression = null;

            if (expressionType.Contains("Literal"))             //e.g. CXXBoolLiteralExpr, IntegerLiteral, etc
            {
                defaultValue = words.Last();
                if (expressionType.StartsWith("Floating"))                 //numbers come in a format like '1.000000e-01'
                {
                    defaultValue = float.Parse(defaultValue, CultureInfo.InvariantCulture).ToString() + "f";
                }
                if (defaultValue == "0" && dump.Contains("NullToPointer"))
                {
                    defaultValue = "null";
                }
                if (defaultValue == "0f" && dump.Contains("Urho3D::Color"))
                {
                    defaultValue = "default(Urho.Color)";
                }
                if (defaultValue == "'nullptr_t'")
                {
                    defaultValue = "null";
                }

                expression = parser.ParseExpression(defaultValue);
            }
            else if (expressionType == "DeclRefExpr")
            {
                var items = defaultValueLine
                            .Split(new[] { "'" }, StringSplitOptions.RemoveEmptyEntries)
                            .Where(i => !string.IsNullOrWhiteSpace(i))
                            .ToArray();
                defaultValue = $"{items[items.Length - 2]}";

                var  type      = items.Last();
                var  clearType = type.DropConst().DropClassOrStructPrefix().DropUrhoNamespace();
                bool isEnum    = type.Contains("enum ");

                expression = parser.ParseExpression(RemapValue(clearType, isEnum, defaultValue));
            }

            return(expression);
        }
Exemple #2
0
        public override ValidationResult ValidateExpression(EvaluationContext ctx, string expression)
        {
            expression = expression.Trim();

            if (expression.Length > 0 && expression[0] == '?')
            {
                expression = expression.Substring(1).TrimStart();
            }

            if (expression.Length > 3 && expression.StartsWith("var", StringComparison.Ordinal) && char.IsWhiteSpace(expression[3]))
            {
                expression = expression.Substring(4).TrimStart();
            }

            expression = ReplaceExceptionTag(expression, ctx.Options.CurrentExceptionTag);

            // Required as a workaround for a bug in the parser (it won't parse simple expressions like numbers)
            if (!expression.EndsWith(";", StringComparison.Ordinal))
            {
                expression += ";";
            }

            var parser = new CSharpParser();

            parser.ParseExpression(expression);

            if (parser.HasErrors)
            {
                return(new ValidationResult(false, parser.Errors.First().Message));
            }

            return(new ValidationResult(true, null));
        }
Exemple #3
0
        private List <IndexData> ParseIndexesAndGetReadyToMerge()
        {
            var parser  = new CSharpParser();
            var indexes = new List <IndexData>();

            foreach (var kvp in indexDefinitions)
            {
                var index     = kvp.Value;
                var indexData = new IndexData(index)
                {
                    IndexId     = index.IndexId,
                    IndexName   = index.Name,
                    OriginalMap = index.Map,
                };

                indexes.Add(indexData);

                if (index.IsMapReduce || index.Maps.Count > 1)
                {
                    indexData.IsMapReduceOrMultiMap = true;
                    continue;
                }

                indexData.OriginalMap = IndexPrettyPrinter.Format(indexData.OriginalMap);
                Expression map     = parser.ParseExpression(indexData.OriginalMap);
                var        visitor = new IndexVisitor(indexData);
                map.AcceptVisitor(visitor);
            }
            return(indexes);
        }
Exemple #4
0
        public ResolveResult ResolveSnippet(ParseInformation parseInfo, TextLocation location, string codeSnippet, ICompilation compilation, CancellationToken cancellationToken)
        {
            var csParseInfo = parseInfo as CSharpFullParseInformation;

            if (csParseInfo == null)
            {
                throw new ArgumentException("Parse info does not have SyntaxTree");
            }
            CSharpAstResolver contextResolver = new CSharpAstResolver(compilation, csParseInfo.SyntaxTree, csParseInfo.UnresolvedFile);
            var            node = csParseInfo.SyntaxTree.GetNodeAt(location);
            CSharpResolver context;

            if (node != null)
            {
                context = contextResolver.GetResolverStateAfter(node, cancellationToken);
            }
            else
            {
                context = new CSharpResolver(compilation);
            }
            CSharpParser parser = new CSharpParser();
            var          expr   = parser.ParseExpression(codeSnippet);

            if (parser.HasErrors)
            {
                return(new ErrorResolveResult(SpecialType.UnknownType, PrintErrorsAsString(parser.Errors), TextLocation.Empty));
            }
            CSharpAstResolver snippetResolver = new CSharpAstResolver(context, expr);

            return(snippetResolver.Resolve(expr, cancellationToken));
        }
Exemple #5
0
        public LiteralSearchStrategy(params string[] terms)
            : base(terms)
        {
            if (1 == searchTerm.Length)
            {
                var parser = new CSharpParser();
                var pe     = parser.ParseExpression(searchTerm[0]) as PrimitiveExpression;

                if (pe != null && pe.Value != null)
                {
                    TypeCode peValueType = Type.GetTypeCode(pe.Value.GetType());
                    switch (peValueType)
                    {
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                        searchTermLiteralType  = TypeCode.Int64;
                        searchTermLiteralValue = CSharpPrimitiveCast.Cast(TypeCode.Int64, pe.Value, false);
                        break;

                    case TypeCode.Single:
                    case TypeCode.Double:
                    case TypeCode.String:
                        searchTermLiteralType  = peValueType;
                        searchTermLiteralValue = pe.Value;
                        break;
                    }
                }
            }
        }
Exemple #6
0
            public void Run()
            {
                try {
                    if (searchMode == SearchMode_Literal)
                    {
                        if (1 == searchTerm.Length)
                        {
                            CSharpParser        parser = new CSharpParser();
                            PrimitiveExpression pe     = parser.ParseExpression(searchTerm[0]) as PrimitiveExpression;
                            if (pe != null && pe.Value != null)
                            {
                                TypeCode peValueType = Type.GetTypeCode(pe.Value.GetType());
                                switch (peValueType)
                                {
                                case TypeCode.Byte:
                                case TypeCode.SByte:
                                case TypeCode.Int16:
                                case TypeCode.UInt16:
                                case TypeCode.Int32:
                                case TypeCode.UInt32:
                                case TypeCode.Int64:
                                case TypeCode.UInt64:
                                    searchTermLiteralType  = TypeCode.Int64;
                                    searchTermLiteralValue = CSharpPrimitiveCast.Cast(TypeCode.Int64, pe.Value, false);
                                    break;

                                case TypeCode.Single:
                                case TypeCode.Double:
                                case TypeCode.String:
                                    searchTermLiteralType  = peValueType;
                                    searchTermLiteralValue = pe.Value;
                                    break;
                                }
                            }
                        }
                    }

                    foreach (var loadedAssembly in assemblies)
                    {
                        ModuleDefinition module = loadedAssembly.ModuleDefinition;
                        if (module == null)
                        {
                            continue;
                        }
                        CancellationToken cancellationToken = cts.Token;
                        foreach (TypeDefinition type in module.Types)
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            PerformSearch(type);
                        }
                    }
                } catch (OperationCanceledException) {
                    // ignore cancellation
                }
                // remove the 'Searching...' entry
                dispatcher.BeginInvoke(
                    DispatcherPriority.Normal,
                    new Action(delegate { this.Results.RemoveAt(this.Results.Count - 1); }));
            }
        public static bool CheckSyntax(string expression, out Error[] errors)
        {
            var p = new CSharpParser();

            p.ParseExpression(expression);
            errors = p.Errors.ToArray();
            return(!errors.Any());
        }
        string ConvertExpression(string code)
        {
            CSharpParser parser = new CSharpParser();
            var          expr   = parser.ParseExpression(code);

            Assert.IsFalse(parser.HasErrors);
            return(ConvertExpression(expr));
        }
Exemple #9
0
        public void GetNodesBetween()
        {
            var parser = new CSharpParser();
            var expr   = parser.ParseExpression("a*b+c*d");
            var nodes  = expr.GetNodesBetween(1, 3, 1, 6).ToList();

            Assert.AreEqual(new[] { "b", "+", "c" }, nodes.Select(n => n.ToString()).ToList());
        }
Exemple #10
0
        /// <summary>
        /// Construct the OCLExpression corresponding to some CSharp expression included in the model.
        /// Try to create pure OCL, fallback to custom CSharpExpression object if not handled.
        /// </summary>
        /// <param name="relation">The relation containing the expression.</param>
        /// <param name="domainPattern">(optional) The domainPattern containing the expression.</param>
        /// <param name="expressionString">The expression string to parse.</param>
        /// <returns></returns>
        private EssentialOCL.IOclExpression ConstructOCLExpression(QVTRelations.IRelation relation, string expressionString, QVTBase.IPattern pattern, EMOF.IType type)
        {
            // To be able to reuse existing transfos: we consider strings with single quotes as well
            string expressionWithOnlyDoubleQuotes = expressionString.Replace("\'", "\"");

            // We parse using Roslyn
            ExpressionSyntax parsedExpression = CSharpParser.ParseExpression(expressionWithOnlyDoubleQuotes);

            // And we use the expression analysis overload variant
            return(ConstructOCLExpression(relation, parsedExpression, pattern, type));
        }
Exemple #11
0
        private static string[] Translate(string query)
        {
            var parser = new CSharpParser();

            var block = parser.ParseExpression(query);

            var captureQueryParameterNamesVisitor = new CaptureQueryParameterNamesVisitor();

            block.AcceptVisitor(captureQueryParameterNamesVisitor, null);
            return(captureQueryParameterNamesVisitor.QueryParameters.ToArray());
        }
Exemple #12
0
        public static T ParseExpression <T>(string expr, bool expectErrors = false) where T : AstNode
        {
            CSharpParser parser           = new CSharpParser();
            AstNode      parsedExpression = parser.ParseExpression(new StringReader(expr));

            Assert.AreEqual(expectErrors, parser.HasErrors, "HasErrors");
            if (expectErrors && parsedExpression == null)
            {
                return(default(T));
            }
            Type type = typeof(T);

            Assert.IsTrue(type.IsAssignableFrom(parsedExpression.GetType()), String.Format("Parsed expression was {0} instead of {1} ({2})", parsedExpression.GetType(), type, parsedExpression));
            return((T)parsedExpression);
        }
        /*	public ICSharpCode.OldNRefactory.Parser.Errors LastErrors {
         *              get;
         *              private set;
         *      }*/

        public Expression ParseExpression(string expressionText)
        {
            expressionText = expressionText.Trim();
            var        parser = new CSharpParser();
            Expression result = null;

            try {
                using (var reader = new StringReader(expressionText)) {
                    result = parser.ParseExpression(reader) as Expression;
                    result.Remove();
//					LastErrors = parser.Errors;
                }
            } catch (Exception) {
            }
            return(result);
        }
Exemple #14
0
        public static T ParseExpression <T>(string expr, bool expectErrors = false) where T : AstNode
        {
            if (expectErrors)
            {
                Assert.Ignore("errors not yet implemented");
            }

            CSharpParser parser           = new CSharpParser();
            AstNode      parsedExpression = parser.ParseExpression(new StringReader(expr));

            Assert.AreEqual(expectErrors, parser.HasErrors, "HasErrors");

            Type type = typeof(T);

            Assert.IsTrue(type.IsAssignableFrom(parsedExpression.GetType()), String.Format("Parsed expression was {0} instead of {1} ({2})", parsedExpression.GetType(), type, parsedExpression));
            return((T)parsedExpression);
        }
        void SearchMatchingExpressions(RefactoringOptions options)
        {
            var parser  = new CSharpParser();
            var astNode = parser.ParseExpression(new StringReader(expressionText));
            var data    = options.GetTextEditorData();
            var unit    = parser.Parse(data);

            if (unit != null)
            {
                var node = unit.GetNodeAt(data.Caret.Line, data.Caret.Column);
                while (node != null && !(node is BlockStatement))
                {
                    node = node.Parent;
                }
                if (node != null)
                {
                    var nodeStack = new Stack <AstNode> ();
                    nodeStack.Push(node);
                    var minLoc = new AstLocation(data.Caret.Line, data.Caret.Column);
                    while (nodeStack.Count > 0)
                    {
                        var curNode = nodeStack.Pop();

                        if (curNode.StartLocation > minLoc && curNode.IsMatch(astNode))
                        {
                            matches.Add(curNode);
                        }
                        foreach (var child in curNode.Children)
                        {
                            nodeStack.Push(child);
                        }
                    }
                }
            }

            if (matches.Count > 1)
            {
                var result = MessageService.AskQuestion(string.Format(GettextCatalog.GetString("Replace all {0} occurences ?"), matches.Count), AlertButton.Yes, AlertButton.No);
                replaceAll = result == AlertButton.Yes;
            }
        }
Exemple #16
0
        public static T ParseExpression <T>(string expr, bool expectErrors = false) where T : AstNode
        {
            CSharpParser parser           = new CSharpParser();
            AstNode      parsedExpression = parser.ParseExpression(expr);

            StringBuilder errorOutput = new StringBuilder();

            foreach (var error in parser.Errors)
            {
                errorOutput.AppendLine(error.Message);
            }
            Assert.AreEqual(expectErrors, parser.HasErrors, errorOutput.ToString());

            if (expectErrors && parsedExpression == null)
            {
                return(default(T));
            }
            Type type = typeof(T);

            Assert.IsTrue(type.IsAssignableFrom(parsedExpression.GetType()), String.Format("Parsed expression was {0} instead of {1} ({2})", parsedExpression.GetType(), type, parsedExpression));
            return((T)parsedExpression);
        }
        static ResolveResult ResolveSnippet(string fileName, TextLocation location, string contextCode, string codeSnippet, ICompilation compilation)
        {
            CSharpParser      contextParser   = new CSharpParser();
            var               cu              = contextParser.Parse(contextCode, fileName);
            CSharpAstResolver contextResolver = new CSharpAstResolver(compilation, cu);
            var               node            = cu.GetNodeAt(location);
            CSharpResolver    context;

            if (node != null)
            {
                context = contextResolver.GetResolverStateAfter(node, CancellationToken.None);
            }
            else
            {
                context = new CSharpResolver(compilation);
            }
            CSharpParser parser = new CSharpParser();
            var          expr   = parser.ParseExpression(codeSnippet);

            Assert.IsFalse(parser.HasErrors);
            CSharpAstResolver snippetResolver = new CSharpAstResolver(context, expr);

            return(snippetResolver.Resolve(expr, CancellationToken.None));
        }
        public void TestInt()
        {
            ExpressionSyntax result = CSharpParser.ParseExpression("12");

            PrintNodeContent(result);
        }
        public void TestComplexString()
        {
            ExpressionSyntax result = CSharpParser.ParseExpression("\"12\" + someVar");

            PrintNodeContent(result);
        }
        public void TestString()
        {
            ExpressionSyntax result = CSharpParser.ParseExpression("\"12\"");

            PrintNodeContent(result);
        }