private IEnumerable <ISignature> HandleComma(VsText.ITextSnapshot snapshot, ProbeAppSettings appSettings)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(_textBuffer);

            if (fileStore != null)
            {
                var fileName = VsTextUtil.TryGetDocumentFileName(_textBuffer);
                var model    = fileStore.GetMostRecentModel(appSettings, fileName, snapshot, "Signature help after ','");
                var modelPos = (new VsText.SnapshotPoint(snapshot, _triggerPos)).TranslateTo(model.Snapshot, VsText.PointTrackingMode.Negative).Position;

                var argsToken = model.File.FindDownward <ArgsToken>().Where(t => t.Span.Start < modelPos && (t.Span.End > modelPos || !t.IsTerminated)).LastOrDefault();
                if (argsToken != null && argsToken.Signature != null)
                {
                    var modelSpan        = new VsText.SnapshotSpan(model.Snapshot, argsToken.Span.ToVsTextSpan());
                    var snapshotSpan     = modelSpan.TranslateTo(snapshot, VsText.SpanTrackingMode.EdgeInclusive);
                    var applicableToSpan = snapshot.CreateTrackingSpan(snapshotSpan.Span, VsText.SpanTrackingMode.EdgeInclusive, 0);
                    yield return(CreateSignature(_textBuffer, argsToken.Signature, applicableToSpan));

                    foreach (var sig in argsToken.SignatureAlternatives)
                    {
                        yield return(CreateSignature(_textBuffer, sig, applicableToSpan));
                    }
                }
            }
        }
Example #2
0
 public ErrorInfo(ErrorCode code, ErrorType type, string message, Span span, VsText.ITextSnapshot snapshot)
 {
     Code     = code;
     Type     = type;
     Message  = message;
     Span     = span;
     Snapshot = snapshot;
 }
Example #3
0
        /// <summary>
        /// Adjusts a position from another snapshot to the model's snapshot.
        /// </summary>
        public int AdjustPosition(int pos, VsText.ITextSnapshot snapshot)
        {
            if (snapshot == null || _snapshot == null || _snapshot == snapshot)
            {
                return(pos);
            }

            var pt = new Microsoft.VisualStudio.Text.SnapshotPoint(snapshot, pos).TranslateTo(_snapshot, Microsoft.VisualStudio.Text.PointTrackingMode.Positive);

            return(pt.Position);
        }
Example #4
0
        public static string GetDocumentPath(Microsoft.VisualStudio.Text.ITextSnapshot ts)
        {
            Microsoft.VisualStudio.Text.ITextDocument textDoc;
            bool rc = ts.TextBuffer.Properties.TryGetProperty(
                typeof(Microsoft.VisualStudio.Text.ITextDocument), out textDoc);

            if (rc && textDoc != null)
            {
                return(textDoc.FilePath);
            }
            return(null);
        }
        public void SetSource(string source, int offset, VsText.ITextSnapshot snapshot, CodeModel.CodeModel model)
        {
            _source    = source;
            _pos       = 0;
            _posOffset = offset;
            _length    = _source.Length;
            _snapshot  = snapshot;
            _model     = model;

            var transStart = snapshot.TranslateOffsetToSnapshot(offset, _model.Snapshot);
            var transEnd   = snapshot.TranslateOffsetToSnapshot(offset + source.Length, _model.Snapshot);

            _tokenMap = new Dictionary <int, Token>();
            foreach (var token in _model.File.FindDownward(transStart, transEnd - transStart))
            {
                var snapStart = _model.Snapshot.TranslateOffsetToSnapshot(token.Span.Start, snapshot);
                _tokenMap[snapStart] = token;
            }
        }
Example #6
0
        public int TranslateOffset(int offset, Microsoft.VisualStudio.Text.ITextSnapshot snapshot)
        {
            if (snapshot == null)
            {
                throw new ArgumentNullException("snapshot");
            }
            if (_snapshot == null)
            {
                throw new InvalidOperationException("Model has no snapshot.");
            }

            if (_snapshot != snapshot)
            {
                var pt = new Microsoft.VisualStudio.Text.SnapshotPoint(snapshot, offset).TranslateTo(_snapshot, Microsoft.VisualStudio.Text.PointTrackingMode.Positive);
                return(pt.Position);
            }
            else
            {
                return(offset);
            }
        }
