示例#1
0
        /// <inheritdoc />
        public string Format(object obj)
        {
            if (obj == null)
            {
                return(@"null");
            }

            Type type = obj.GetType();

            try
            {
                IFormattingRule rule = GetPreferredRule(type);

                if (rule != null)
                {
                    string result = rule.Format(obj, this);

                    if (!string.IsNullOrEmpty(result))
                    {
                        return(result);
                    }
                }
            }
            catch
            {
                // Ignore exceptions.
            }

            return(String.Concat("{", type.ToString(), "}"));
        }
示例#2
0
 public ContainedLanguage(
     IVsTextBufferCoordinator bufferCoordinator,
     IComponentModel componentModel,
     AbstractProject project,
     IVsHierarchy hierarchy,
     uint itemid,
     TLanguageService languageService,
     SourceCodeKind sourceCodeKind,
     IFormattingRule vbHelperFormattingRule,
     Workspace workspace
     )
     : base(
         bufferCoordinator,
         componentModel,
         project.VisualStudioProject,
         hierarchy,
         itemid,
         project.ProjectTracker,
         project.Id,
         languageService.LanguageServiceId,
         vbHelperFormattingRule: null
         )
 {
     Contract.ThrowIfTrue(vbHelperFormattingRule != null);
 }
        public BaseIndentationFormattingRule(SyntaxNode root, TextSpan span, int baseIndentation, IFormattingRule vbHelperFormattingRule = null)
        {
            _span = span;
            SetInnermostNodeForSpan(root, ref _span, out _token1, out _token2, out _commonNode);

            _baseIndentation = baseIndentation;
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }
示例#4
0
        public BaseIndentationFormattingRule(SyntaxNode root, TextSpan span, int baseIndentation, IFormattingRule vbHelperFormattingRule = null)
        {
            _span = span;
            SetInnermostNodeForSpan(root, ref _span, out _token1, out _token2, out _commonNode);

            _baseIndentation        = baseIndentation;
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }
        public BaseIndentationFormattingRule(SyntaxNode root, TextSpan span, int baseIndentation, IFormattingRule vbHelperFormattingRule = null)
        {
            this.span = span;
            SetInnermostNodeForSpan(root, ref this.span, out token1, out token2, out commonNode);

            this.baseIndentation        = baseIndentation;
            this.vbHelperFormattingRule = vbHelperFormattingRule;
        }
        public BaseIndentationFormattingRule(SyntaxNode root, TextSpan span, int baseIndentation, IFormattingRule vbHelperFormattingRule = null)
        {
            this.span = span;
            SetInnermostNodeForSpan(root, ref this.span, out token1, out token2, out commonNode);

            this.baseIndentation = baseIndentation;
            this.vbHelperFormattingRule = vbHelperFormattingRule;
        }
        private Task <SyntaxNode> GetSyntaxRootAndFilter(IFormattingRule formattingRule, Document document, CancellationToken cancellationToken)
        {
            if (!formattingRule.SupportsLanguage(document.Project.Language))
            {
                return(Task.FromResult <SyntaxNode>(null));
            }

            return(GetSyntaxRootAndFilter(document, cancellationToken));
        }
示例#8
0
        public static async Task <IList <Diagnostic> > EvaluateRuleAsync(IFormattingRule rule, string code)
        {
            // Create an Ad-Hoc Workspace
            var workspace = new AdhocWorkspace();
            var project   = workspace.AddProject("TestProject", LanguageNames.CSharp);
            var doc       = project.AddDocument("TestDocument", SourceText.From(code));

            // Run the rule results
            return(await rule.EvaluateAsync(doc));
        }
        /// <summary>
        /// Creates a rule-based formatter.
        /// </summary>
        /// <param name="rules">The rules to use.</param>
        /// <param name="extensionPoints">The entry point for framework extensions.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="rules"/> is null.</exception>
        public RuleBasedFormatter(IExtensionPoints extensionPoints, IFormattingRule[] rules)
        {
            if (extensionPoints == null)
                throw new ArgumentNullException("extensionPoints");
            if (rules == null)
                throw new ArgumentNullException("rules");

            this.rules = new List<IFormattingRule>(rules);
            this.preferredRules = new Dictionary<Type, IFormattingRule>();
            this.extensionPoints = extensionPoints;
        }
