public WaitForCompleteAnalysisDialog(VsProjectAnalyzer analyzer)
        {
            _analyzer = analyzer;
            InitializeComponent();

            new Thread(AnalysisComplete).Start();
        }
Exemple #2
0
 internal ExpressionAnalysis(VsProjectAnalyzer analyzer, string expression, ModuleAnalysis analysis, int index, ITrackingSpan span)
 {
     _expr = expression;
     _analysis = analysis;
     _index = index;
     _span = span;
     _analyzer = analyzer;
 }
Exemple #3
0
 public PreviewChangesEngine(IRenameVariableInput input, ExpressionAnalysis analysis, RenameVariableRequest request, string originalName, string privatePrefix, VsProjectAnalyzer analyzer, IEnumerable<IAnalysisVariable> variables)
 {
     _analysis = analysis;
     _analyzer = analyzer;
     _renameReq = request;
     _originalName = originalName;
     _privatePrefix = privatePrefix;
     _variables = variables;
     _input = input;
     _list = new PreviewList(CreatePreviewItems().ToArray());
 }
Exemple #4
0
        private static async Task <VsProjectAnalyzer> CreateAnalyzerAsync(PythonVersion version)
        {
            version.AssertInstalled();
            var factory      = new MockPythonInterpreterFactory(version.Configuration);
            var sp           = new MockServiceProvider();
            var services     = new Microsoft.PythonTools.Editor.PythonEditorServices(sp);
            var interpreters = new MockInterpreterOptionsService();

            interpreters.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider", factory));
            services.InterpreterRegistryService = interpreters;
            services.InterpreterOptionsService  = interpreters;
            return(await VsProjectAnalyzer.CreateForTestsAsync(
                       services,
                       factory
                       ));
        }
Exemple #5
0
 public AnalysisEntry(
     VsProjectAnalyzer analyzer,
     string path,
     int fileId,
     bool isTemporaryFile   = false,
     bool suppressErrorList = false
     )
 {
     Analyzer          = analyzer;
     Path              = path;
     FileId            = fileId;
     Properties        = new Dictionary <object, object>();
     IsTemporaryFile   = isTemporaryFile;
     SuppressErrorList = suppressErrorList;
     _bufferParser     = new WeakReference <BufferParser>(null);
 }
Exemple #6
0
        public BufferParser(AnalysisEntry analysis, VsProjectAnalyzer parser, ITextBuffer buffer)
        {
            Debug.Assert(analysis != null);

            _parser       = parser;
            _timer        = new Timer(ReparseTimer, null, Timeout.Infinite, Timeout.Infinite);
            _buffers      = new[] { buffer };
            AnalysisEntry = analysis;

            analysis.BufferParser = this;

            InitBuffer(buffer, 0);

            // lock not necessary for _bufferInfo, no one has access to us yet...
            ParseBuffers(new[] { buffer.CurrentSnapshot }, new[] { _bufferInfo[buffer] }).DoNotWait();
        }