Example #7
0
        private void RefreshFunctionList(VsTextEditor.IWpfTextView view)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (!c_functionTab.IsSelected)
            {
                return;
            }

            if (view != null)
            {
                var fileStore = CodeModel.FileStore.GetOrCreateForTextBuffer(view.TextBuffer);
                if (fileStore != null)
                {
                    var snapshot = view.TextSnapshot;
                    if (_activeView != view || _activeSnapshot != snapshot)
                    {
                        _activeView     = view;
                        _activeSnapshot = snapshot;

                        var appSettings = ProbeEnvironment.CurrentAppSettings;
                        var fileName    = VsTextUtil.TryGetDocumentFileName(view.TextBuffer);
                        _activeFunctions = (from f in fileStore.GetFunctionDropDownList(appSettings, fileName, snapshot)
                                            orderby f.Name.ToLower()
                                            select new FunctionListItem(f)).ToArray();
                        ApplyFunctionFilter();
                        c_functionList.ItemsSource = _activeFunctions;
                    }
                    return;
                }
            }

            _activeView                = null;
            _activeSnapshot            = null;
            _activeFunctions           = null;
            c_functionList.ItemsSource = null;
        }
        public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> quickInfoContent, out ITrackingSpan applicableToSpan)
        {
            applicableToSpan = null;
            if (session == null || quickInfoContent == null)
            {
                return;
            }

            Provider.IntelliSenseCache.BeginReferenceSourceParsing();

            if (session.TextView.TextBuffer == this.TextBuffer)
            {
                ITextSnapshot currentSnapshot = this.TextBuffer.CurrentSnapshot;
                SnapshotPoint?triggerPoint    = session.GetTriggerPoint(currentSnapshot);
                if (!triggerPoint.HasValue)
                {
                    return;
                }

                lock (_contentUpdateLock)
                {
                    if (triggerPoint == this._triggerPoint)
                    {
                        foreach (var content in _quickInfoContent)
                        {
                            quickInfoContent.Add(content);
                        }

                        applicableToSpan = _applicableToSpan;
                        return;
                    }
                }

                BeginUpdateQuickInfoContent(session, triggerPoint.Value);
            }
        }
Example #9
0
 public Microsoft.VisualStudio.Text.SnapshotSpan ToVsTextSnapshotSpan(VsText.ITextSnapshot snapshot)
 {
     return(new VsText.SnapshotSpan(snapshot, new VsText.Span(_start, _end - _start)));
 }