示例#10
0
        internal ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            VisualStudioProject project,
            IVsHierarchy hierarchy,
            uint itemid,
            VisualStudioProjectTracker projectTrackerOpt,
            ProjectId projectId,
            TLanguageService languageService,
            IFormattingRule vbHelperFormattingRule = null)
        {
            this.BufferCoordinator = bufferCoordinator;
            this.ComponentModel    = componentModel;
            this.Project           = project;
            _languageService       = languageService;

            this.Workspace = projectTrackerOpt?.Workspace ?? componentModel.GetService <VisualStudioWorkspace>();

            _editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();
            _diagnosticAnalyzerService    = componentModel.GetService <IDiagnosticAnalyzerService>();

            // Get the ITextBuffer for the secondary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines));
            var secondaryVsTextBuffer = (IVsTextBuffer)secondaryTextLines;

            SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryVsTextBuffer);

            // Get the ITextBuffer for the primary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines));
            DataBuffer = _editorAdaptersFactoryService.GetDataBuffer((IVsTextBuffer)primaryTextLines);

            // Create our tagger
            var bufferTagAggregatorFactory = ComponentModel.GetService <IBufferTagAggregatorFactoryService>();

            _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator <ITag>(SubjectBuffer);

            if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath)))
            {
                // we couldn't look up the document moniker from an hierarchy for an itemid.
                // Since we only use this moniker as a key, we could fall back to something else, like the document name.
                Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
                if (!hierarchy.TryGetItemName(itemid, out filePath))
                {
                    FatalError.Report(new System.Exception("Failed to get document moniker for a contained document"));
                }
            }

            DocumentId documentId;

            if (this.Project != null)
            {
                documentId = this.Project.AddSourceTextContainer(
                    SubjectBuffer.AsTextContainer(), filePath,
                    sourceCodeKind: SourceCodeKind.Regular, folders: default,
示例#11
0
        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);

            _containedLanguage = containedLanguage;
            _sourceCodeKind    = sourceCodeKind;
            _componentModel    = componentModel;
            _workspace         = workspace;
            _optionService     = _workspace.Services.GetService <IOptionService>();
            _hostType          = GetHostType();

            var rdt = (IVsRunningDocumentTable)componentModel.GetService <SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable));

            IVsHierarchy sharedHierarchy;
            uint         itemIdInSharedHierarchy;
            var          isSharedHierarchy = LinkedFileUtilities.TryGetSharedHierarchyAndItemId(hierarchy, itemId, out sharedHierarchy, out itemIdInSharedHierarchy);

            var filePath = isSharedHierarchy
                ? rdt.GetMonikerForHierarchyAndItemId(sharedHierarchy, itemIdInSharedHierarchy)
                : rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId);

            // we couldn't look up the document moniker in RDT for a hierarchy/item pair
            // Since we only use this moniker as a key, we could fall back to something else, like the document name.
            if (filePath == null)
            {
                Debug.Assert(false, "Could not get the document moniker for an item in its hierarchy.");
                filePath = hierarchy.GetDocumentNameForHierarchyAndItemId(itemId);
            }

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key     = new DocumentKey(Project, filePath);
            this.Id      = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = containedLanguage.Project.GetFolderNames(itemId);
            this.Loader  = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService <ITextDifferencingSelectorService>();
            _snapshotTracker           = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule    = vbHelperFormattingRule;
        }