Exemple #7
0
 public AnalysisEntry(
     VsProjectAnalyzer analyzer,
     string path,
     Uri documentUri,
     bool isTemporaryFile   = false,
     bool suppressErrorList = false
     )
 {
     Analyzer          = analyzer;
     Path              = path;
     DocumentUri       = documentUri ?? (!string.IsNullOrEmpty(path) ? new Uri(path) : null);
     Properties        = new Dictionary <object, object>();
     IsTemporaryFile   = isTemporaryFile;
     SuppressErrorList = suppressErrorList;
     _bufferParser     = new WeakReference <BufferParser>(null);
 }
        public void AnalyzeBadEgg()
        {
            var factories = new[] { InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(3, 4)) };
            var services  = PythonToolsTestUtilities.CreateMockServiceProvider().GetEditorServices();

            using (var analyzer = new VsProjectAnalyzer(services, factories[0])) {
                analyzer.SetSearchPathsAsync(new[] { TestData.GetPath(@"TestData\BadEgg.egg") }).Wait();
                analyzer.WaitForCompleteAnalysis(_ => true);

                // Analysis result must contain the module for the filename inside the egg that is a valid identifier,
                // and no entries for the other filename which is not.
                var moduleNames = analyzer.GetModulesResult(true).Result.Select(x => x.Name);
                AssertUtil.Contains(moduleNames, "module");
                AssertUtil.DoesntContain(moduleNames, "42");
            }
        }
        public override CompletionSet GetCompletions(IGlyphService glyphService)
        {
            var start = _stopwatch.ElapsedMilliseconds;

            var line     = Span.GetStartPoint(TextBuffer.CurrentSnapshot).GetContainingLine();
            var startPos = line.Start.Position + line.GetText().IndexOf("def");

            var analysis = GetAnalysisEntry();
            var snapshot = TextBuffer.CurrentSnapshot;
            var pos      = VsProjectAnalyzer.TranslateIndex(startPos, snapshot, analysis);

            var cls         = analysis.GetDefinitionTree(pos).LastOrDefault(member => member.MemberType == Interpreter.PythonMemberType.Class);
            var members     = analysis.GetOverrideable(pos).ToArray();
            var completions = members
                              .Select(member => PythonCompletion(glyphService,
                                                                 member.Name,
                                                                 MakeCompletionString(member, cls.Name),
                                                                 member.Documentation,
                                                                 StandardGlyphGroup.GlyphGroupOverload));

            CompletionSet res;

            if (completions.Any())
            {
                res = new FuzzyCompletionSet(
                    "PythonOverrides",
                    "Python",
                    Span,
                    completions,
                    _options,
                    CompletionComparer.UnderscoresLast
                    );
            }
            else
            {
                res = new CompletionSet();
            }

            var end = _stopwatch.ElapsedMilliseconds;

            if (/*Logging &&*/ end - start > TooMuchTime)
            {
                Trace.WriteLine(String.Format("{0} lookup time {1} for {2} classes", this, end - start, res.Completions.Count));
            }

            return(res);
        }
        private async Task AnalyzeReferenceAsync(VsProjectAnalyzer interp)
        {
            if (interp == null)
            {
                _failedToAnalyze = true;
                return;
            }

            _failedToAnalyze = false;

            var resp = await interp.AddReferenceAsync(new ProjectAssemblyReference(AssemblyName, Url));

            if (resp == null)
            {
                _failedToAnalyze = true;
            }
        }
        internal async Task AddAnalyzedAssembly(VsProjectAnalyzer interp)
        {
            if (interp != null)
            {
                var    asmName = AssemblyName;
                string outFile;
                try {
                    outFile = ReferencedProjectOutputPath;
                } catch (COMException) {
                    _failedToAnalyze = true;
                    return;
                }
                _failedToAnalyze = false;
                _curReference    = null;

                if (!string.IsNullOrEmpty(asmName))
                {
                    _asmName      = new AssemblyName(asmName);
                    _curReference = new ProjectAssemblyReference(_asmName, ReferencedProjectOutputPath);
                }
                else if (File.Exists(outFile))
                {
                    _asmName      = null;
                    _curReference = new ProjectReference(outFile, ProjectReferenceKind.ExtensionModule);
                }
                else
                {
                    if (ReferencedProjectObject == null ||
                        !Utilities.GuidEquals(PythonConstants.ProjectFactoryGuid, ReferencedProjectObject.Kind))
                    {
                        // Only failed if the reference isn't to another Python
                        // project.
                        _failedToAnalyze = true;
                    }
                }

                if (_curReference != null)
                {
                    try {
                        await interp.AddReferenceAsync(_curReference);
                    } catch (Exception) {
                        _failedToAnalyze = true;
                    }
                }
            }
        }
Exemple #12
0
            public SimpleLocationInfo(VsProjectAnalyzer analyzer, IServiceProvider serviceProvider, string searchText, AnalysisLocation locInfo, StandardGlyphGroup glyphType)
            {
                _serviceProvider = serviceProvider;
                _locationInfo    = locInfo;
                _glyphType       = glyphType;
                _pathText        = GetSearchDisplayText();
                AnalysisEntry entry = analyzer.GetAnalysisEntryFromPath(_locationInfo.FilePath);

                if (entry != null)
                {
                    _lineText = entry.GetLine(_locationInfo.Line) ?? "";
                }
                else
                {
                    _lineText = "";
                }
            }
Exemple #13
0
        private async Task <VsProjectAnalyzer> CreateAnalyzerAsync(IPythonInterpreterFactory factory, string location)
        {
            _site.MustBeCalledFromUIThread();

            var pythonServices = _site.GetPythonToolsService();
            var res            = await VsProjectAnalyzer.CreateForWorkspaceAsync(
                pythonServices.EditorServices,
                factory,
                location
                );

            res.AbnormalAnalysisExit += OnAnalysisProcessExited;

            await UpdateAnalyzerSearchPathsAsync(res);

            return(res);
        }
