示例#1
0
        public bool AugmentSignatureHelpSession(ISignatureHelpSession session, IList <ISignature> signatures, AstRoot ast, Action <object> triggerSession)
        {
            ITextSnapshot snapshot = _textBuffer.CurrentSnapshot;
            int           position = session.GetTriggerPoint(_textBuffer).GetPosition(snapshot);

            // Retrieve parameter positions from the current text buffer snapshot
            ParameterInfo parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(ast, snapshot, position);

            if (parametersInfo != null)
            {
                position = Math.Min(parametersInfo.SignatureEnd, position);
                int start = Math.Min(position, snapshot.Length);
                int end   = Math.Min(parametersInfo.SignatureEnd, snapshot.Length);

                ITrackingSpan applicableToSpan = snapshot.CreateTrackingSpan(Span.FromBounds(start, end), SpanTrackingMode.EdgeInclusive);

                // Get collection of function signatures from documentation (parsed RD file)
                IFunctionInfo functionInfo = FunctionIndex.GetFunctionInfo(parametersInfo.FunctionName, triggerSession, session.TextView);
                if (functionInfo != null && functionInfo.Signatures != null)
                {
                    foreach (ISignatureInfo signatureInfo in functionInfo.Signatures)
                    {
                        ISignature signature = CreateSignature(session, functionInfo, signatureInfo, applicableToSpan, ast, position);
                        signatures.Add(signature);
                    }

                    session.Properties["functionInfo"] = functionInfo;
                    return(true);
                }
            }

            return(false);
        }
        public async Task ParameterTest_ComputeCurrentParameter02()
        {
            await FunctionIndex.GetPackageNameAsync("legend");

            _settings.PartialArgumentNameMatch.Returns(true);

            var textBuffer = new TextBufferMock("legend(bty=1, lt=3)", RContentTypeDefinition.ContentType);
            var eb         = textBuffer.ToEditorBuffer();
            var source     = new RSignatureHelpSource(textBuffer, Services);
            var session    = new SignatureHelpSessionMock(Services, textBuffer, 0);
            var textView   = session.TextView as TextViewMock;
            var signatures = new List <ISignature>();

            using (var tree = new EditorTree(eb, Services)) {
                tree.Build();
                using (var document = new EditorDocumentMock(tree)) {
                    session.TrackingPoint = new TrackingPointMock(textBuffer, 7, PointTrackingMode.Positive, TrackingFidelityMode.Forward);

                    tree.TakeThreadOwnerShip();
                    await source.AugmentSignatureHelpSessionAsync(session, signatures, tree.AstRoot);

                    signatures.Should().ContainSingle();

                    textView.Caret = new TextCaretMock(textView, 8);
                    var sh    = ((RSignatureHelp)signatures[0]).FunctionSignatureHelp;
                    var index = sh.SignatureInfo.ComputeCurrentParameter(tree.BufferSnapshot, tree.AstRoot, 8, _settings);
                    index.Should().Be(11);

                    textView.Caret = new TextCaretMock(textView, 15);
                    index          = sh.SignatureInfo.ComputeCurrentParameter(tree.BufferSnapshot, tree.AstRoot, 15, _settings);
                    index.Should().Be(6);
                }
            }
        }
示例#3
0
        public void RSignature()
        {
            using (var script = new TestScript("```{r}\r\n\r\n```", MdContentTypeDefinition.ContentType)) {
                FunctionRdDataProvider.HostStartTimeout = 10000;
                using (new RHostScript(EditorShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>())) {
                    FunctionIndex.Initialize();
                    FunctionIndex.BuildIndexAsync().Wait();
                    FunctionIndexUtility.GetFunctionInfoAsync("lm").Wait(3000);

                    script.MoveDown();
                    script.Type("x <- lm(");
                    script.DoIdle(2000);

                    ISignatureHelpSession session = script.GetSignatureSession();
                    session.Should().NotBeNull();
                    IParameter parameter = session.SelectedSignature.CurrentParameter;
                    parameter.Should().NotBeNull();
                    parameter.Name.Should().Be("formula");

                    script.Type("sub");
                    script.DoIdle(500);
                    script.Type("{TAB}");
                    script.DoIdle(1000);

                    parameter = session.SelectedSignature.CurrentParameter;
                    parameter.Name.Should().Be("subset");

                    string actual = script.EditorText;
                    actual.Should().Be("```{r}\r\nx <- lm(subset = )\r\n```");

                    session   = script.GetSignatureSession();
                    parameter = session.SelectedSignature.CurrentParameter;
                }
            }
        }