示例#12
0
        public override IEnumerable <IFormattingRule> GetDefaultFormattingRules()
        {
            var rules = this.lazyExportedRules.Value;

            var spaceFormattingRules = new IFormattingRule[]
            {
                new WrappingFormattingRule(),
                new SpacingFormattingRule(),
                new NewLineUserSettingFormattingRule(),
                new IndentUserSettingsFormattingRule()
            };

            return(spaceFormattingRules.Concat(rules).ToImmutableArray());
        }
        public override IEnumerable<IFormattingRule> GetDefaultFormattingRules()
        {
            var rules = this.lazyExportedRules.Value;

            var spaceFormattingRules = new IFormattingRule[]
                {
                    new WrappingFormattingRule(),
                    new SpacingFormattingRule(),
                    new NewLineUserSettingFormattingRule(),
                    new IndentUserSettingsFormattingRule()
                };

            return spaceFormattingRules.Concat(rules).ToImmutableList();
        }
 public IFormattingRule GetCompiledRule(ILogEnvironment environment)
 {
     if (_compiledRule == null)
     {
         try
         {
             _compiledRule = ComplieRule();
             _compiledRule.SetEnvironment(environment);
         }
         catch
         {
             _compiledRule = DummyRule.Instance;
         }
     }
     return(_compiledRule);
 }
        public void SetUpFormatter()
        {
            extensionPoints = new DefaultExtensionPoints();

            IConverter converter = new RuleBasedConverter(extensionPoints, new IConversionRule[]
            {
                new ObjectToStringConversionRule()
            });

            formattingRule = new T();

            formatter = new RuleBasedFormatter(extensionPoints, new IFormattingRule[]
            {
                formattingRule,
                new ConvertToStringFormattingRule(converter)
            });
        }
示例#16
0
        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);
            Contract.ThrowIfFalse(containedLanguage.Project is AbstractLegacyProject);

            _containedLanguage = containedLanguage;
            _sourceCodeKind    = sourceCodeKind;
            _componentModel    = componentModel;
            _workspace         = workspace;
            _hostType          = GetHostType();

            string filePath;

            if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemId, out filePath)))
            {
                // we couldn't look up the document moniker from an hierarchy for an itemid.
                // Since we only use this moniker as a key, we could fall back to something else, like the document name.
                Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
                if (!hierarchy.TryGetItemName(itemId, out filePath))
                {
                    Environment.FailFast("Failed to get document moniker for a contained document");
                }
            }

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key     = new DocumentKey(Project, filePath);
            this.Id      = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = ((AbstractLegacyProject)containedLanguage.Project).GetFolderNames(itemId);
            this.Loader  = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService <ITextDifferencingSelectorService>();
            _snapshotTracker           = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule    = vbHelperFormattingRule;
        }
示例#17
0
        private IFormattingRule GetPreferredRuleWithoutCache(Type type)
        {
            int             bestPriority = int.MinValue;
            IFormattingRule bestRule     = null;

            foreach (IFormattingRule rule in rules)
            {
                int?priority = rule.GetPriority(type);

                if (priority.HasValue && priority.Value >= bestPriority)
                {
                    bestPriority = priority.Value;
                    bestRule     = rule;
                }
            }

            return(bestRule);
        }
示例#18
0
 public ContainedLanguage(
     IVsTextBufferCoordinator bufferCoordinator,
     IComponentModel componentModel,
     AbstractProject project,
     IVsHierarchy hierarchy,
     uint itemid,
     TLanguageService languageService,
     SourceCodeKind sourceCodeKind,
     IFormattingRule vbHelperFormattingRule)
     : this(bufferCoordinator,
            componentModel,
            project.VisualStudioProject,
            hierarchy,
            itemid,
            languageService,
            vbHelperFormattingRule)
 {
 }