Exemple #14
0
        /// <summary>
        /// Implements Goto Definition.  Called when the user selects Goto Definition from the 
        /// context menu or hits the hotkey associated with Goto Definition.
        /// 
        /// If there is 1 and only one definition immediately navigates to it.  If there are
        /// no references displays a dialog box to the user.  Otherwise it opens the find
        /// symbols dialog with the list of results.
        /// </summary>
        private async void GotoDefinition() {
            UpdateStatusForIncompleteAnalysis();

            var caret = _textView.GetPythonCaret();
            if (caret != null) {

                var defs = await VsProjectAnalyzer.AnalyzeExpressionAsync(_serviceProvider, _textView, caret.Value);
                if (defs == null) {
                    return;
                }
                Dictionary<AnalysisLocation, SimpleLocationInfo> references, definitions, values;
                GetDefsRefsAndValues(_textView.GetAnalyzerAtCaret(_serviceProvider), _serviceProvider, defs.Expression, defs.Variables, out definitions, out references, out values);

                if ((values.Count + definitions.Count) == 1) {
                    if (values.Count != 0) {
                        foreach (var location in values.Keys) {
                            GotoLocation(location);
                            break;
                        }
                    } else {
                        foreach (var location in definitions.Keys) {
                            GotoLocation(location);
                            break;
                        }
                    }
                } else if (values.Count + definitions.Count == 0) {
                    if (String.IsNullOrWhiteSpace(defs.Expression)) {
                        MessageBox.Show(String.Format("Cannot go to definition.  The cursor is not on a symbol."), "Python Tools for Visual Studio");
                    } else {
                        MessageBox.Show(String.Format("Cannot go to definition \"{0}\"", defs.Expression), "Python Tools for Visual Studio");
                    }
                } else if (definitions.Count == 0) {
                    ShowFindSymbolsDialog(defs.Expression, new SymbolList("Values", StandardGlyphGroup.GlyphForwardType, values.Values));
                } else if (values.Count == 0) {
                    ShowFindSymbolsDialog(defs.Expression, new SymbolList("Definitions", StandardGlyphGroup.GlyphLibrary, definitions.Values));
                } else {
                    ShowFindSymbolsDialog(defs.Expression,
                        new LocationCategory("Goto Definition",
                            new SymbolList("Definitions", StandardGlyphGroup.GlyphLibrary, definitions.Values),
                            new SymbolList("Values", StandardGlyphGroup.GlyphForwardType, values.Values)
                        )
                    );
                }
            }
        }
Exemple #15
0
        internal static async Task ParseBuffersAsync(
            PythonEditorServices services,
            VsProjectAnalyzer analyzer,
            IEnumerable <ITextSnapshot> snapshots
            )
        {
            var updates = snapshots
                          .GroupBy(s => PythonTextBufferInfo.TryGetForBuffer(s.TextBuffer)?.AnalysisEntry.FileId ?? -1)
                          .Where(g => g.Key >= 0)
                          .Select(g => Tuple.Create(
                                      g.Key,
                                      g.Select(s => GetUpdateForSnapshot(services, s)).Where(u => u != null).ToArray()
                                      ))
                          .ToList();

            if (!updates.Any())
            {
                return;
            }

            analyzer._analysisComplete = false;
            Interlocked.Increment(ref analyzer._parsePending);

            foreach (var update in updates)
            {
                var res = await analyzer.SendRequestAsync(
                    new AP.FileUpdateRequest()
                {
                    fileId  = update.Item1,
                    updates = update.Item2
                }
                    );

                if (res != null)
                {
                    Debug.Assert(res.failed != true);
                    analyzer.OnAnalysisStarted();
                    ValidateBufferContents(snapshots, res);
                }
                else
                {
                    Interlocked.Decrement(ref analyzer._parsePending);
                }
            }
        }
Exemple #16
0
        private static void GetDefsRefsAndValues(VsProjectAnalyzer analyzer, IServiceProvider serviceProvider, string expr, IReadOnlyList <IAnalysisVariable> variables, out Dictionary <LocationInfo, SimpleLocationInfo> definitions, out Dictionary <LocationInfo, SimpleLocationInfo> references, out Dictionary <LocationInfo, SimpleLocationInfo> values)
        {
            references  = new Dictionary <LocationInfo, SimpleLocationInfo>();
            definitions = new Dictionary <LocationInfo, SimpleLocationInfo>();
            values      = new Dictionary <LocationInfo, SimpleLocationInfo>();

            if (variables == null)
            {
                Debug.Fail("unexpected null variables");
                return;
            }

            foreach (var v in variables)
            {
                if (v?.Location == null)
                {
                    Debug.Fail("unexpected null variable or location");
                    continue;
                }
                if (v.Location.FilePath == null)
                {
                    // ignore references in the REPL
                    continue;
                }

                switch (v.Type)
                {
                case VariableType.Definition:
                    values.Remove(v.Location);
                    definitions[v.Location] = new SimpleLocationInfo(analyzer, serviceProvider, expr, v.Location, StandardGlyphGroup.GlyphGroupField);
                    break;

                case VariableType.Reference:
                    references[v.Location] = new SimpleLocationInfo(analyzer, serviceProvider, expr, v.Location, StandardGlyphGroup.GlyphGroupField);
                    break;

                case VariableType.Value:
                    if (!definitions.ContainsKey(v.Location))
                    {
                        values[v.Location] = new SimpleLocationInfo(analyzer, serviceProvider, expr, v.Location, StandardGlyphGroup.GlyphGroupField);
                    }
                    break;
                }
            }
        }