Example #10
0
        public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> quickInfoContent, out ITrackingSpan applicableToSpan)
        {
            applicableToSpan = null;
            if (session == null || quickInfoContent == null)
            {
                return;
            }

            if (session.TextView.TextBuffer == this.TextBuffer)
            {
                ITextSnapshot currentSnapshot = this.TextBuffer.CurrentSnapshot;
                SnapshotPoint?triggerPoint    = session.GetTriggerPoint(currentSnapshot);
                if (!triggerPoint.HasValue)
                {
                    return;
                }

                #region experimental
                /* use the experimental model to locate and process the expression */
                Stopwatch stopwatch = Stopwatch.StartNew();

                // lex the entire document
                var input       = new SnapshotCharStream(currentSnapshot, new Span(0, currentSnapshot.Length));
                var lexer       = new GoLexer(input);
                var tokenSource = new GoSemicolonInsertionTokenSource(lexer);
                var tokens      = new CommonTokenStream(tokenSource);
                tokens.Fill();

                // locate the last token before the trigger point
                while (true)
                {
                    IToken nextToken = tokens.LT(1);
                    if (nextToken.Type == CharStreamConstants.EndOfFile)
                    {
                        break;
                    }

                    if (nextToken.StartIndex > triggerPoint.Value.Position)
                    {
                        break;
                    }

                    tokens.Consume();
                }

                switch (tokens.LA(-1))
                {
                case GoLexer.IDENTIFIER:
                    //case GoLexer.KW_THIS:
                    //case GoLexer.KW_UNIV:
                    //case GoLexer.KW_IDEN:
                    //case GoLexer.KW_INT2:
                    //case GoLexer.KW_SEQINT:
                    break;

                default:
                    return;
                }

                Network network = NetworkBuilder <GoSimplifiedAtnBuilder> .GetOrBuildNetwork();

                RuleBinding memberSelectRule = network.GetRule(GoSimplifiedAtnBuilder.RuleNames.PrimaryExpr);
#if false
                HashSet <Transition> memberSelectTransitions = new HashSet <Transition>();
                GetReachableTransitions(memberSelectRule, memberSelectTransitions);
#endif

                NetworkInterpreter interpreter = new NetworkInterpreter(network, tokens);

                interpreter.BoundaryRules.Add(memberSelectRule);
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.Label));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.TypeSwitchGuard));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.FieldName));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.Receiver));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.FunctionDecl));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.BaseTypeName));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.TypeSpec));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.IdentifierList));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.MethodName));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.ParameterDecl));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.FieldIdentifierList));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.PackageName));
                interpreter.BoundaryRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.TypeName));

                interpreter.ExcludedStartRules.Add(network.GetRule(GoSimplifiedAtnBuilder.RuleNames.Block));

                while (interpreter.TryStepBackward())
                {
                    if (interpreter.Contexts.Count == 0)
                    {
                        break;
                    }

                    /* we want all traces to start outside the binOpExpr18 rule, which means all
                     * traces with a transition reachable from binOpExpr18 should contain a push
                     * transition with binOpExpr18's start state as its target.
                     */
                    if (interpreter.Contexts.All(context => context.BoundedStart))
                    {
                        break;
                    }
                }

                interpreter.CombineBoundedStartContexts();

                IOutputWindowPane pane = Provider.OutputWindowService.TryGetPane(PredefinedOutputWindowPanes.TvlIntellisense);
                if (pane != null)
                {
                    pane.WriteLine(string.Format("Located {0} QuickInfo expression(s) in {1}ms.", interpreter.Contexts.Count, stopwatch.ElapsedMilliseconds));
                }

                HashSet <string> finalResult = new HashSet <string>();
                SnapshotSpan?    contextSpan = null;
                foreach (var context in interpreter.Contexts)
                {
                    Span?span = null;
                    //List<string> results = AnalyzeInterpreterTrace(context, memberSelectRule, out span);

                    foreach (var transition in context.Transitions)
                    {
                        if (!transition.Transition.IsMatch)
                        {
                            continue;
                        }

                        IToken token     = transition.Token;
                        Span   tokenSpan = new Span(token.StartIndex, token.StopIndex - token.StartIndex + 1);
                        if (span == null)
                        {
                            span = tokenSpan;
                        }
                        else
                        {
                            span = Span.FromBounds(Math.Min(span.Value.Start, tokenSpan.Start), Math.Max(span.Value.End, tokenSpan.End));
                        }
                    }

                    if (span.HasValue && !span.Value.IsEmpty)
                    {
                        contextSpan = new SnapshotSpan(currentSnapshot, span.Value);
                    }

                    //if (results.Count > 0)
                    //{
                    //    finalResult.UnionWith(results);
                    //    applicableToSpan = currentSnapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive);
                    //}
                }

                foreach (var result in finalResult)
                {
                    quickInfoContent.Add(result);
                }

                #endregion

#if false
                var selection = session.TextView.Selection.StreamSelectionSpan;
                if (selection.IsEmpty || !selection.Contains(new VirtualSnapshotPoint(triggerPoint.Value)))
                {
                    SnapshotSpan?expressionSpan = Provider.IntellisenseCache.GetExpressionSpan(triggerPoint.Value);
                    if (expressionSpan.HasValue)
                    {
                        selection = new VirtualSnapshotSpan(expressionSpan.Value);
                    }
                }