示例#4
0
        public async Task InitializeAsync()
        {
            await Workflow.RSessions.TrySwitchBrokerAsync(GetType().Name);

            await PackageIndex.BuildIndexAsync();

            await FunctionIndex.BuildIndexAsync();
        }
        public IReadOnlyCollection <RCompletion> GetEntries(RCompletionContext context)
        {
            List <RCompletion> completions   = new List <RCompletion>();
            ImageSource        functionGlyph = GlyphService.GetGlyph(StandardGlyphGroup.GlyphGroupValueType, StandardGlyphItem.GlyphItemPublic);

            // Safety checks
            FunctionCall funcCall = context.AstRoot.GetNodeOfTypeFromPosition <FunctionCall>(context.Position);

            if (funcCall == null || funcCall.OpenBrace == null || funcCall.Arguments == null)
            {
                return(completions);
            }

            if (context.Position < funcCall.OpenBrace.End || context.Position >= funcCall.SignatureEnd)
            {
                return(completions);
            }

            // Retrieve parameter positions from the current text buffer snapshot
            ParameterInfo parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(context.AstRoot, context.TextBuffer.CurrentSnapshot, context.Position);

            if (parametersInfo == null)
            {
                return(completions);
            }

            // Get collection of function signatures from documentation (parsed RD file)
            IFunctionInfo functionInfo = FunctionIndex.GetFunctionInfo(parametersInfo.FunctionName, o => { }, context.Session.TextView);

            if (functionInfo == null)
            {
                return(completions);
            }

            // Collect parameter names from all signatures
            IEnumerable <KeyValuePair <string, IArgumentInfo> > arguments = new Dictionary <string, IArgumentInfo>();

            foreach (ISignatureInfo signature in functionInfo.Signatures)
            {
                var args = signature.Arguments.ToDictionary(x => x.Name);
                arguments = arguments.Union(args);
            }

            // Add names of arguments that  are not yet specified to the completion
            // list with '=' sign so user can tell them from function names.
            IEnumerable <string> declaredArguments = funcCall.Arguments.Where(x => x is NamedArgument).Select(x => ((NamedArgument)x).Name);
            IEnumerable <KeyValuePair <string, IArgumentInfo> > possibleArguments = arguments.Where(x => x.Key != "..." && !declaredArguments.Contains(x.Key));

            foreach (KeyValuePair <string, IArgumentInfo> arg in possibleArguments)
            {
                string displayText   = arg.Key + " =";
                string insertionText = arg.Key + " = ";
                completions.Add(new RCompletion(displayText, insertionText, arg.Value.Description, functionGlyph));
            }

            return(completions);
        }
示例#6
0
        public static async Task DisposeAsync()
        {
            IRSessionProvider sessionProvider = EditorShell.Current.ExportProvider.GetExportedValue <IRSessionProvider>();

            if (sessionProvider != null)
            {
                await Task.WhenAll(sessionProvider.GetSessions().Select(s => s.StopHostAsync()));
            }

            FunctionIndex.Terminate();
        }