Exemple #17
0
            public ClassifierHelper(string code, PythonLanguageVersion version)
            {
                _vs = new MockVs();

                var reg       = _vs.ContentTypeRegistry;
                var providers = _vs.ComponentModel.GetExtensions <IClassifierProvider>().ToArray();

                _provider1 = providers.OfType <PythonClassifierProvider>().Single();
                _provider2 = providers.OfType <PythonAnalysisClassifierProvider>().Single();

                var factory = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion());

                _analyzer = new VsProjectAnalyzer(_vs.ServiceProvider, factory, new[] { factory });

                _view = _vs.CreateTextView(PythonCoreConstants.ContentType, code, v => {
                    v.TextView.TextBuffer.Properties.AddProperty(typeof(VsProjectAnalyzer), _analyzer);
                });
            }
Exemple #18
0
        private void AddMissingImports(List <string> importList, SnapshotPoint point)
        {
            if (importList.Count == 0)
            {
                return;
            }

            var bi    = _services.GetBufferInfo(_textView.TextBuffer);
            var entry = bi?.AnalysisEntry;

            if (entry == null)
            {
                return;
            }

            SourceLocation loc;

            try {
                var line = point.GetContainingLine();
                loc = new SourceLocation(
                    point.Position,
                    line.LineNumber + 1,
                    point.Position - line.Start + 1
                    );
            } catch (ArgumentException ex) {
                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
                return;
            }

            foreach (var import in importList)
            {
                var isMissing = entry.Analyzer.WaitForRequest(
                    entry.Analyzer.IsMissingImportAsync(entry, import, loc),
                    "ExpansionClient.IsMissingImportAsync",
                    false
                    );

                if (isMissing)
                {
                    VsProjectAnalyzer.AddImport(_textView.TextBuffer, null, import);
                }
            }
        }
Exemple #19
0
        internal void AddBuffer(ITextBuffer textBuffer)
        {
            int newId;
            var bi = _services.GetBufferInfo(textBuffer);

            var entry = bi.AnalysisEntry;

            if (entry == null)
            {
                throw new InvalidOperationException("buffer must have a project entry before parsing");
            }

            lock (this) {
                var existing = _buffers.FirstOrDefault(b => b.Buffer == bi);
                if (existing != null)
                {
                    existing.AddRef();
                    return;
                }

                _buffers = _buffers.Concat(Enumerable.Repeat(new PythonTextBufferInfoWithRefCount(bi), 1)).ToArray();
                newId    = _buffers.Length - 1;

                if (!bi.SetAnalysisBufferId(newId))
                {
                    // Raced, and now the buffer belongs somewhere else.
                    Debug.Fail("Race condition adding the buffer to a parser");
                    _buffers[newId] = null;
                    return;
                }
                _bufferIdMapping[newId] = bi;
            }

            if (bi.ParseImmediately)
            {
                // Any buffer requesting immediate parsing enables it for
                // the whole file.
                _parseImmediately = true;
            }

            bi.AddSink(this, this);
            VsProjectAnalyzer.ConnectErrorList(bi);
        }
Exemple #20
0
        public void Invoke(CancellationToken cancellationToken)
        {
            Debug.Assert(!string.IsNullOrEmpty(_name));

            AnalysisEntry entry;

            if (!_source._services.AnalysisEntryService.TryGetAnalysisEntry(_source._view, _buffer, out entry))
            {
                return;
            }

            VsProjectAnalyzer.AddImport(
                entry,
                _fromModule,
                _name,
                _source._view,
                _buffer
                );
        }
Exemple #21
0
        /// <summary>
        /// Gets the best analyzer for this text view, accounting for things like REPL windows and
        /// difference windows.
        /// </summary>
        internal static VsProjectAnalyzer GetBestAnalyzer(this ITextView textView, IServiceProvider serviceProvider)
        {
            // If we have set an analyzer explicitly, return that
            VsProjectAnalyzer analyzer = null;

            if (textView.TextBuffer.Properties.TryGetProperty(typeof(VsProjectAnalyzer), out analyzer))
            {
                return(analyzer);
            }

            // If we have a REPL evaluator we'll use it's analyzer
            var evaluator = textView.TextBuffer.GetInteractiveWindow()?.Evaluator as IPythonInteractiveIntellisense;

            if (evaluator != null)
            {
                return(evaluator.Analyzer);
            }

            // If we have a difference viewer we'll match the LHS w/ the RHS
            IWpfDifferenceViewerFactoryService diffService = null;

            try {
                diffService = serviceProvider.GetComponentModel().GetService <IWpfDifferenceViewerFactoryService>();
            } catch (System.ComponentModel.Composition.CompositionException) {
            } catch (System.ComponentModel.Composition.ImportCardinalityMismatchException) {
            }
            if (diffService != null)
            {
                var viewer = diffService.TryGetViewerForTextView(textView);
                if (viewer != null)
                {
                    var entry = GetAnalysisEntry(null, viewer.DifferenceBuffer.LeftBuffer, serviceProvider) ??
                                GetAnalysisEntry(null, viewer.DifferenceBuffer.RightBuffer, serviceProvider);

                    if (entry != null)
                    {
                        return(entry.Analyzer);
                    }
                }
            }

            return(serviceProvider.GetPythonToolsService().DefaultAnalyzer);
        }