#endif
                VirtualSnapshotSpan selection = new VirtualSnapshotSpan();
                if (contextSpan.HasValue)
                {
                    selection = new VirtualSnapshotSpan(contextSpan.Value);
                }

                if (!selection.IsEmpty && selection.Contains(new VirtualSnapshotPoint(triggerPoint.Value)))
                {
                    applicableToSpan = selection.Snapshot.CreateTrackingSpan(selection.SnapshotSpan, SpanTrackingMode.EdgeExclusive);
                    quickInfoContent.Add(selection.GetText());

                    //try
                    //{
                    //    Expression currentExpression = Provider.IntellisenseCache.ParseExpression(selection);
                    //    if (currentExpression != null)
                    //    {
                    //        SnapshotSpan? span = currentExpression.Span;
                    //        if (span.HasValue)
                    //            applicableToSpan = span.Value.Snapshot.CreateTrackingSpan(span.Value, SpanTrackingMode.EdgeExclusive);

                    //        quickInfoContent.Add(currentExpression.ToString());
                    //    }
                    //    else
                    //    {
                    //        quickInfoContent.Add("Could not parse expression.");
                    //    }
                    //}
                    //catch (Exception ex) when (!ErrorHandler.IsCriticalException(ex))
                    //{
                    //    quickInfoContent.Add(ex.Message);
                    //}
                }
            }
        }
Example #11
0
        public CodeModel CreatePreprocessedModel(ProbeAppSettings appSettings, string fileName, VsText.ITextSnapshot snapshot, bool visible, string reason)
        {
            CodeSource source;
            IEnumerable <Preprocessor.IncludeDependency> includeDependencies = null;

            if (visible)
            {
                source = new CodeSource();
                source.Append(snapshot.GetText(), fileName, 0, snapshot.Length, true, true, false);
                source.Flush();
            }
            else
            {
                var merger = new FileMerger();
                merger.MergeFile(appSettings, fileName, snapshot.GetText(), false, true);
                source = merger.MergedContent;

                includeDependencies = (from f in merger.FileNames
                                       select new Preprocessor.IncludeDependency(f, false, true, merger.GetFileContent(f))).ToArray();
            }

            var model = CreatePreprocessedModel(appSettings, source, fileName, visible, reason, includeDependencies);

            model.Snapshot = snapshot;
            return(model);
        }
Example #12
0
        public CodeModel CreatePreprocessedModel(ProbeAppSettings appSettings, string fileName, VsText.ITextSnapshot snapshot, string reason)
        {
            var source = new CodeSource();

            source.Append(snapshot.GetText(), fileName, 0, snapshot.Length, true, true, false);
            source.Flush();

            var model = CreatePreprocessedModel(appSettings, source, fileName, true, reason, null);

            model.Snapshot = snapshot;
            return(model);
        }
Example #13
0
        public CodeModel RegenerateModel(ProbeAppSettings appSettings, string fileName, VsText.ITextSnapshot snapshot, string reason)
        {
#if DEBUG
            if (snapshot == null)
            {
                throw new ArgumentNullException("snapshot");
            }
#endif

            _model = CreatePreprocessedModel(appSettings, fileName, snapshot, reason);

            var ev = ModelUpdated;
            if (ev != null)
            {
                ev(this, new ModelUpdatedEventArgs(_model));
            }

            return(_model);
        }
