コード例 #1
0
        public async Task Validate(string content, int start, int length, string message, string propertyName)
        {
            var prop = propertyName != null?_options.GetType().GetProperty(propertyName) : null;

            prop?.SetValue(_options, true);

            var ast = RParser.Parse(content);
            await _validator.RunAsync(ast, _results, CancellationToken.None);

            _results.Should().HaveCount(length > 0 ? 1 : 0);

            if (length > 0)
            {
                _results.TryPeek(out IValidationError e);
                e.Start.Should().Be(start);
                e.Length.Should().Be(length);
                e.Message.Should().Be(Resources.ResourceManager.GetString(message));
                e.Severity.Should().Be(ErrorSeverity.Warning);
            }

            if (prop != null)
            {
                prop.SetValue(_options, false);
                var r = new ConcurrentQueue <IValidationError>();
                await _validator.RunAsync(ast, r, CancellationToken.None);

                r.Should().BeEmpty();
            }
        }
コード例 #2
0
        public void ParameterTest01()
        {
            var content = @"x <- foo(a,b,c,d)";
            var ast     = RParser.Parse(content);

            var editorBuffer   = new TextBufferMock(content, RContentTypeDefinition.ContentType).ToEditorBuffer();
            var parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 10);

            parametersInfo.Should().NotBeNull()
            .And.HaveFunctionCall()
            .And.HaveFunctionName("foo")
            .And.HaveParameterIndex(0)
            .And.HaveSignatureEnd(17);

            parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 11);
            parametersInfo.Should().HaveParameterIndex(1);
            parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 12);
            parametersInfo.Should().HaveParameterIndex(1);

            parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 13);
            parametersInfo.Should().HaveParameterIndex(2);
            parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 14);
            parametersInfo.Should().HaveParameterIndex(2);

            parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 15);
            parametersInfo.Should().HaveParameterIndex(3);
            parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 16);
            parametersInfo.Should().HaveParameterIndex(3);
        }
コード例 #3
0
ファイル: ParameterTest.cs プロジェクト: xoriath/RTVS
        public void ParameterTest01()
        {
            string  content = @"x <- foo(a,b,c,d)";
            AstRoot ast     = RParser.Parse(content);

            ITextBuffer   textBuffer     = new TextBufferMock(content, RContentTypeDefinition.ContentType);
            ParameterInfo parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 10);

            parametersInfo.Should().NotBeNull()
            .And.HaveFunctionCall()
            .And.HaveFunctionName("foo")
            .And.HaveParameterIndex(0)
            .And.HaveSignatureEnd(17);

            parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 11);
            parametersInfo.Should().HaveParameterIndex(1);
            parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 12);
            parametersInfo.Should().HaveParameterIndex(1);

            parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 13);
            parametersInfo.Should().HaveParameterIndex(2);
            parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 14);
            parametersInfo.Should().HaveParameterIndex(2);

            parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 15);
            parametersInfo.Should().HaveParameterIndex(3);
            parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 16);
            parametersInfo.Should().HaveParameterIndex(3);
        }
コード例 #4
0
        public bool CanExecuteCode(string text)
        {
            if (text.StartsWith("?", StringComparison.Ordinal))
            {
                return(true);
            }

            var ast = RParser.Parse(text);

            if (ast.Errors.Count > 0)
            {
                // if we have any errors other than an incomplete statement send the
                // bad code to R.  Otherwise continue reading input.
                foreach (var error in ast.Errors)
                {
                    if (error.ErrorType != ParseErrorType.CloseCurlyBraceExpected &&
                        error.ErrorType != ParseErrorType.CloseBraceExpected &&
                        error.ErrorType != ParseErrorType.CloseSquareBracketExpected &&
                        error.ErrorType != ParseErrorType.FunctionBodyExpected &&
                        error.ErrorType != ParseErrorType.RightOperandExpected)
                    {
                        return(true);
                    }
                }
                return(false);
            }
            return(true);
        }