Exemple #22
0
        protected override void Reload()
        {
            using (new DebugTimer("Project Load")) {
                _intermediateOutputPath = Path.Combine(ProjectHome, GetProjectProperty("BaseIntermediateOutputPath"));

                if (_analyzer != null && _analyzer.RemoveUser())
                {
                    _analyzer.Dispose();
                }
                _analyzer = new VsProjectAnalyzer(ProjectFolder);
                _analyzer.MaxLogLength = NodejsPackage.Instance.IntellisenseOptionsPage.AnalysisLogMax;
                LogAnalysisLevel();

                base.Reload();

                SyncFileSystem();

                NodejsPackage.Instance.CheckSurveyNews(false);
                ModulesNode.ReloadHierarchySafe();

                // scan for files which were loaded from cached analysis but no longer
                // exist and remove them.
                _analyzer.ReloadComplete();

                var ignoredPaths = GetProjectProperty(NodejsConstants.AnalysisIgnoredDirectories);

                if (!string.IsNullOrWhiteSpace(ignoredPaths))
                {
                    _analysisIgnoredDirs = ignoredPaths.Split(';').Select(x => '\\' + x + '\\').ToArray();
                }
                else
                {
                    _analysisIgnoredDirs = new string[0];
                }

                var maxFileSizeProp = GetProjectProperty(NodejsConstants.AnalysisMaxFileSize);
                int maxFileSize;
                if (maxFileSizeProp != null && Int32.TryParse(maxFileSizeProp, out maxFileSize))
                {
                    _maxFileSize = maxFileSize;
                }
            }
        }
Exemple #23
0
        public ITextBuffer CreatePythonTextBuffer(string input, string filePath, VsProjectAnalyzer testAnalyzer = null)
        {
            var textBufferFactory          = _exportProvider.GetExportedValue <ITextBufferFactoryService>();
            var textDocumentFactoryService = _exportProvider.GetExportedValue <ITextDocumentFactoryService>();
            var textContentType            = _exportProvider.GetExportedValue <IContentTypeRegistryService>().GetContentType(PythonCoreConstants.ContentType);

            var textBuffer = textBufferFactory.CreateTextBuffer(input, textContentType);

            textDocumentFactoryService.CreateTextDocument(textBuffer, filePath);

            if (testAnalyzer != null)
            {
                textBuffer.Properties.AddProperty(VsProjectAnalyzer._testAnalyzer, testAnalyzer);
            }

            textBuffer.Properties.AddProperty(VsProjectAnalyzer._testFilename, filePath);

            return(textBuffer);
        }
Exemple #24
0
        private async Task ExtractMethodTest(string input, Func <Span> extract, TestResult expected, string scopeName = null, string targetName = "g", Version version = null, params string[] parameters)
        {
            var fact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version ?? new Version(2, 7));

            var editorTestToolset = new EditorTestToolset().WithPythonToolsService();
            var services          = editorTestToolset.GetPythonEditorServices();

            using (var analyzer = await VsProjectAnalyzer.CreateForTestsAsync(services, fact))
            {
                var   analysisStartedTask = EventTaskSources.VsProjectAnalyzer.AnalysisStarted.Create(analyzer);
                var   buffer = editorTestToolset.CreatePythonTextBuffer(input, Path.Combine(TestData.GetTempPath(), "fob.py"), analyzer);
                var   view   = editorTestToolset.CreateTextView(buffer);
                await analysisStartedTask;

                var bi = services.GetBufferInfo(buffer);
                bi.ParseImmediately = true;
                var entry = await analyzer.AnalyzeFileAsync(bi.DocumentUri, bi.Filename);

                Assert.AreEqual(entry, bi.TrySetAnalysisEntry(entry, null));
                var bp = entry.GetOrCreateBufferParser(services);
                bp.AddBuffer(buffer);
                await bp.EnsureCodeSyncedAsync(bi.Buffer, true);

                ExtractMethodTestInput extractInput = new ExtractMethodTestInput(true, scopeName, targetName, parameters ?? new string[0]);
                await editorTestToolset.UIThread.InvokeTask(() =>
                {
                    view.Selection.Select(new SnapshotSpan(view.TextBuffer.CurrentSnapshot, extract()), false);
                    return(new Microsoft.PythonTools.Refactoring.MethodExtractor(services, view).ExtractMethod(extractInput));
                });

                if (expected.IsError)
                {
                    Assert.AreEqual(expected.Text, extractInput.FailureReason);
                    Assert.AreEqual(input, view.TextBuffer.CurrentSnapshot.GetText());
                }
                else
                {
                    Assert.AreEqual(null, extractInput.FailureReason);
                    Assert.AreEqual(expected.Text, view.TextBuffer.CurrentSnapshot.GetText());
                }
            }
        }