Example #14
0
        public CodeModel GetCurrentModel(ProbeAppSettings appSettings, string fileName, VsText.ITextSnapshot snapshot, string reason)
        {
#if DEBUG
            if (snapshot == null)
            {
                throw new ArgumentNullException("snapshot");
            }
#endif

            if (_model != null)
            {
                if (snapshot != null && _model.Snapshot.Version.VersionNumber < snapshot.Version.VersionNumber)
                {
                    _model = CreatePreprocessedModel(appSettings, fileName, snapshot, reason);

                    var ev = ModelUpdated;
                    if (ev != null)
                    {
                        ev(this, new ModelUpdatedEventArgs(_model));
                    }
                }
            }
            else
            {
                _model = CreatePreprocessedModel(appSettings, fileName, snapshot, reason);

                var ev = ModelUpdated;
                if (ev != null)
                {
                    ev(this, new ModelUpdatedEventArgs(_model));
                }
            }

            return(_model);
        }
        private IEnumerable <ISignature> HandleOpenBracket(VsText.ITextSnapshot snapshot, ProbeAppSettings appSettings)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var lineText = snapshot.GetLineTextUpToPosition(_triggerPos);

            var match = _rxFuncBeforeBracket.Match(lineText);

            if (match.Success)
            {
                var line          = snapshot.GetLineFromPosition(_triggerPos);
                var word1         = match.Groups[2].Value;
                var word1Start    = line.Start.Position + match.Groups[2].Index;
                var funcName      = match.Groups[3].Value;
                var funcNameStart = line.Start.Position + match.Groups[3].Index;

                var fileStore = FileStore.GetOrCreateForTextBuffer(_textBuffer);
                if (fileStore != null)
                {
                    if (!string.IsNullOrEmpty(word1))
                    {
                        VsText.ITrackingSpan applicableToSpan = null;

                        var fileName = VsTextUtil.TryGetDocumentFileName(snapshot.TextBuffer);
                        var model    = fileStore.GetMostRecentModel(appSettings, fileName, snapshot, "Signature help after '(' - dot separated words");
                        var modelPos = model.AdjustPosition(word1Start, snapshot);

                        foreach (var word1Def in model.DefinitionProvider.GetAny(modelPos, word1))
                        {
                            if (!word1Def.AllowsChild)
                            {
                                continue;
                            }
                            foreach (var word2Def in word1Def.GetChildDefinitions(funcName))
                            {
                                if (!word2Def.ArgumentsRequired)
                                {
                                    continue;
                                }
                                if (applicableToSpan == null)
                                {
                                    applicableToSpan = snapshot.CreateTrackingSpan(new VsText.Span(_triggerPos, 0), VsText.SpanTrackingMode.EdgeInclusive);
                                }
                                yield return(CreateSignature(_textBuffer, word2Def.ArgumentsSignature, applicableToSpan));
                            }
                        }
                    }
                    else
                    {
                        VsText.ITrackingSpan applicableToSpan = null;

                        var fileName = VsTextUtil.TryGetDocumentFileName(snapshot.TextBuffer);
                        var model    = fileStore.GetMostRecentModel(appSettings, fileName, snapshot, "Signature help after '('");
                        var modelPos = model.AdjustPosition(funcNameStart, snapshot);
                        foreach (var def in model.DefinitionProvider.GetAny(modelPos, funcName))
                        {
                            if (!def.ArgumentsRequired)
                            {
                                continue;
                            }

                            if (applicableToSpan == null)
                            {
                                applicableToSpan = snapshot.CreateTrackingSpan(new VsText.Span(_triggerPos, 0), VsText.SpanTrackingMode.EdgeInclusive);
                            }
                            yield return(CreateSignature(_textBuffer, def.ArgumentsSignature, applicableToSpan));
                        }
                    }
                }
            }
        }