示例#19
0
        public static async Task SingleErrorTestAsync(IFormattingRule rule, string code, DiagnosticDescriptor expectedDescriptor, string expectedMessage = null)
        {
            MarkupTestFile.GetSpan(code, out code, out var expectedLocation);

            var actualDiagnostics = await EvaluateRuleAsync(rule, code);

            Assert.Collection(actualDiagnostics,
                              diagnostic =>
            {
                // Check ID specially so that we get a friendly error if the descriptor doesn't match
                Assert.Equal(expectedDescriptor.Id, diagnostic.Id);
                Assert.Same(expectedDescriptor, diagnostic.Descriptor);

                if (expectedMessage != null)
                {
                    Assert.Equal(expectedMessage, diagnostic.GetMessage());
                }

                Assert.Equal(expectedLocation, diagnostic.Location.SourceSpan);
            });
        }
        private IEnumerable <string> CalcSpaces(FormattingStageContext formattingStageContext)
        {
            IFormattingRule currentRule = null;

            foreach (var formattingRule in myFormatter.FormattingRules)
            {
                if (formattingRule.Match(formattingStageContext))
                {
                    if (currentRule == null)
                    {
                        if (formattingRule.GetPriority() > 0)
                        {
                            currentRule = formattingRule;
                        }
                    }
                    else
                    {
                        if (formattingRule.GetPriority() > currentRule.GetPriority())
                        {
                            currentRule = formattingRule;
                        }
                    }
                }
            }

            if (currentRule != null)
            {
                return(currentRule.Space(formattingStageContext, this));
            }
            if (IsTokensGlued(formattingStageContext))
            {
                //return new[] {" "};
                return(null);
            }
            else
            {
                return(new[] { "" });
            }
        }
示例#21
0
 public static IEnumerable <IFormattingRule> Concat(this IFormattingRule rule, IEnumerable <IFormattingRule> rules)
 {
     return(SpecializedCollections.SingletonEnumerable(rule).Concat(rules));
 }