Exemple #25
0
        private static async Task CodeFormattingTest(string input, object selection, string expected, object expectedSelection, CodeFormattingOptions options, bool selectResult = true)
        {
            var fact = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7));
            var editorTestToolset = new EditorTestToolset().WithPythonToolsService();

            var services = editorTestToolset.GetPythonEditorServices();

            using (var analyzer = await VsProjectAnalyzer.CreateForTestsAsync(services, fact)) {
                var   analysisStartedTask = EventTaskSources.VsProjectAnalyzer.AnalysisStarted.Create(analyzer);
                var   buffer = editorTestToolset.CreatePythonTextBuffer(input, analyzer);
                var   view   = editorTestToolset.CreateTextView(buffer);
                await analysisStartedTask;

                var bi    = services.GetBufferInfo(buffer);
                var entry = await analyzer.AnalyzeFileAsync(bi.Filename);

                Assert.AreEqual(entry, bi.TrySetAnalysisEntry(entry, null), "Failed to set analysis entry");
                entry.GetOrCreateBufferParser(services).AddBuffer(buffer);

                var selectionSpan = new SnapshotSpan(
                    buffer.CurrentSnapshot,
                    ExtractMethodTests.GetSelectionSpan(input, selection)
                    );
                editorTestToolset.UIThread.Invoke(() => view.Selection.Select(selectionSpan, false));

                await analyzer.FormatCodeAsync(
                    selectionSpan,
                    view,
                    options,
                    selectResult
                    );

                Assert.AreEqual(expected, view.TextBuffer.CurrentSnapshot.GetText());
                if (expectedSelection != null)
                {
                    Assert.AreEqual(
                        ExtractMethodTests.GetSelectionSpan(expected, expectedSelection),
                        view.Selection.StreamSelectionSpan.SnapshotSpan.Span
                        );
                }
            }
        }
        public async void Invoke(CancellationToken cancellationToken)
        {
            Debug.Assert(!string.IsNullOrEmpty(_name));

            var           entryService = _source._provider.GetEntryService();
            AnalysisEntry entry;

            if (entryService == null || !entryService.TryGetAnalysisEntry(_source._view, _buffer, out entry))
            {
                return;
            }

            await VsProjectAnalyzer.AddImportAsync(
                entry,
                _fromModule,
                _name,
                _source._view,
                _buffer
                );
        }
Exemple #27
0
        private void UninitBuffer(PythonTextBufferInfo subjectBuffer)
        {
            if (subjectBuffer == null)
            {
                throw new ArgumentNullException(nameof(subjectBuffer));
            }
            subjectBuffer.OnChangedLowPriority -= BufferChangedLowPriority;
            VsProjectAnalyzer.DisconnectErrorList(subjectBuffer);
            lock (this) {
                _bufferIdMapping.Remove(subjectBuffer.AnalysisEntryId);
                subjectBuffer.SetAnalysisEntryId(-1);
            }


            if (_document != null)
            {
                _document.EncodingChanged -= EncodingChanged;
                _document = null;
            }
        }
Exemple #28
0
        /// <summary>
        /// Implements Find All References.  Called when the user selects Find All References from
        /// the context menu or hits the hotkey associated with find all references.
        ///
        /// Always opens the Find Symbol Results box to display the results.
        /// </summary>
        private async void FindAllReferences()
        {
            UpdateStatusForIncompleteAnalysis();

            var caret = _textView.GetPythonCaret();

            if (caret != null)
            {
                var references = await VsProjectAnalyzer.AnalyzeExpressionAsync(_serviceProvider, _textView, caret.Value);

                if (references == null)
                {
                    return;
                }

                var locations = GetFindRefLocations(_textView.GetAnalyzerAtCaret(_serviceProvider), _serviceProvider, references.Expression, references.Variables);

                ShowFindSymbolsDialog(references.Expression, locations);
            }
        }
Exemple #29
0
        public PythonSignature(VsProjectAnalyzer analyzer, ITrackingSpan span, AP.Signature overload, int paramIndex, string lastKeywordArg = null)
        {
            _span     = span;
            _overload = overload;
            _analyzer = analyzer;

            _listParamIndex = _dictParamIndex = int.MaxValue;

            if (string.IsNullOrEmpty(lastKeywordArg))
            {
                _initialParameterIndex = paramIndex;
            }
            else
            {
                _initialParameterIndex = int.MaxValue;
                _initialParameterName  = lastKeywordArg;
            }

            _documentation = overload.doc;
        }
Exemple #30
0
        private IEnumerable <CompletionResult> GetAvailableCompletions(PythonTextBufferInfo bufferInfo, SnapshotPoint point)
        {
            var analysis = bufferInfo.AnalysisEntry;

            if (analysis == null)
            {
                return(Enumerable.Empty <CompletionResult>());
            }

            var analyzer = analysis.Analyzer;

            lock (analyzer) {
                var location = VsProjectAnalyzer.TranslateIndex(
                    point.Position,
                    point.Snapshot,
                    analysis
                    );
                return(analyzer.WaitForRequest(analyzer.GetAllAvailableMembersAsync(analysis, location, _options.MemberOptions), "GetCompletions.GetAllAvailableMembers")
                       .MaybeEnumerate());
            }
        }