Example #16
0
        public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> quickInfoContent, out ITrackingSpan applicableToSpan)
        {
            applicableToSpan = null;
            if (session == null || quickInfoContent == null)
            {
                return;
            }

            if (session.TextView.TextBuffer == this.TextBuffer)
            {
                ITextSnapshot currentSnapshot = this.TextBuffer.CurrentSnapshot;
                SnapshotPoint?triggerPoint    = session.GetTriggerPoint(currentSnapshot);
                if (!triggerPoint.HasValue)
                {
                    return;
                }

                #region experimental
                /* use the experimental model to locate and process the expression */
                Stopwatch stopwatch = Stopwatch.StartNew();

                // lex the entire document
                var input  = new SnapshotCharStream(currentSnapshot, new Span(0, currentSnapshot.Length));
                var lexer  = new AlloyLexer(input);
                var tokens = new CommonTokenStream(lexer);
                tokens.Fill();

                // locate the last token before the trigger point
                while (true)
                {
                    IToken nextToken = tokens.LT(1);
                    if (nextToken.Type == CharStreamConstants.EndOfFile)
                    {
                        break;
                    }

                    if (nextToken.StartIndex > triggerPoint.Value.Position)
                    {
                        break;
                    }

                    tokens.Consume();
                }

                switch (tokens.LA(-1))
                {
                case AlloyLexer.IDENTIFIER:
                case AlloyLexer.KW_THIS:
                case AlloyLexer.KW_UNIV:
                case AlloyLexer.KW_IDEN:
                case AlloyLexer.KW_INT2:
                case AlloyLexer.KW_SEQINT:
                case AlloyLexer.INTEGER:
                    break;

                default:
                    return;
                }

                Network network = NetworkBuilder <AlloySimplifiedAtnBuilder> .GetOrBuildNetwork();

                RuleBinding memberSelectRule = network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.BinOpExpr18);
#if DEBUG && false
                HashSet <Transition> memberSelectTransitions = new HashSet <Transition>(ObjectReferenceEqualityComparer <Transition> .Default);
                GetReachableTransitions(memberSelectRule, memberSelectTransitions);
#endif

                NetworkInterpreter interpreter = new NetworkInterpreter(network, tokens);

                interpreter.BoundaryRules.Add(memberSelectRule);
                //interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.UnaryExpression));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.LetDecl));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.NameListName));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.Ref));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.Module));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.Open));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.FactDecl));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.AssertDecl));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.FunctionName));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.CmdDecl));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.Typescope));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.EnumDecl));
                interpreter.BoundaryRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.ElseClause));

                interpreter.ExcludedStartRules.Add(network.GetRule(AlloySimplifiedAtnBuilder.RuleNames.CallArguments));

                while (interpreter.TryStepBackward())
                {
                    if (interpreter.Contexts.Count == 0)
                    {
                        break;
                    }

                    /* we want all traces to start outside the binOpExpr18 rule, which means all
                     * traces with a transition reachable from binOpExpr18 should contain a push
                     * transition with binOpExpr18's start state as its target.
                     */
                    if (interpreter.Contexts.All(context => context.BoundedStart))
                    {
                        break;
                    }
                }

                HashSet <InterpretTrace> contexts = new HashSet <InterpretTrace>(BoundedStartInterpretTraceEqualityComparer.Default);
                if (interpreter.Contexts.Count > 0)
                {
                    contexts.UnionWith(interpreter.Contexts);
                }
                else
                {
                    contexts.UnionWith(interpreter.BoundedStartContexts);
                }

                IOutputWindowPane pane = Provider.OutputWindowService.TryGetPane(PredefinedOutputWindowPanes.TvlIntellisense);
                if (pane != null)
                {
                    pane.WriteLine(string.Format("Located {0} QuickInfo expression(s) in {1}ms.", contexts.Count, stopwatch.ElapsedMilliseconds));
                }

                HashSet <Span> spans = new HashSet <Span>();
                foreach (var context in contexts)
                {
                    Span?span = null;
                    foreach (var transition in context.Transitions)
                    {
                        if (!transition.Transition.IsMatch)
                        {
                            continue;
                        }

                        IToken token     = transition.Token;
                        Span   tokenSpan = new Span(token.StartIndex, token.StopIndex - token.StartIndex + 1);
                        if (span == null)
                        {
                            span = tokenSpan;
                        }
                        else
                        {
                            span = Span.FromBounds(Math.Min(span.Value.Start, tokenSpan.Start), Math.Max(span.Value.End, tokenSpan.End));
                        }
                    }

                    if (span.HasValue)
                    {
                        spans.Add(span.Value);
                    }
                }

                //List<Expression> expressions = new List<Expression>();
                //HashSet<string> finalResult = new HashSet<string>();
                //SnapshotSpan? contextSpan = null;

                bool foundInfo = false;
                foreach (var span in spans)
                {
                    if (!span.IsEmpty)
                    {
                        VirtualSnapshotSpan selection = new VirtualSnapshotSpan(new SnapshotSpan(currentSnapshot, span));
                        if (!selection.IsEmpty && selection.Contains(new VirtualSnapshotPoint(triggerPoint.Value)))
                        {
                            try
                            {
                                Expression currentExpression = Provider.IntellisenseCache.ParseExpression(selection);
                                if (currentExpression != null && currentExpression.Span.HasValue && currentExpression.Span.Value.Contains(triggerPoint.Value))
                                {
                                    applicableToSpan = currentExpression.Span.Value.Snapshot.CreateTrackingSpan(currentExpression.Span.Value, SpanTrackingMode.EdgeExclusive);
                                    quickInfoContent.Add(currentExpression.ToString());
                                    foundInfo = true;
                                }
                            }
                            catch (Exception ex)
                            {
                                if (ErrorHandler.IsCriticalException(ex))
                                {
                                    throw;
                                }

                                quickInfoContent.Add(ex.Message);
                            }
                        }

                        //try
                        //{
                        //    SnapshotSpan contextSpan = new SnapshotSpan(currentSnapshot, span.Value);
                        //    Expression expression = Provider.IntellisenseCache.ParseExpression(contextSpan);
                        //    if (expression != null)
                        //        expressions.Add(expression);
                        //}
                        //catch (Exception e)
                        //{
                        //    if (ErrorHandler.IsCriticalException(e))
                        //        throw;
                        //}
                    }

                    //if (results.Count > 0)
                    //{
                    //    finalResult.UnionWith(results);
                    //    applicableToSpan = currentSnapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive);
                    //}
                }

                if (!foundInfo && spans.Count > 0)
                {
                    foreach (var span in spans)
                    {
                        if (!span.IsEmpty)
                        {
                            VirtualSnapshotSpan selection = new VirtualSnapshotSpan(new SnapshotSpan(currentSnapshot, span));
                            if (!selection.IsEmpty && selection.Contains(new VirtualSnapshotPoint(triggerPoint.Value)))
                            {
                                applicableToSpan = selection.Snapshot.CreateTrackingSpan(selection.SnapshotSpan, SpanTrackingMode.EdgeExclusive);
                                break;
                            }
                        }
                    }

                    quickInfoContent.Add("Could not parse expression.");
                }

                //foreach (var result in finalResult)
                //{
                //    quickInfoContent.Add(result);
                //}

                #endregion

