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(); } }
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); }
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); }
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); }
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); }
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); }
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)); }
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); }
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(); }
public static AstRoot VerifyParse(string expected, string expression) { AstRoot ast = RParser.Parse(new TextStream(expression)); ParserTest.CompareTrees(expected, ast); return(ast); }
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(); }
/// <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(); }
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); }
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"); }
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); }
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(); }
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); }
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); }
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>(); }
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(); }
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); }
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)); }
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)); } }
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))); }
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(); }
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>(); }
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()); }
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); }
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); } }
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); } }