Exemple #31
0
        public static Dictionary <string, TagInfo> GetFilters(this VsProjectAnalyzer analyzer)
        {
            var filtersRes = analyzer.SendExtensionCommandAsync(
                DjangoAnalyzer.Name,
                DjangoAnalyzer.Commands.GetFilters,
                string.Empty
                ).WaitOrDefault(1000);


            var res = new Dictionary <string, TagInfo>();

            if (filtersRes != null)
            {
                var filters = new JavaScriptSerializer().Deserialize <Dictionary <string, string> >(filtersRes);
                foreach (var filter in filters)
                {
                    res[filter.Key] = new TagInfo(filter.Value, null);
                }
            }
            return(res);
        }
Exemple #32
0
        /*
         * Needed if we switch to per project Analysis levels
         * internal NodejsTools.Options.AnalysisLevel AnalysisLevel(){
         *  var analyzer = _analyzer;
         *  if (_analyzer != null) {
         *      return _analyzer.AnalysisLevel;
         *  }
         *  return NodejsTools.Options.AnalysisLevel.None;
         * }
         */
        private void IntellisenseOptionsPageAnalysisLevelChanged(object sender, EventArgs e)
        {
            var oldAnalyzer = _analyzer;

            _analyzer = null;

            var analyzer = new VsProjectAnalyzer(ProjectFolder);

            Reanalyze(this, analyzer);
            if (oldAnalyzer != null)
            {
                analyzer.SwitchAnalyzers(oldAnalyzer);
                if (oldAnalyzer.RemoveUser())
                {
                    oldAnalyzer.Dispose();
                }
            }
            _analyzer = analyzer;
            _analyzer.MaxLogLength = NodejsPackage.Instance.IntellisenseOptionsPage.AnalysisLogMax;
            LogAnalysisLevel();
        }
Exemple #33
0
        private void UpdateDefaultAnalyzer(object sender, EventArgs args)
        {
            // no need to update if analyzer isn't created yet.
            if (_analyzer == null)
            {
                return;
            }

            _container.GetUIThread().InvokeAsync(() => {
                if (_analyzer != null)
                {
                    var analyzer = CreateAnalyzer();

                    if (_analyzer != null)
                    {
                        analyzer.SwitchAnalyzers(_analyzer);
                    }
                    _analyzer = analyzer;
                }
            }).DoNotWait();
        }
Exemple #34
0
        internal AnalysisQueue(VsProjectAnalyzer analyzer)
        {
            _workEvent = new AutoResetEvent(false);
            _cancel = new CancellationTokenSource();
            _analyzer = analyzer;

            _queue = new List<IAnalyzable>[PriorityCount];
            for (int i = 0; i < PriorityCount; i++) {
                _queue[i] = new List<IAnalyzable>();
            }

            _workThread = new Thread(Worker);
            _workThread.Name = "J Analysis Queue";
            _workThread.Priority = ThreadPriority.BelowNormal;
            _workThread.IsBackground = true;

            // start the thread, wait for our synchronization context to be created
            using (AutoResetEvent threadStarted = new AutoResetEvent(false)) {
                _workThread.Start(threadStarted);
                threadStarted.WaitOne();
            }
        }
Exemple #35
0
 protected override void Close()
 {
     base.Close();
     if (_ownsAnalyzer && _replAnalyzer != null) {
         _replAnalyzer.Dispose();
         _replAnalyzer = null;
     }
 }
 internal NormalCompletionAnalysis(VsProjectAnalyzer analyzer, ITextSnapshot snapshot, ITrackingSpan span, ITextBuffer textBuffer, CompletionOptions options)
     : base(span, textBuffer, options)
 {
     _snapshot = snapshot;
     _analyzer = analyzer;
 }
Exemple #37
0
 /*!*/
 internal static IReplWindow EnsureReplWindow(VsProjectAnalyzer analyzer)
 {
     return EnsureReplWindow(analyzer.InterpreterFactory);
 }
Exemple #38
0
        public BufferParser(Dispatcher dispatcher, IProjectEntry initialProjectEntry, VsProjectAnalyzer parser, ITextBuffer buffer)
        {
            _parser = parser;
            _timer = new Timer(ReparseTimer, null, Timeout.Infinite, Timeout.Infinite);
            _buffers = new[] { buffer };
            _currentProjEntry = initialProjectEntry;
            _dispatcher = dispatcher;

            InitBuffer(buffer);
        }
Exemple #39
0
 /// <summary>
 /// Creates a new parse queue which will parse using the provided parser.
 /// </summary>
 /// <param name="parser"></param>
 public ParseQueue(VsProjectAnalyzer parser)
 {
     _parser = parser;
 }