#if false
                var selection = session.TextView.Selection.StreamSelectionSpan;
                if (selection.IsEmpty || !selection.Contains(new VirtualSnapshotPoint(triggerPoint.Value)))
                {
                    SnapshotSpan?expressionSpan = Provider.IntellisenseCache.GetExpressionSpan(triggerPoint.Value);
                    if (expressionSpan.HasValue)
                    {
                        selection = new VirtualSnapshotSpan(expressionSpan.Value);
                    }
                }
#endif
                //VirtualSnapshotSpan selection = new VirtualSnapshotSpan();
                //if (contextSpan.HasValue)
                //    selection = new VirtualSnapshotSpan(contextSpan.Value);

                //if (!selection.IsEmpty && selection.Contains(new VirtualSnapshotPoint(triggerPoint.Value)))
                //{
                //    applicableToSpan = selection.Snapshot.CreateTrackingSpan(selection.SnapshotSpan, SpanTrackingMode.EdgeExclusive);

                //    try
                //    {
                //        Expression currentExpression = Provider.IntellisenseCache.ParseExpression(selection);
                //        if (currentExpression != null)
                //        {
                //            SnapshotSpan? span = currentExpression.Span;
                //            if (span.HasValue)
                //                applicableToSpan = span.Value.Snapshot.CreateTrackingSpan(span.Value, SpanTrackingMode.EdgeExclusive);

                //            quickInfoContent.Add(currentExpression.ToString());
                //        }
                //        else
                //        {
                //            quickInfoContent.Add("Could not parse expression.");
                //        }
                //    }
                //    catch (Exception ex)
                //    {
                //        if (ErrorHandler.IsCriticalException(ex))
                //            throw;

                //        quickInfoContent.Add(ex.Message);
                //    }
                //}
            }
        }