示例#22
0
        internal ContainedLanguage(
            IVsTextBufferCoordinator bufferCoordinator,
            IComponentModel componentModel,
            VisualStudioProject project,
            IVsHierarchy hierarchy,
            uint itemid,
            VisualStudioProjectTracker projectTrackerOpt,
            ProjectId projectId,
            TLanguageService languageService,
            IFormattingRule vbHelperFormattingRule = null)
        {
            this.BufferCoordinator = bufferCoordinator;
            this.ComponentModel    = componentModel;
            this.Project           = project;
            _languageService       = languageService;

            this.Workspace = projectTrackerOpt?.Workspace ?? componentModel.GetService <VisualStudioWorkspace>();

            _editorAdaptersFactoryService = componentModel.GetService <IVsEditorAdaptersFactoryService>();
            _diagnosticAnalyzerService    = componentModel.GetService <IDiagnosticAnalyzerService>();

            // Get the ITextBuffer for the secondary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetSecondaryBuffer(out var secondaryTextLines));
            var secondaryVsTextBuffer = (IVsTextBuffer)secondaryTextLines;

            SubjectBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(secondaryVsTextBuffer);

            // Get the ITextBuffer for the primary buffer
            Marshal.ThrowExceptionForHR(bufferCoordinator.GetPrimaryBuffer(out var primaryTextLines));
            DataBuffer = _editorAdaptersFactoryService.GetDataBuffer((IVsTextBuffer)primaryTextLines);

            // Create our tagger
            var bufferTagAggregatorFactory = ComponentModel.GetService <IBufferTagAggregatorFactoryService>();

            _bufferTagAggregator = bufferTagAggregatorFactory.CreateTagAggregator <ITag>(SubjectBuffer);

            if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemid, out var filePath)))
            {
                // we couldn't look up the document moniker from an hierarchy for an itemid.
                // Since we only use this moniker as a key, we could fall back to something else, like the document name.
                Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
                if (!hierarchy.TryGetItemName(itemid, out filePath))
                {
                    FatalError.Report(new System.Exception("Failed to get document moniker for a contained document"));
                }
            }

            DocumentId documentId;

            if (this.Project != null)
            {
                documentId = this.Project.AddSourceTextContainer(SubjectBuffer.AsTextContainer(), filePath);
            }
            else
            {
                documentId = DocumentId.CreateNewId(projectId, $"{nameof(ContainedDocument)}: {filePath}");

                // We must jam a document into an existing workspace, which we'll assume is safe to do with OnDocumentAdded
                Workspace.OnDocumentAdded(DocumentInfo.Create(documentId, filePath, filePath: filePath));
                Workspace.OnDocumentOpened(documentId, SubjectBuffer.AsTextContainer());
            }

            this.ContainedDocument = new ContainedDocument(
                componentModel.GetService <IThreadingContext>(),
                documentId,
                subjectBuffer: SubjectBuffer,
                dataBuffer: DataBuffer,
                bufferCoordinator,
                this.Workspace,
                project,
                hierarchy,
                itemid,
                componentModel,
                vbHelperFormattingRule);

            // TODO: Can contained documents be linked or shared?
            this.DataBuffer.Changed += OnDataBufferChanged;
        }
        private Task<SyntaxNode> GetSyntaxRootAndFilter(IFormattingRule formattingRule, Document document, CancellationToken cancellationToken)
        {
            if (!formattingRule.SupportsLanguage(document.Project.Language))
            {
                return Task.FromResult<SyntaxNode>(null);
            }

            return GetSyntaxRootAndFilter(document, cancellationToken);
        }
        /// <summary>
        /// Ensure that an event handler exists for a given event.
        /// </summary>
        /// <param name="thisDocument">The document corresponding to this operation.</param>
        /// <param name="targetDocument">The document to generate the event handler in if it doesn't
        /// exist.</param>
        /// <param name="className">The name of the type to generate the event handler in.</param>
        /// <param name="objectName">The name of the event member (if <paramref
        /// name="useHandlesClause"/> is true)</param>
        /// <param name="objectTypeName">The name of the type containing the event.</param>
        /// <param name="nameOfEvent">The name of the event member in <paramref
        /// name="objectTypeName"/></param>
        /// <param name="eventHandlerName">The name of the method to be hooked up to the
        /// event.</param>
        /// <param name="itemidInsertionPoint">The VS itemid of the file to generate the event
        /// handler in.</param>
        /// <param name="useHandlesClause">If true, a vb "Handles" clause will be generated for the
        /// handler.</param>
        /// <param name="additionalFormattingRule">An additional formatting rule that can be used to
        /// format the newly inserted method</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>Either the unique id of the method if it already exists, or the unique id of
        /// the to be generated method, the text of the to be generated method, and the position in
        /// <paramref name="itemidInsertionPoint"/> where the text should be inserted.</returns>
        public static Tuple<string, string, VsTextSpan> EnsureEventHandler(
            Document thisDocument,
            Document targetDocument,
            string className,
            string objectName,
            string objectTypeName,
            string nameOfEvent,
            string eventHandlerName,
            uint itemidInsertionPoint,
            bool useHandlesClause,
            IFormattingRule additionalFormattingRule,
            CancellationToken cancellationToken)
        {
            var thisCompilation = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var type = thisCompilation.GetTypeByMetadataName(className);

            var existingEventHandlers = GetCompatibleEventHandlers(targetDocument, className, objectTypeName, nameOfEvent, cancellationToken);
            var existingHandler = existingEventHandlers.SingleOrDefault(e => e.Item1 == eventHandlerName);
            if (existingHandler != null)
            {
                return Tuple.Create(existingHandler.Item2, (string)null, default(VsTextSpan));
            }

            // Okay, it doesn't exist yet.  Let's create it.
            var codeGenerationService = targetDocument.GetLanguageService<ICodeGenerationService>();
            var syntaxFactory = targetDocument.GetLanguageService<SyntaxGenerator>();
            var eventMember = GetEventSymbol(thisDocument, objectTypeName, nameOfEvent, type, cancellationToken);
            if (eventMember == null)
            {
                throw new InvalidOperationException();
            }

            var eventType = ((IEventSymbol)eventMember).Type;
            if (eventType.Kind != SymbolKind.NamedType || ((INamedTypeSymbol)eventType).DelegateInvokeMethod == null)
            {
                throw new InvalidOperationException(ServicesVSResources.EventTypeIsInvalid);
            }

            var handlesExpressions = useHandlesClause ?
                new[]
                {
                    syntaxFactory.MemberAccessExpression(
                        objectName != null ? syntaxFactory.IdentifierName(objectName) : syntaxFactory.ThisExpression(),
                        syntaxFactory.IdentifierName(nameOfEvent))
                }
            : null;

            var invokeMethod = ((INamedTypeSymbol)eventType).DelegateInvokeMethod;
            var newMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
                attributes: null,
                accessibility: Accessibility.Protected,
                modifiers: new DeclarationModifiers(),
                returnType: targetDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetSpecialType(SpecialType.System_Void),
                explicitInterfaceSymbol: null,
                name: eventHandlerName,
                typeParameters: null,
                parameters: invokeMethod.Parameters.ToArray(),
                statements: null,
                handlesExpressions: handlesExpressions);

            var annotation = new SyntaxAnnotation();
            newMethod = annotation.AddAnnotationToSymbol(newMethod);
            var codeModel = targetDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>();
            var syntaxFacts = targetDocument.Project.LanguageServices.GetService<ISyntaxFactsService>();

            var targetSyntaxTree = targetDocument.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            var position = type.Locations.First(loc => loc.SourceTree == targetSyntaxTree).SourceSpan.Start;
            var destinationType = syntaxFacts.GetContainingTypeDeclaration(targetSyntaxTree.GetRoot(cancellationToken), position);
            var insertionPoint = codeModel.GetEndPoint(destinationType, EnvDTE.vsCMPart.vsCMPartBody);

            if (insertionPoint == null)
            {
                throw new InvalidOperationException(ServicesVSResources.MemberInsertionFailed);
            }

            var newType = codeGenerationService.AddMethod(destinationType, newMethod, new CodeGenerationOptions(autoInsertionLocation: false), cancellationToken);
            var newRoot = targetSyntaxTree.GetRoot(cancellationToken).ReplaceNode(destinationType, newType);

            newRoot = Simplifier.ReduceAsync(targetDocument.WithSyntaxRoot(newRoot), Simplifier.Annotation, null, cancellationToken).WaitAndGetResult(cancellationToken).GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            var formattingRules = additionalFormattingRule.Concat(Formatter.GetDefaultFormattingRules(targetDocument));

            var workspace = targetDocument.Project.Solution.Workspace;
            newRoot = Formatter.Format(newRoot, Formatter.Annotation, workspace, workspace.Options, formattingRules, cancellationToken);

            var newMember = newRoot.GetAnnotatedNodesAndTokens(annotation).Single();
            var newMemberText = newMember.ToFullString();

            // In VB, the final newline is likely a statement terminator in the parent - just add
            // one on so that things don't get messed.
            if (!newMemberText.EndsWith(Environment.NewLine, StringComparison.Ordinal))
            {
                newMemberText += Environment.NewLine;
            }

            return Tuple.Create(ConstructMemberId(newMethod), newMemberText, insertionPoint.Value.ToVsTextSpan());
        }