示例#7
0
        public async Task BuildPackageIndexTest()
        {
            string[] packageNames =
            {
                "base",
                "boot",
                "class",
                "cluster",
                "codetools",
                "compiler",
                "datasets",
                "foreign",
                "graphics",
                "grDevices",
                "grid",
                "KernSmooth",
                "lattice",
                "MASS",
                "Matrix",
                "methods",
                "mgcv",
                "nlme",
                "nnet",
                "parallel",
                "rpart",
                "spatial",
                "splines",
                "stats",
                "stats4",
                "survival",
                "tcltk",
                "tools",
                "translations",
                "utils",
            };

            IPackageIndex packageIndex;

            using (var host = new IntelliSenseRSession(_coreShell, _workflowProvider)) {
                await host.StartSessionAsync();

                var functionIndex = new FunctionIndex(_coreShell, null, host);
                packageIndex = new PackageIndex(_workflowProvider, _coreShell, host, functionIndex);
                await packageIndex.BuildIndexAsync();
            }

            foreach (var name in packageNames)
            {
                IPackageInfo pi = await packageIndex.GetPackageInfoAsync(name);

                pi.Should().NotBeNull();
                pi.Name.Should().Be(name);
            }
        }
示例#8
0
        internal bool AugmentQuickInfoSession(AstRoot ast, int position, IQuickInfoSession session,
                                              IList <object> quickInfoContent, out ITrackingSpan applicableToSpan,
                                              Action <object> retriggerAction)
        {
            int signatureEnd = position;

            applicableToSpan = null;

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

            if (!string.IsNullOrEmpty(functionName))
            {
                ITextSnapshot snapshot = session.TextView.TextBuffer.CurrentSnapshot;

                position = Math.Min(signatureEnd, position);
                int start = Math.Min(position, snapshot.Length);
                int end   = Math.Min(signatureEnd, snapshot.Length);

                applicableToSpan = snapshot.CreateTrackingSpan(Span.FromBounds(start, end), SpanTrackingMode.EdgeInclusive);

                IFunctionInfo functionInfo = FunctionIndex.GetFunctionInfo(functionName, retriggerAction, session);

                if (functionInfo != null && functionInfo.Signatures != null)
                {
                    foreach (ISignatureInfo sig in functionInfo.Signatures)
                    {
                        string signatureString = sig.GetSignatureString();
                        int    wrapLength      = Math.Min(SignatureInfo.MaxSignatureLength, signatureString.Length);
                        string text;

                        if (string.IsNullOrWhiteSpace(functionInfo.Description))
                        {
                            text = string.Empty;
                        }
                        else
                        {
                            /// VS may end showing very long tooltip so we need to keep
                            /// description reasonably short: typically about
                            /// same length as the function signature.
                            text = signatureString + "\r\n" + functionInfo.Description.Wrap(wrapLength);
                        }

                        if (text.Length > 0)
                        {
                            quickInfoContent.Add(text);
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
示例#9
0
        public async Task PackageDescriptionTest()
        {
            PackageIndex packageIndex;

            using (var host = new IntelliSenseRSession(_coreShell, _workflowProvider)) {
                await host.StartSessionAsync();

                var functionIndex = new FunctionIndex(_coreShell, null, host);
                packageIndex = new PackageIndex(_workflowProvider, _coreShell, host, functionIndex);
                await packageIndex.BuildIndexAsync();
            }
            IPackageInfo pi = await packageIndex.GetPackageInfoAsync("base");

            pi.Description.Should().Be("Base R functions.");
        }
示例#10
0
        private static IPackageInfo TryFindPackageNew(string packageName)
        {
            foreach (Lazy <IPackageCollection> collection in _collections)
            {
                IPackageInfo package = collection.Value.Packages.FirstOrDefault((p) => p.Name.EqualsIgnoreCase(packageName));
                if (package != null)
                {
                    _packages[package.Name.ToLowerInvariant()] = package;

                    FunctionIndex.BuildIndexForPackage(package);
                    return(package);
                }
            }

            return(null);
        }
示例#11
0
        public async Task PackageDescriptionTest()
        {
            RToolsSettings.Current = new TestRToolsSettings();
            PackageIndex packageIndex;

            using (var host = new IntelliSenseRSession(_shell, _sessionProvider, _workflowProvider)) {
                await host.CreateSessionAsync();

                var functionIndex = new FunctionIndex(_shell, null, host);
                packageIndex = new PackageIndex(_shell, host, functionIndex);
                await packageIndex.BuildIndexAsync();
            }
            IPackageInfo pi = await packageIndex.GetPackageInfoAsync("base");

            pi.Description.Should().Be("Base R functions.");
        }
示例#12
0
        public async Task InternalExternal(string content, int position, string expectedEntry, string notExpectedEntry)
        {
            var packageName = await FunctionIndex.GetPackageNameAsync(expectedEntry);

            packageName.Should().NotBeNull();

            var completionSets = new List <CompletionSet>();

            RCompletionTestUtilities.GetCompletions(Services, content, position, completionSets);
            completionSets.Should().ContainSingle();

            var entries = completionSets[0].Completions.Select(c => c.DisplayText).ToList();

            entries.Should().Contain(expectedEntry);
            entries.Should().NotContain(notExpectedEntry);
        }
示例#13
0
        public static Task <IFunctionInfo> GetFunctionInfoAsync(string functionName)
        {
            FunctionRdDataProvider.HostStartTimeout = 10000;

            var tcs    = new TaskCompletionSource <IFunctionInfo>();
            var result = FunctionIndex.GetFunctionInfo(functionName, o => {
                var r = FunctionIndex.GetFunctionInfo(functionName);
                tcs.TrySetResult(r);
            });

            if (result != null)
            {
                tcs.TrySetResult(result);
            }

            return(tcs.Task);
        }
示例#14
0
 private void InterpretWordImp()
 {
     while (input.Length > 0)
     {
         functionIndex = FunctionIndex.GetArray(input);
         HandleConstants();
         HandleParameters();
         // jesli wszystko zadzaialalo to w tym momencie funkcja powinna zaczyac sie na indexie 0
         if (functionIndex != null)
         {
             AddNecessaryMultiplications();
             interpretedWord.Add(new Function(functionIndex[0].functionType, additionalPriority));
             lastAddedElement = ElementType.Function;
             input            = input.Remove(0, Function.FunctionTypeToString((FunctionType)functionIndex[0].functionType).Length);
         }
     }
 }
        /// <summary>
        /// Extracts information on the current function in the completion context, if any.
        /// </summary>
        /// <returns></returns>
        private static IFunctionInfo GetFunctionInfo(RCompletionContext context)
        {
            // Retrieve parameter positions from the current text buffer snapshot
            IFunctionInfo functionInfo = null;

            ParameterInfo parametersInfo = SignatureHelp.GetParametersInfoFromBuffer(context.AstRoot, context.TextBuffer.CurrentSnapshot, context.Position);

            if (parametersInfo != null)
            {
                // User-declared functions take priority
                functionInfo = context.AstRoot.GetUserFunctionInfo(parametersInfo.FunctionName, context.Position);
                if (functionInfo == null)
                {
                    // Get collection of function signatures from documentation (parsed RD file)
                    functionInfo = FunctionIndex.GetFunctionInfo(parametersInfo.FunctionName, o => { }, context.Session.TextView);
                }
            }
            return(functionInfo);
        }
        public async Task ParameterTest_ComputeCurrentParameter01()
        {
            var textBuffer   = new TextBufferMock("aov(", RContentTypeDefinition.ContentType);
            var editorBuffer = textBuffer.ToEditorBuffer();
            var source       = new RSignatureHelpSource(textBuffer, Services);
            var session      = new SignatureHelpSessionMock(Services, textBuffer, 0);
            var textView     = session.TextView as TextViewMock;
            var signatures   = new List <ISignature>();

            using (var tree = new EditorTree(editorBuffer, Services)) {
                tree.Build();
                using (var document = new EditorDocumentMock(tree)) {
                    session.TrackingPoint = new TrackingPointMock(textBuffer, 4, PointTrackingMode.Positive, TrackingFidelityMode.Forward);
                    await FunctionIndex.GetPackageNameAsync("aov");

                    tree.TakeThreadOwnerShip();
                    await source.AugmentSignatureHelpSessionAsync(session, signatures, tree.AstRoot);

                    signatures.Should().ContainSingle();

                    var index = GetCurrentParameterIndex(signatures[0], signatures[0].CurrentParameter);
                    index.Should().Be(0);

                    textView.Caret = new TextCaretMock(textView, 5);
                    TextBufferUtility.ApplyTextChange(textBuffer, 4, 0, 1, "a");
                    index = GetCurrentParameterIndex(signatures[0], signatures[0].CurrentParameter);
                    index.Should().Be(0);

                    textView.Caret = new TextCaretMock(textView, 6);
                    TextBufferUtility.ApplyTextChange(textBuffer, 5, 0, 1, ",");
                    tree.EnsureTreeReady();
                    index = GetCurrentParameterIndex(signatures[0], signatures[0].CurrentParameter);
                    index.Should().Be(1);

                    textView.Caret = new TextCaretMock(textView, 7);
                    TextBufferUtility.ApplyTextChange(textBuffer, 6, 0, 1, ",");
                    tree.EnsureTreeReady();
                    index = GetCurrentParameterIndex(signatures[0], signatures[0].CurrentParameter);
                    index.Should().Be(2);
                }
            }
        }
        public async Task SpecificPackage(string content, int position, string expectedEntry, string expectedDescription, bool realHost)
        {
            var hostScript = realHost ? new RHostScript(Workflow.RSessions) : null;

            try {
                var info = await FunctionIndex.GetFunctionInfoAsync(expectedEntry);

                info.Should().NotBeNull();

                var completionSets = new List <CompletionSet>();
                RCompletionTestUtilities.GetCompletions(EditorShell, content, position, completionSets);

                completionSets.Should().ContainSingle();

                var entry = completionSets[0].Completions.FirstOrDefault(c => c.DisplayText == expectedEntry);
                entry.Should().NotBeNull();

                var description = entry.Description;
                description.Should().Contain(expectedDescription);
            } finally {
                hostScript?.Dispose();
            }
        }
示例#18
0
        protected override void Initialize()
        {
            Current = this;

            // Force app shell creation before everything else
            var shell = VsAppShell.Current;

            if (IsCommandLineMode())
            {
                return;
            }

            VsWpfOverrides.Apply();
            CranMirrorList.Download();

            RtvsTelemetry.Initialize();

            using (var p = Current.GetDialogPage(typeof(RToolsOptionsPage)) as RToolsOptionsPage) {
                p.LoadSettings();
            }

            MicrosoftRClient.CheckInstall(VsAppShell.Current);
            base.Initialize();

            ProjectIconProvider.LoadProjectImages();
            LogCleanup.DeleteLogsAsync(DiagnosticLogs.DaysToRetain);

            _indexBuildingTask = FunctionIndex.BuildIndexAsync();

            AdviseExportedWindowFrameEvents <ActiveWpfTextViewTracker>();
            AdviseExportedWindowFrameEvents <VsActiveRInteractiveWindowTracker>();
            AdviseExportedDebuggerEvents <VsDebuggerModeTracker>();

            System.Threading.Tasks.Task.Run(() => RtvsTelemetry.Current.ReportConfiguration());

            IdleTimeAction.Create(ExpansionsCache.Load, 200, typeof(ExpansionsCache));
        }
示例#19
0
 public override int GetHashCode()
 {
     return((BlockId.GetHashCode()) ^
            (ClassScope.GetHashCode()) ^
            (FunctionIndex.GetHashCode()));
 }
示例#20
0
 private void PrepareFunctionIndex()
 {
     FunctionIndex.Initialize();
     FunctionIndex.BuildIndexAsync().Wait();
 }
示例#21
0
 public static Task InitializeAsync()
 {
     RToolsSettings.Current = new TestRToolsSettings();
     FunctionIndex.Initialize();
     return(FunctionIndex.BuildIndexAsync());
 }
示例#22
0
 public static void Initialize()
 {
     FunctionIndex.Initialize();
 }
示例#23
0
        public object ExecuteCommand(object input, FunctionIndex index)
        {
            ICommonFunc func = FuncTable[(int)index];

            return(func.ExecuteCommand(input));
        }