Example #17
0
        public static void Run(string sourceFileName, VsText.ITextSnapshot snapshot)
        {
            if (string.IsNullOrWhiteSpace(sourceFileName))
            {
                return;
            }

            Log.Debug("Running background FEC for file '{0}'.", sourceFileName);

            var counter = 10;

            while (counter > 0)
            {
                if (!ProbeCompiler.Instance.Mutex.WaitOne(1000))
                {
                    Log.Debug("Waiting for other compile/FEC operation to complete...");
                    counter--;
                    if (counter == 0)
                    {
                        Log.Debug("Ran out of retries when waiting for compile/FEC operation to complete.");
                        return;
                    }
                }
                else
                {
                    break;
                }
            }

            try
            {
                var first       = true;
                var reportError = new Action <ErrorTask>(task =>
                {
                    if (first)
                    {
                        first = false;
                        //ErrorTaskProvider.Instance.RemoveAllForFile(sourceFileName);
                        ErrorTaskProvider.Instance.RemoveAllForSource(ErrorTaskSource.BackgroundFec, sourceFileName);
                    }
                    if (task != null)
                    {
                        ErrorTaskProvider.Instance.Add(task);
                    }
                });

                var output = new CallbackOutput(line =>
                {
                    var index = line.IndexOf(": error :");
                    if (index >= 0)
                    {
                        Log.Debug("Background FEC error: {0}", line);

                        string fileName;
                        int lineNum;
                        if (ProbeCompiler.ParseFileNameAndLine(line.Substring(0, index), out fileName, out lineNum))
                        {
                            var message = line.Substring(index + ": error :".Length).Trim();
                            var task    = new ErrorTask(fileName, lineNum - 1, -1, message, ErrorType.Error, ErrorTaskSource.BackgroundFec, sourceFileName, snapshot);
                            reportError(task);
                        }
                        return;
                    }

                    index = line.IndexOf(": warning :");
                    if (index >= 0)
                    {
                        Log.Debug("Background FEC warning: {0}", line);

                        string fileName;
                        int lineNum;
                        if (ProbeCompiler.ParseFileNameAndLine(line.Substring(0, index), out fileName, out lineNum))
                        {
                            var message = line.Substring(index + ": warning :".Length).Trim();
                            var task    = new ErrorTask(fileName, lineNum - 1, -1, message, ErrorType.Warning, ErrorTaskSource.BackgroundFec, sourceFileName, snapshot);
                            reportError(task);
                        }
                        return;
                    }
                });

                var workingDir = ProbeToolsPackage.TempDir;

                var runner = new ProcessRunner();
                runner.CaptureOutput = true;
                runner.CaptureError  = true;

                var exitCode = runner.CaptureProcess("fec.exe", string.Concat("\"", sourceFileName, "\""), workingDir, output);
                if (exitCode == 0)
                {
                    if (first)
                    {
                        reportError(null);
                    }
                    Log.Debug("Background FEC completed successfully.");
                }
                else
                {
                    Log.Write(LogLevel.Warning, "FEC.exe returned exit code {0} when running background FEC for file '{1}'.", exitCode, sourceFileName);
                }
            }
            catch (Exception ex)
            {
                Log.WriteEx(ex);
            }
            finally
            {
                ProbeCompiler.Instance.Mutex.ReleaseMutex();
            }
        }
Example #18
0
        public IEnumerable <FunctionDropDownItem> GetFunctionDropDownList(ProbeAppSettings appSettings,
                                                                          string fileName, VsText.ITextSnapshot snapshot)
        {
            var model = GetMostRecentModel(appSettings, fileName, snapshot, "Function drop-down list.");

            var prepModel = model.PreprocessorModel;

            if (prepModel == null)
            {
                yield break;
            }

            foreach (var func in model.PreprocessorModel.LocalFunctions)
            {
                var def = func.Definition;
                if (def.EntireSpan.Length == 0)
                {
                    continue;
                }
                if (!def.SourceFileName.Equals(model.FileName, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                yield return(new FunctionDropDownItem
                {
                    Name = def.Name,
                    Span = new Span(def.SourceStartPos, def.SourceStartPos),
                    EntireFunctionSpan = def.EntireSpan
                });
            }
        }