Exemple #40
0
        protected override void Connect()
        {
            _interpreter = GetInterpreterFactory();
            var processInfo = new ProcessStartInfo(Path.Combine(JToolsPackage.GetJToolsInstallPath(), (Interpreter.Configuration.Architecture == ProcessorArchitecture.X86 ? "j32" : "j64"), "J.Console.exe"));

            #if DEBUG
            const string debugReplEnv = "DEBUG_REPL";
            Environment.SetEnvironmentVariable(debugReplEnv, "true");
            bool debugMode = Environment.GetEnvironmentVariable(debugReplEnv) != null;
            processInfo.CreateNoWindow = !debugMode;
            processInfo.UseShellExecute = debugMode;
            processInfo.RedirectStandardOutput = !debugMode;
            processInfo.RedirectStandardError = !debugMode;
            processInfo.RedirectStandardInput = !debugMode;
            #else
            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;
            processInfo.RedirectStandardOutput = true;
            processInfo.RedirectStandardError = true;
            processInfo.RedirectStandardInput = true;
            #endif

            Socket conn;
            int portNum;
            CreateConnection(out conn, out portNum);

            List<string> args = new List<string>();

            if (!String.IsNullOrWhiteSpace(InterpreterOptions)) {
                args.Add(InterpreterOptions);
            }

            string filename, dir, extraArgs = null;
            VsProjectAnalyzer analyzer;
            if (JToolsPackage.TryGetStartupFileAndDirectory(out filename, out dir, out analyzer)) {
                processInfo.WorkingDirectory = dir;
                var startupProj = JToolsPackage.GetStartupProject();
                if (startupProj != null) {
                    string searchPath = startupProj.GetProjectProperty(CommonConstants.SearchPath, true);
                    string pathEnvVar = Interpreter.Configuration.PathEnvironmentVariable;
                    if (!string.IsNullOrEmpty(searchPath) && !String.IsNullOrWhiteSpace(pathEnvVar)) {
                        processInfo.EnvironmentVariables[pathEnvVar] = searchPath;
                    }

                    string interpArgs = startupProj.GetProjectProperty(CommonConstants.InterpreterArguments, true);
                    if (!String.IsNullOrWhiteSpace(interpArgs)) {
                        args.Add(interpArgs);
                    }

                    extraArgs = startupProj.GetProjectProperty(CommonConstants.CommandLineArguments, true);
                }
                if (analyzer.InterpreterFactory == _interpreter) {
                    if (_replAnalyzer != null && _replAnalyzer != analyzer) {
                        analyzer.SwitchAnalyzers(_replAnalyzer);
                    }
                    _replAnalyzer = analyzer;
                    _ownsAnalyzer = false;
                }
            }

            //args.Add("\"" + Path.Combine(JToolsPackage.GetJToolsInstallPath(), "visualstudio_py_repl.py") + "\"");
            args.Add("--port");
            args.Add(portNum.ToString());
            args.Add("-r");

            if (!String.IsNullOrWhiteSpace(StartupScript)) {
                args.Add("--launch_file");
                args.Add("\"" + StartupScript + "\"");
            }

            _enableAttach = EnableAttach;
            if (EnableAttach) {
                args.Add("--enable-attach");
            }

            bool multipleScopes = true;
            if (!String.IsNullOrWhiteSpace(ExecutionMode)) {
                // change ID to module name if we have a registered mode
                var modes = J.Tools.Options.ExecutionMode.GetRegisteredModes();
                string modeValue = ExecutionMode;
                foreach (var mode in modes) {
                    if (mode.Id == ExecutionMode) {
                        modeValue = mode.Type;
                        multipleScopes = mode.SupportsMultipleScopes;
                        break;
                    }
                }
                args.Add("--execution_mode");
                args.Add(modeValue);
            }

            SetMultipleScopes(multipleScopes);

            processInfo.Arguments = String.Join(" ", args);

            var process = new Process();
            process.StartInfo = processInfo;
            try {
                process.Start();
            } catch (Exception e) {
                Window.WriteError(String.Format("Failed to start interactive process: {0}{1}{2}", Environment.NewLine, e.ToString(), Environment.NewLine));
                return;
            }

            CreateCommandProcessor(conn, null, processInfo.RedirectStandardOutput, process);
        }
Exemple #41
0
 internal void RecreateAnalyzer() {
     if (_analyzer != null) {
         _analyzer.Dispose();
     }
     _analyzer = CreateAnalyzer();
 }
Exemple #42
0
 internal static bool TryGetStartupFileAndDirectory(out string filename, out string dir, out VsProjectAnalyzer analyzer) {
     var startupProject = GetStartupProject();
     if (startupProject != null) {
         filename = startupProject.GetStartupFile();
         dir = startupProject.GetWorkingDirectory();
         analyzer = ((JProjectNode)startupProject).GetAnalyzer();
     } else {
         var textView = CommonPackage.GetActiveTextView();
         if (textView == null) {
             filename = null;
             dir = null;
             analyzer = null;
             return false;
         }
         filename = textView.GetFilePath();
         analyzer = textView.GetAnalyzer();
         dir = Path.GetDirectoryName(filename);
     }
     return true;
 }