示例#25
0
        private void AdjustIndentationForSpan(
            Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options)
        {
            var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);

            using (var rulePool = SharedPools.Default<List<IFormattingRule>>().GetPooledObject())
            using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject())
            {
                var venusFormattingRules = rulePool.Object;
                var visibleSpans = spanPool.Object;

                venusFormattingRules.Add(baseIndentationRule);
                venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance);

                var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document));

                var workspace = document.Project.Solution.Workspace;
                var changes = Formatter.GetFormattedTextChanges(
                    root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) },
                    workspace, options, formattingRules, CancellationToken.None);

                visibleSpans.Add(visibleSpan);
                var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span));

                foreach (var change in newChanges)
                {
                    edit.Replace(change.Span.ToSpan(), change.NewText);
                }
            }
        }
示例#26
0
        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);

            _containedLanguage = containedLanguage;
            _sourceCodeKind = sourceCodeKind;
            _componentModel = componentModel;
            _workspace = workspace;
            _optionService = _workspace.Services.GetService<IOptionService>();
            _hostType = GetHostType();

            var rdt = (IVsRunningDocumentTable)componentModel.GetService<SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable));

            IVsHierarchy sharedHierarchy;
            uint itemIdInSharedHierarchy;
            var isSharedHierarchy = LinkedFileUtilities.TryGetSharedHierarchyAndItemId(hierarchy, itemId, out sharedHierarchy, out itemIdInSharedHierarchy);

            var filePath = isSharedHierarchy
                ? rdt.GetMonikerForHierarchyAndItemId(sharedHierarchy, itemIdInSharedHierarchy)
                : rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId);

            // we couldn't look up the document moniker in RDT for a hierarchy/item pair
            // Since we only use this moniker as a key, we could fall back to something else, like the document name.
            if (filePath == null)
            {
                Debug.Assert(false, "Could not get the document moniker for an item in its hierarchy.");
                filePath = hierarchy.GetDocumentNameForHierarchyAndItemId(itemId);
            }

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key = new DocumentKey(Project, filePath);
            this.Id = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = containedLanguage.Project.GetFolderNames(itemId);
            this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
            _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }
示例#27
0
        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);

            _containedLanguage = containedLanguage;
            _sourceCodeKind = sourceCodeKind;
            _componentModel = componentModel;
            _workspace = workspace;
            _optionService = _workspace.Services.GetService<IOptionService>();
            _hostType = GetHostType();

            string filePath;
            if (!ErrorHandler.Succeeded(((IVsProject)hierarchy).GetMkDocument(itemId, out filePath)))
            {
                // we couldn't look up the document moniker from an hierarchy for an itemid.
                // Since we only use this moniker as a key, we could fall back to something else, like the document name.
                Debug.Assert(false, "Could not get the document moniker for an item from its hierarchy.");
                if (!hierarchy.TryGetItemName(itemId, out filePath))
                {
                    Environment.FailFast("Failed to get document moniker for a contained document");
                }
            }

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key = new DocumentKey(Project, filePath);
            this.Id = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = containedLanguage.Project.GetFolderNames(itemId);
            this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
            _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }
示例#28
0
        public ContainedDocument(
            AbstractContainedLanguage containedLanguage,
            SourceCodeKind sourceCodeKind,
            Workspace workspace,
            IVsHierarchy hierarchy,
            uint itemId,
            IComponentModel componentModel,
            IFormattingRule vbHelperFormattingRule)
        {
            Contract.ThrowIfNull(containedLanguage);

            _containedLanguage = containedLanguage;
            _sourceCodeKind = sourceCodeKind;
            _componentModel = componentModel;
            _workspace = workspace;
            _optionService = _workspace.Services.GetService<IOptionService>();
            _hostType = GetHostType();

            var rdt = (IVsRunningDocumentTable)componentModel.GetService<SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable));
            var filePath = rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId);

            if (Project.Hierarchy != null)
            {
                string moniker;
                Project.Hierarchy.GetCanonicalName(itemId, out moniker);
                _itemMoniker = moniker;
            }

            this.Key = new DocumentKey(Project, filePath);
            this.Id = DocumentId.CreateNewId(Project.Id, filePath);
            this.Folders = containedLanguage.Project.GetFolderNames(itemId);
            this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath);
            _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>();
            _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer);
            _vbHelperFormattingRule = vbHelperFormattingRule;
        }