コード例 #5
0
ファイル: RCompletionController.cs プロジェクト: Fooway/RTVS
        private async Task <bool> IsFunction(string name)
        {
            if (Keywords.IsKeyword(name))
            {
                return(false);
            }

            string  expression = $"tryCatch(is.function({name}), error = function(e) {{ }})";
            AstRoot ast        = RParser.Parse(expression);

            if (ast.Errors.Count > 0)
            {
                return(false);
            }

            var       sessionProvider = EditorShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>();
            IRSession session         = sessionProvider.GetOrCreate(GuidList.InteractiveWindowRSessionGuid, null);

            if (session != null)
            {
                using (IRSessionEvaluation eval = await session.BeginEvaluationAsync(isMutating: false)) {
                    REvaluationResult result = await eval.EvaluateAsync(expression);

                    if (result.ParseStatus == RParseStatus.OK &&
                        !string.IsNullOrEmpty(result.StringResult) &&
                        (result.StringResult == "T" || result.StringResult == "TRUE"))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
コード例 #6
0
        private async Task <bool> IsFunction(string name)
        {
            if (Keywords.IsKeyword(name))
            {
                return(false);
            }

            string  expression = $"tryCatch(is.function({name}), error = function(e) {{ }})";
            AstRoot ast        = RParser.Parse(expression);

            if (ast.Errors.Count > 0)
            {
                return(false);
            }

            var       sessionProvider = EditorShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>();
            IRSession session         = sessionProvider.GetOrCreate(GuidList.InteractiveWindowRSessionGuid);

            if (session != null)
            {
                using (IRSessionEvaluation eval = await session.BeginEvaluationAsync()) {
                    try {
                        return(await eval.EvaluateAsync <bool>(expression, REvaluationKind.Normal));
                    } catch (RException) {
                    }
                }
            }
            return(false);
        }
コード例 #7
0
        public static ITextView MakeTextView(string content, int caretPosition, out AstRoot ast)
        {
            ast = RParser.Parse(content);
            ITextBuffer textBuffer = new TextBufferMock(content, RContentTypeDefinition.ContentType);

            return(new TextViewMock(textBuffer, caretPosition));
        }
コード例 #8
0
ファイル: ConfigurationParser.cs プロジェクト: zachwieja/RTVS
        private bool ParseAssignment(string text, out IRValueNode leftOperand, out IRValueNode rightOperand)
        {
            leftOperand  = null;
            rightOperand = null;

            // Parse the expression
            var ast = RParser.Parse(text);

            if (ast.Errors.Count == 0)
            {
                // Expected 'Variable <- Expression'
                var scope = ast.Children[0] as GlobalScope;
                if (scope?.Children.Count > 0)
                {
                    var exp = (scope.Children[0] as IExpressionStatement)?.Expression;
                    if (exp?.Children.Count == 1)
                    {
                        var op = exp.Children[0] as IOperator;
                        if (op != null)
                        {
                            if (op.OperatorType == OperatorType.LeftAssign && op.LeftOperand != null && op.RightOperand != null)
                            {
                                leftOperand  = op.LeftOperand;
                                rightOperand = op.RightOperand;
                                return(true);
                            }
                        }
                    }
                }
            }
            return(false);
        }
コード例 #9
0
        public void InsertRoxygen01()
        {
            var     tb     = new TextBufferMock(string.Empty, RContentTypeDefinition.ContentType);
            AstRoot ast    = RParser.Parse(tb.CurrentSnapshot.GetText());
            var     result = RoxygenBlock.TryInsertBlock(tb, ast, 0);

            result.Should().BeFalse();

            tb  = new TextBufferMock("x <- 1\r\ny <- 2", RContentTypeDefinition.ContentType);
            ast = RParser.Parse(tb.CurrentSnapshot.GetText());
            RoxygenBlock.TryInsertBlock(tb, ast, 0).Should().BeFalse();
            RoxygenBlock.TryInsertBlock(tb, ast, 8).Should().BeFalse();

            tb  = new TextBufferMock("##\r\nx <- function(a) { }", RContentTypeDefinition.ContentType);
            ast = RParser.Parse(tb.CurrentSnapshot.GetText());
            RoxygenBlock.TryInsertBlock(tb, ast, 4).Should().BeTrue();
            string actual = tb.CurrentSnapshot.GetText();

            actual.Should().Be(
                @"#' Title
#'
#' @param a
#'
#' @return
#' @export
#'
#' @examples
x <- function(a) { }");

            int funcStart = tb.CurrentSnapshot.GetText().IndexOf("x <-");

            tb.Insert(funcStart, "\r\n");
            RoxygenBlock.TryInsertBlock(tb, ast, funcStart - 2).Should().BeFalse();
        }
コード例 #10
0
ファイル: ParserTest.cs プロジェクト: fpcMotif/RTVS
        public static AstRoot VerifyParse(string expected, string expression)
        {
            AstRoot ast = RParser.Parse(new TextStream(expression));

            ParserTest.CompareTrees(expected, ast);
            return(ast);
        }
コード例 #11
0
        public void AstNode_PropertiesTest()
        {
            AstRoot ast = RParser.Parse(new TextStream(" x <- a+b"));

            ast.Properties.AddProperty("a", "b");

            ast.Properties.PropertyList.Should().HaveCount(1);
            ast.Properties.ContainsProperty("a").Should().BeTrue();
            ast.Properties.ContainsProperty("b").Should().BeFalse();
            ast.Properties.GetProperty("a").Should().Be("b");
            ast.Properties.GetProperty <object>("a").Should().Be("b");

            ast.Properties["a"] = "c";
            ast.Properties.ContainsProperty("a").Should().BeTrue();
            ast.Properties.ContainsProperty("b").Should().BeFalse();
            ast.Properties.GetProperty("a").Should().Be("c");
            ast.Properties.GetProperty <object>("a").Should().Be("c");

            string s;

            ast.Properties.TryGetProperty("a", out s).Should().BeTrue();
            s.Should().Be("c");

            ast.Properties.RemoveProperty("a");
            ast.Properties.PropertyList.Should().BeEmpty();
            ast.Properties.ContainsProperty("a").Should().BeFalse();
        }
コード例 #12
0
ファイル: EditorTree.cs プロジェクト: nomada2/RTVS
        /// <summary>
        /// Builds initial AST. Subsequent updates should be coming from a background thread.
        /// </summary>
        public void Build()
        {
            if (_ownerThread != Thread.CurrentThread.ManagedThreadId)
            {
                throw new ThreadStateException("Method should only be called on the main thread");
            }

            var sw = Stopwatch.StartNew();

            TreeUpdateTask.Cancel();

            if (TextBuffer != null)
            {
                TextSnapshot = TextBuffer.CurrentSnapshot;
                _astRoot     = RParser.Parse(new TextProvider(TextBuffer.CurrentSnapshot));
            }

            TreeUpdateTask.ClearChanges();

            // Fire UpdatesPending notification, even though we don't have ranges for the event
            List <TextChangeEventArgs> textChanges = new List <TextChangeEventArgs>();

            FireOnUpdatesPending(textChanges);

            FireOnUpdateBegin();
            FireOnUpdateCompleted(TreeUpdateType.NewTree);

            sw.Stop();
        }
コード例 #13
0
        public void Signature(string content, int position, string expectedFunctionName, int expectedSignatureEnd)
        {
            var ast          = RParser.Parse(content);
            var functionName = ast.GetFunctionNameFromBuffer(ref position, out int signatureEnd);

            functionName.Should().Be(expectedFunctionName);
            signatureEnd.Should().Be(expectedSignatureEnd);
        }
コード例 #14
0
        public void GetPackageNamesTest()
        {
            AstRoot ast = RParser.Parse(new TextStream("library(a); library(b); while(T) { library(c) }"));

            string[] names = ast.GetFilePackageNames().ToArray();

            names.Should().Equal("a", "b", "c");
        }
コード例 #15
0
        public void AstShiftTest1() {
            AstRoot ast = RParser.Parse(new TextStream(" a()"));
            IScope scope = ast.Children[0].Should().BeAssignableTo<IScope>().Which;

            scope.Children[0].Start.Should().Be(1);
            ast.Shift(1);
            scope.Children[0].Start.Should().Be(2);
        }
コード例 #16
0
        public void S4Error(string content)
        {
            var tb = new TextBufferMock("##\r\n" + content, RContentTypeDefinition.ContentType);
            var eb = tb.ToEditorBuffer();

            var ast = RParser.Parse(tb.CurrentSnapshot.GetText());

            RoxygenBlock.TryInsertBlock(eb, ast, 4).Should().BeFalse();
        }
コード例 #17
0
        public void ParameterTest03()
        {
            var content      = @"x <- foo(,,";
            var ast          = RParser.Parse(content);
            var editorBuffer = new TextBufferMock(content, RContentTypeDefinition.ContentType).ToEditorBuffer();

            var parametersInfo = ast.GetSignatureInfoFromBuffer(editorBuffer.CurrentSnapshot, 11);

            parametersInfo.Should().HaveParameterIndex(2);
        }
コード例 #18
0
        public void Signature(string content, int position, string expectedFunctionName, int expectedSignatureEnd)
        {
            AstRoot ast = RParser.Parse(content);

            int    signatureEnd;
            string functionName = SignatureHelp.GetFunctionNameFromBuffer(ast, ref position, out signatureEnd);

            functionName.Should().Be(expectedFunctionName);
            signatureEnd.Should().Be(expectedSignatureEnd);
        }
コード例 #19
0
        public void NodeFromRangeTest()
        {
            AstRoot ast = RParser.Parse(new TextStream(" x <- a123+b"));

            IAstNode node = ast.NodeFromRange(new TextRange(2, 5));

            node.Should().BeAssignableTo <IOperator>();

            node = ast.NodeFromRange(new TextRange(7, 2));
            node.Should().BeOfType <Variable>();
        }
コード例 #20
0
ファイル: LinterTest.cs プロジェクト: skeptycal/RTVS
        public async Task Projected(string content, int start, int length, string message, string propertyName)
        {
            var prop = propertyName != null?_options.GetType().GetProperty(propertyName) : null;

            prop?.SetValue(_options, true);

            var ast = RParser.Parse(content);
            await _validator.RunAsync(ast, true, true, _results, CancellationToken.None);

            _results.Should().BeEmpty();
        }
コード例 #21
0
ファイル: ParameterTest.cs プロジェクト: xoriath/RTVS
        public void ParameterTest03()
        {
            string content = @"x <- foo(,,";

            AstRoot     ast        = RParser.Parse(content);
            ITextBuffer textBuffer = new TextBufferMock(content, RContentTypeDefinition.ContentType);

            var parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, textBuffer.CurrentSnapshot, 11);

            parametersInfo.Should().HaveParameterIndex(2);
        }
コード例 #22
0
        private AstRoot UpdateAst(IEditorBuffer editorBuffer)
        {
            var document = editorBuffer.GetEditorDocument <IREditorDocument>();

            if (document != null)
            {
                document.EditorTree.EnsureTreeReady();
                return(document.EditorTree.AstRoot);
            }
            return(RParser.Parse(editorBuffer.CurrentSnapshot));
        }
コード例 #23
0
        public EditorDocumentMock(string content, string filePath = null)
        {
            var tb = new TextBufferMock(content, RContentTypeDefinition.ContentType);

            EditorTree = new EditorTreeMock(new EditorBuffer(tb), RParser.Parse(content));
            tb.AddService(this);
            if (!string.IsNullOrEmpty(filePath))
            {
                tb.Properties.AddProperty(typeof(ITextDocument), new TextDocumentMock(tb, filePath));
            }
        }
コード例 #24
0
        private static AstRoot UpdateAst(ITextBuffer textBuffer)
        {
            IREditorDocument document = REditorDocument.TryFromTextBuffer(textBuffer);

            if (document != null)
            {
                document.EditorTree.EnsureTreeReady();
                return(document.EditorTree.AstRoot);
            }
            return(RParser.Parse(new TextProvider(textBuffer.CurrentSnapshot)));
        }
コード例 #25
0
        public void ParseCommentsTest01()
        {
            AstRoot ast = RParser.Parse("#Not");

            ast.Comments.Should().ContainSingle();
            ast.Comments[0].Start.Should().Be(0);
            ast.Comments[0].Length.Should().Be(4);

            ast.Comments.Contains(0).Should().BeFalse();
            ast.Comments.Contains(1).Should().BeTrue();
            ast.Comments.Contains(4).Should().BeTrue();
        }
コード例 #26
0
        public void GetPositionNodeTest()
        {
            AstRoot ast = RParser.Parse(new TextStream(" x <- a+b"));

            IAstNode scope;
            IAstNode variable;

            ast.GetPositionNode(0, out scope);
            scope.Should().BeAssignableTo <IScope>();

            scope.GetPositionNode(1, out variable);
            variable.Should().BeOfType <Variable>();
        }
コード例 #27
0
        public bool CanExecuteCode(string text)
        {
            if (text.StartsWith("?", StringComparison.Ordinal))
            {
                return(true);
            }

            // if we have any errors other than an incomplete statement send the
            // bad code to R.  Otherwise continue reading input.
            var ast = RParser.Parse(text);

            return(ast.IsCompleteExpression());
        }
コード例 #28
0
ファイル: SmartIndenter.cs プロジェクト: gbull122/vscode-r
        private static int?GetIndentFromArguments(IFunction fc, IEditorLine prevLine, IREditorSettings settings)
        {
            // Fetch first argument on the previous line or first artument of the function
            // x < function(a,
            //              |
            // x < function(a,
            //                 b, c
            //                 |
            var snapshot = prevLine.Snapshot;
            var offset   = 0;

            // If previous line contains start of the function call, format it
            // so whitespace is correct and we can determine proper indentation
            // based on the argument or the opening brace
            if (prevLine.Contains(fc.Start))
            {
                var start  = snapshot.GetLineFromPosition(fc.Start).Start;
                var end    = snapshot.GetLineFromPosition(fc.End).End;
                var fcText = snapshot.GetText(TextRange.FromBounds(start, end));

                // Remember current indentation since formatter will remove it
                var currentIndent     = IndentBuilder.TextIndentInSpaces(fcText, settings.TabSize);
                var formattedLineText = new RFormatter().Format(fcText);
                // Restore leading indent
                formattedLineText = IndentBuilder.GetIndentString(currentIndent, settings.IndentType, settings.TabSize) + formattedLineText;

                var ast   = RParser.Parse(formattedLineText);
                var newFc = ast.FindFirstElement(n => n is IFunction) as IFunction;
                if (newFc != null)
                {
                    offset = prevLine.Start;
                }
                fc = newFc;
            }

            if (fc != null)
            {
                var arg = fc.Arguments.FirstOrDefault(a => !(a is StubArgument) && prevLine.Contains(a.Start + offset));

                if (arg != null)
                {
                    var argPosition = arg.Start + offset;
                    return(argPosition - snapshot.GetLineFromPosition(argPosition).Start);
                }

                var bracePosition = fc.OpenBrace.Start + offset;
                return(bracePosition - snapshot.GetLineFromPosition(bracePosition).Start + 1);
            }
            return(null);
        }
コード例 #29
0
ファイル: DataTipTest.cs プロジェクト: nomada2/RTVS
        public void DataTip(string code, int start, int length, string dataTip)
        {
            var ast  = RParser.Parse(new TextStream(code));
            var node = RDataTip.GetDataTipExpression(ast, new TextRange(start, length));

            if (dataTip == null)
            {
                node.Should().BeNull();
            }
            else
            {
                node.Should().NotBeNull();
                var expr = code.Substring(node.Start, node.Length);
                expr.Should().Be(dataTip);
            }
        }
コード例 #30
0
        public async Task Validate2(string content, int[] start, int[] length, string[] message)
        {
            var ast = RParser.Parse(content);
            await _validator.RunAsync(ast, _results, CancellationToken.None);

            _results.Should().HaveCount(start.Length);

            for (var i = 0; i < start.Length; i++)
            {
                _results.TryDequeue(out IValidationError e);
                e.Start.Should().Be(start[i]);
                e.Length.Should().Be(length[i]);
                e.Message.Should().Be(Resources.ResourceManager.GetString(message[i]));
                e.Severity.Should().Be(ErrorSeverity.Warning);
            }
        }