private void MakeFormat(FormattingRange range, IEnumerable <string> space)
        {
            PsiFormatterHelper.ReplaceSpaces(range.First, range.Last, space);

            // TODO: Move antiglueing logic into CalcSpaces()
            ITokenNode nextToken;
            ITokenNode prevToken = range.First.FindLastTokenIn();

            if (prevToken != null)
            {
                nextToken = prevToken.GetNextToken();
            }
            else
            {
                nextToken = range.First.NextSibling.FindFirstTokenIn();
                if (nextToken != null)
                {
                    prevToken = nextToken.GetPrevToken();
                }
            }

            if (prevToken != null && nextToken != null)
            {
                ITokenNode separator = Context.CodeFormatter.GetMinimalSeparator(prevToken, nextToken);
                if (separator != null)
                {
                    LowLevelModificationUtil.AddChildAfter(range.First, separator);
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// The code must not contain multiple whitespace in a row.
        /// </summary>
        /// <param name="node">
        /// The node.
        /// </param>
        public static void CodeMustNotContainMultipleWhitespaceInARow(ITreeNode node)
        {
            for (ITreeNode currentNode = node; currentNode != null; currentNode = currentNode.NextSibling)
            {
                if (currentNode is ITokenNode)
                {
                    ITokenNode currentToken  = currentNode as ITokenNode;
                    ITokenNode previousToken = currentToken.GetPrevToken();

                    if (previousToken != null)
                    {
                        if (currentToken.GetTokenType() == CSharpTokenType.WHITE_SPACE && previousToken.GetTokenType() == CSharpTokenType.WHITE_SPACE)
                        {
                            using (WriteLockCookie.Create(true))
                            {
                                LowLevelModificationUtil.DeleteChild(currentToken);
                            }
                        }
                    }
                }

                if (currentNode.FirstChild != null)
                {
                    CodeMustNotContainMultipleWhitespaceInARow(currentNode.FirstChild);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Negative and positive signs must be spaced correctly.
        /// </summary>
        /// <param name="node">
        /// The node to use.
        /// </param>
        /// <param name="tokenToCheck">
        /// The token to check.
        /// </param>
        public static void NegativeAndPositiveSignsMustBeSpacedCorrectly(ITreeNode node, TokenNodeType tokenToCheck)
        {
            for (ITreeNode currentNode = node; currentNode != null; currentNode = currentNode.NextSibling)
            {
                if (currentNode is ITokenNode)
                {
                    ITokenNode tokenNode = currentNode as ITokenNode;

                    if (tokenNode.GetTokenType() == tokenToCheck)
                    {
                        if (tokenNode.Parent is IOperatorExpression && !(tokenNode.Parent is IAdditiveExpression))
                        {
                            ITokenNode nextToken = tokenNode.GetNextToken();

                            if (nextToken.IsWhitespace())
                            {
                                using (WriteLockCookie.Create(true))
                                {
                                    // remove the whitespace or new line
                                    LowLevelModificationUtil.DeleteChild(nextToken);
                                }
                            }
                        }
                    }
                }

                if (currentNode.FirstChild != null)
                {
                    NegativeAndPositiveSignsMustBeSpacedCorrectly(currentNode.FirstChild, tokenToCheck);
                }
            }
        }
Ejemplo n.º 4
0
        public override void Regenerate(IndependentInjectedNodeContext nodeContext)
        {
            var htmlAttributeValue = nodeContext.OriginalContextNode as IHtmlAttributeValue;

            if (htmlAttributeValue == null)
            {
                Logger.Fail("Original node is not IHtmlAttributeValue");
                return;
            }

            if (htmlAttributeValue.LeadingQuote == null)
            {
                Logger.Fail("No leading quote");
                return;
            }

            var buffer = nodeContext.GeneratedNode.GetTextAsBuffer();

            var token =
                htmlAttributeValue.LeadingQuote.TokenTypes.ATTRIBUTE_VALUE.Create(buffer, TreeOffset.Zero,
                                                                                  new TreeOffset(buffer.Length)) as IHtmlToken;

            var list = htmlAttributeValue.ValueElements.ToArray();

            if (list.Any())
            {
                LowLevelModificationUtil.DeleteChildRange(list.First(), list.Last());
            }

            LowLevelModificationUtil.AddChildAfter(htmlAttributeValue.LeadingQuote, token);
        }
Ejemplo n.º 5
0
        public void MakeIndent(ITreeNode indentNode, string indent)
        {
            var lastSpace = AsWhitespaceNode(indentNode.PrevSibling);

            if (lastSpace != null && lastSpace.GetTokenType() != NewLineType)
            {
                var firstSpace = LeftWhitespaces(lastSpace).TakeWhile(ws => ws.GetTokenType() != NewLineType).LastOrDefault() ?? lastSpace;

                if (firstSpace != lastSpace || lastSpace.GetText() != indent)
                {
                    if (indent.IsEmpty())
                    {
                        LowLevelModificationUtil.DeleteChildRange(firstSpace, lastSpace);
                    }
                    else
                    {
                        LowLevelModificationUtil.ReplaceChildRange(firstSpace, lastSpace, CreateSpace(indent));
                    }
                }
            }
            else if (!indent.IsEmpty())
            {
                LowLevelModificationUtil.AddChildBefore(indentNode, CreateSpace(indent));
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Do not place regions within elements.
        /// </summary>
        /// <param name="node">
        /// The node to process.
        /// </param>
        private void DoNotPlaceRegionsWithinElements(ITreeNode node)
        {
            for (ITreeNode currentNode = node; currentNode != null; currentNode = currentNode.NextSibling)
            {
                if (currentNode is ITokenNode)
                {
                    ITokenNode tokenNode = currentNode as ITokenNode;

                    if (tokenNode.GetTokenType() == CSharpTokenType.PP_START_REGION)
                    {
                        IStartRegion startRegionNode = tokenNode.GetContainingNode <IStartRegion>(true);
                        if (startRegionNode != null)
                        {
                            if (startRegionNode.Parent is IBlock)
                            {
                                // we're in a block so remove the end and start region
                                IEndRegion endRegionNode = startRegionNode.EndRegion;

                                using (WriteLockCookie.Create(true))
                                {
                                    LowLevelModificationUtil.DeleteChild(endRegionNode);
                                    LowLevelModificationUtil.DeleteChild(startRegionNode);
                                }
                            }
                        }
                    }
                }

                if (currentNode.FirstChild != null)
                {
                    this.DoNotPlaceRegionsWithinElements(currentNode.FirstChild);
                }
            }
        }
Ejemplo n.º 7
0
        private void ChangeDocumentation(string text)
        {
            text = text.Trim('\r', '\n');

            if (!string.IsNullOrEmpty(text))
            {
                var newNode = GetElementFactory().CreateDocCommentBlock(text);
                if (IsCreated)
                {
                    LowLevelModificationUtil.ReplaceChildRange(Node, Node, newNode);
                }
                else
                {
                    LowLevelModificationUtil.AddChildBefore(AnalyzeUnit.Node.FirstChild, newNode);
                }
                newNode.FormatNode();

                Node = newNode;
            }
            else if (Node != null)
            {
                LowLevelModificationUtil.DeleteChild(Node);
                Node = null;
            }

            Update();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Code must not contain empty statements.
        /// </summary>
        /// <param name="node">
        /// The node to process.
        /// </param>
        private void CodeMustNotContainEmptyStatements(ITreeNode node)
        {
            for (ITreeNode currentNode = node; currentNode != null; currentNode = currentNode.NextSibling)
            {
                if (currentNode is ITokenNode)
                {
                    ITokenNode tokenNode = currentNode as ITokenNode;

                    if (tokenNode.GetTokenType() == CSharpTokenType.SEMICOLON && !(tokenNode.Parent is IForStatement))
                    {
                        ITokenNode nextNonWhitespaceToken = Utils.GetFirstNonWhitespaceTokenToRight(tokenNode);

                        while (nextNonWhitespaceToken.GetTokenType() == CSharpTokenType.SEMICOLON)
                        {
                            using (WriteLockCookie.Create(true))
                            {
                                if (nextNonWhitespaceToken.GetNextToken().GetTokenType() == CSharpTokenType.WHITE_SPACE)
                                {
                                    LowLevelModificationUtil.DeleteChild(nextNonWhitespaceToken.GetNextToken());
                                }

                                // remove the spare semi colon
                                LowLevelModificationUtil.DeleteChild(nextNonWhitespaceToken);
                                nextNonWhitespaceToken = Utils.GetFirstNonWhitespaceTokenToRight(tokenNode);
                            }
                        }
                    }
                }

                if (currentNode.FirstChild != null)
                {
                    this.CodeMustNotContainEmptyStatements(currentNode.FirstChild);
                }
            }
        }
        IReferenceExpression IReferenceExpression.SetName(string name)
        {
            var newToken = new FSharpIdentifierToken(name);

            LowLevelModificationUtil.ReplaceChildRange(this, this, newToken);
            return(newToken);
        }
Ejemplo n.º 10
0
        public static void MakeIndent(this ITreeNode indentNode, string indent)
        {
            var lastSpace = indentNode.PrevSibling as IWhitespaceNode;

            if (lastSpace != null && lastSpace.GetTokenType() != PsiTokenType.NEW_LINE)
            {
                ITreeNode firstSpace = lastSpace.LeftWhitespaces().TakeWhile(ws => ws != PsiTokenType.NEW_LINE).LastOrDefault() ?? lastSpace;
                while (firstSpace.GetTokenType() != PsiTokenType.NEW_LINE)
                {
                    firstSpace = firstSpace.GetNextToken();
                }
                firstSpace = firstSpace.GetNextToken();
                if (firstSpace != lastSpace || lastSpace.GetText() != indent)
                {
                    if (indent.IsEmpty())
                    {
                        LowLevelModificationUtil.DeleteChildRange(firstSpace, lastSpace);
                    }
                    else
                    {
                        LowLevelModificationUtil.ReplaceChildRange(firstSpace, lastSpace, CreateSpace(indent));
                    }
                }
            }
            else if (!indent.IsEmpty())
            {
                LowLevelModificationUtil.AddChildBefore(indentNode, CreateSpace(indent));
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Preprocessor keywords must not be preceded by space.
        /// </summary>
        /// <param name="node">
        /// The node to use.
        /// </param>
        public static void PreprocessorKeywordsMustNotBePrecededBySpace(ITreeNode node)
        {
            for (ITreeNode currentNode = node; currentNode != null; currentNode = currentNode.NextSibling)
            {
                if (currentNode is IPreprocessorDirective)
                {
                    IPreprocessorDirective preprocessorDirectiveNode = currentNode as IPreprocessorDirective;

                    TreeOffset directiveTokenNodeOffset = preprocessorDirectiveNode.Directive.GetTreeStartOffset();

                    TreeOffset numberSignTokenNodeOffset = preprocessorDirectiveNode.NumberSign.GetTreeStartOffset();

                    if (directiveTokenNodeOffset - 1 != numberSignTokenNodeOffset)
                    {
                        // There is a gap between them
                        ITokenNode tokenNode = preprocessorDirectiveNode.NumberSign;

                        ITokenNode nextToken = tokenNode.GetNextToken();

                        using (WriteLockCookie.Create(true))
                        {
                            // remove the whitespace or new line
                            LowLevelModificationUtil.DeleteChild(nextToken);
                        }
                    }
                }

                if (currentNode.FirstChild != null)
                {
                    PreprocessorKeywordsMustNotBePrecededBySpace(currentNode.FirstChild);
                }
            }
        }
Ejemplo n.º 12
0
        protected virtual void DoPutNewIndents([NotNull] IFormalParameterList parameters)
        {
            LowLevelModificationUtil.AddChildBefore(parameters, CreateLineBreakToken());

            foreach (var paramDecl in parameters.ParameterDeclarationsEnumerable.Skip(1))
            {
                LowLevelModificationUtil.AddChildBefore(paramDecl, CreateLineBreakToken());
            }
        }
Ejemplo n.º 13
0
        IReferenceExpression IReferenceExpression.SetName(string name)
        {
            if (IdentifierToken is var id && id != null)
            {
                LowLevelModificationUtil.ReplaceChildRange(id, id, new FSharpIdentifierToken(name));
            }

            return(this);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Inserts a newline in front of the Node provided.
        /// </summary>
        /// <param name="currentNode">
        /// The node to insert in front of.
        /// </param>
        /// <returns>
        /// The inserted ITreeNode.
        /// </returns>
        public static ITreeNode InsertNewLineBefore(this ITreeNode currentNode)
        {
            LeafElementBase leafElement = GetLeafElement();

            using (WriteLockCookie.Create(true))
            {
                LowLevelModificationUtil.AddChildBefore(currentNode, new[] { leafElement });
            }

            return(leafElement);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Commas must be spaced correctly.
        /// </summary>
        /// <param name="node">
        /// The node to use.
        /// </param>
        public void EqualsMustBeSpacedCorrectly(ITreeNode node)
        {
            List <TokenNodeType> tokensThatCanBeLeftSideOfEquals = new List <TokenNodeType>
            {
                CSharpTokenType.WHITE_SPACE,
                CSharpTokenType.NE,
                CSharpTokenType.LT,
                CSharpTokenType.GT
            };

            const string WhiteSpace = " ";

            for (ITreeNode currentNode = node; currentNode != null; currentNode = currentNode.NextSibling)
            {
                if (currentNode is ITokenNode)
                {
                    ITokenNode tokenNode = currentNode as ITokenNode;

                    if (tokenNode.GetTokenType() == CSharpTokenType.EQ)
                    {
                        ITokenNode nextToken = tokenNode.GetNextToken();

                        ITokenNode previousToken = tokenNode.GetPrevToken();

                        if (!nextToken.IsWhitespace())
                        {
                            using (WriteLockCookie.Create(true))
                            {
                                // insert a space
                                LeafElementBase leafElement = TreeElementFactory.CreateLeafElement(
                                    CSharpTokenType.WHITE_SPACE, new JetBrains.Text.StringBuffer(WhiteSpace), 0, WhiteSpace.Length);
                                LowLevelModificationUtil.AddChildBefore(nextToken, new ITreeNode[] { leafElement });
                            }
                        }

                        if (!tokensThatCanBeLeftSideOfEquals.Contains(previousToken.GetTokenType()))
                        {
                            using (WriteLockCookie.Create(true))
                            {
                                // insert a space
                                LeafElementBase leafElement = TreeElementFactory.CreateLeafElement(
                                    CSharpTokenType.WHITE_SPACE, new JetBrains.Text.StringBuffer(WhiteSpace), 0, WhiteSpace.Length);
                                LowLevelModificationUtil.AddChildBefore(tokenNode, new ITreeNode[] { leafElement });
                            }
                        }
                    }
                }

                if (currentNode.FirstChild != null)
                {
                    this.EqualsMustBeSpacedCorrectly(currentNode.FirstChild);
                }
            }
        }
Ejemplo n.º 16
0
        public static void ReplaceIdentifier([CanBeNull] this IFSharpIdentifier fsIdentifier, string name)
        {
            // todo: replace the composite identifier node with a single token where possible
            if (!(fsIdentifier?.FirstChild is FSharpIdentifierToken token))
            {
                return;
            }

            name = Lexhelp.Keywords.QuoteIdentifierIfNeeded(name);
            using (WriteLockCookie.Create(fsIdentifier.IsPhysical()))
                LowLevelModificationUtil.ReplaceChildRange(token, token, new FSharpIdentifierToken(name));
        }
        public override CSharpPostfixExpressionContext FixExpression(CSharpPostfixExpressionContext context)
        {
            var psiServices     = Reference.GetPsiServices();
            var expressionRange = ExecutionContext.GetDocumentRange(context.Expression);
            var referenceRange  = ExecutionContext.GetDocumentRange(Reference);

            var textWithReference = expressionRange.SetEndTo(referenceRange.TextRange.EndOffset).GetText();

            var indexOfReferenceDot = textWithReference.LastIndexOf('.');

            if (indexOfReferenceDot <= 0)
            {
                return(context);
            }

            var realReferenceRange = referenceRange.SetStartTo(expressionRange.TextRange.StartOffset + indexOfReferenceDot);

            var transactionManager = psiServices.Transactions.DocumentTransactionManager;
            var document           = expressionRange.Document;

            // todo: make sure this is not in undo stack!
            using (transactionManager.CreateTransactionCookie(DefaultAction.Commit, FixCommandName))
            {
                document.ReplaceText(realReferenceRange.TextRange, ")");
                document.InsertText(expressionRange.TextRange.StartOffset, "unchecked(");
            }

            //using (psiServices.Solution.CreateTransactionCookie(DefaultAction.Commit, FixCommandName, NullProgressIndicator.Instance))
            //{
            //
            //}

            psiServices.Files.CommitAllDocuments();

            var uncheckedExpression = TextControlToPsi.GetElement <IUncheckedExpression>(psiServices.Solution, document, expressionRange.TextRange.StartOffset + 1);

            if (uncheckedExpression == null)
            {
                return(context);
            }

            var operand = uncheckedExpression.Operand;

            psiServices.Transactions.Execute(FixCommandName, () =>
            {
                LowLevelModificationUtil.DeleteChild(operand);
                LowLevelModificationUtil.ReplaceChildRange(uncheckedExpression, uncheckedExpression, operand);
            });

            Assertion.Assert(operand.IsPhysical(), "operand.IsPhysical()");

            return(new CSharpPostfixExpressionContext(this, operand));
        }
Ejemplo n.º 18
0
        public static void ReplaceIdentifier([CanBeNull] this IFSharpIdentifier fsIdentifier, string name)
        {
            var token = fsIdentifier?.IdentifierToken;

            if (token == null)
            {
                return;
            }

            name = NamingManager.GetNamingLanguageService(fsIdentifier.Language).MangleNameIfNecessary(name);
            using (WriteLockCookie.Create(fsIdentifier.IsPhysical()))
                LowLevelModificationUtil.ReplaceChildRange(token, token, new FSharpIdentifierToken(name));
        }
Ejemplo n.º 19
0
        public static void ReplaceChild(ITreeNode parent, ITreeNode nameNode, string name)
        {
            if (name.IsEmpty())
            {
                throw new ArgumentException("name shouldn't be empty", "name");
            }

            using (WriteLockCookie.Create(parent.IsPhysical()))
            {
                IRuleName ruleName = PsiElementFactory.GetInstance(parent.GetPsiModule()).CreateIdentifierExpression(name);
                LowLevelModificationUtil.ReplaceChildRange(nameNode, nameNode, ruleName.FirstChild);
            }
        }
        public void ProcessBeforeInterior(ITreeNode element)
        {
            var header = element as IXmlTagHeader;

            if (header == null)
            {
                return;
            }

            // note: using LINQ's .OrderBy() because of stable sorting behavior
            var sortedAttributes = header.Attributes.OrderBy(x => x, _orderComparer).ToList();

            if (sortedAttributes.SequenceEqual(header.AttributesEnumerable))
            {
                return;
            }

            using (WriteLockCookie.Create()) {
                var xamlFactory    = XamlElementFactory.GetInstance(header);
                var replacementMap = new Dictionary <IXmlAttribute, IXmlAttribute>();

                // I'm using LowLevelModificationUtil to physically modify AST at low-level,
                // without cloning, invoking reference binds and formatting
                // (like ModificationUtil.*/.RemoveAttribute()/.AddAttributeBefore() methods do).

                var attributes = header.Attributes;
                for (var index = 0; index < attributes.Count; index++)
                {
                    var attribute       = attributes[index];
                    var sortedAttribute = sortedAttributes[index];
                    if (attribute == sortedAttribute)
                    {
                        continue;
                    }

                    // replace attribute to be reordered with fake attribute
                    var fakeAttribute = xamlFactory.CreateRootAttribute("fake");
                    LowLevelModificationUtil.ReplaceChildRange(attribute, attribute, fakeAttribute);
                    replacementMap.Add(fakeAttribute, sortedAttribute);
                }

                // now all attributes in 'replacementMap' are detached from AST and replaces with fake ones
                // let's now replace fakes with attributes in order:

                foreach (var attribute in replacementMap)
                {
                    var fakeAttribute = attribute.Key;
                    LowLevelModificationUtil.ReplaceChildRange(fakeAttribute, fakeAttribute, attribute.Value);
                }
            }
        }
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var sceneName = myWarning.SceneName;

            Assertion.Assert(sceneName != null, "sceneName != null");

            var unityModule = GetUnityModule(solution);

            Assertion.Assert(unityModule != null, "unityModule != null");

            var buildSettings = GetEditorBuildSettings(unityModule);

            var scenes = GetSceneCollection(buildSettings.GetDominantPsiFile <UnityYamlLanguage>() as IYamlFile) as IBlockSequenceNode;

            Assertion.Assert(scenes != null, "scene != null");
            foreach (var entry in scenes.Entries)
            {
                var scene       = entry.Value;
                var sceneRecord = scene as IBlockMappingNode;
                if (sceneRecord == null)
                {
                    continue;
                }

                var path = GetUnityScenePathRepresentation(
                    (sceneRecord.Entries[1].Content.Value as IPlainScalarNode).NotNull("PlainScalarNode:1").Text.GetText());
                var simple = path.Split('/').Last();
                var isEnabledPlaneScalarNode = (sceneRecord.Entries[0].Content.Value as IPlainScalarNode).NotNull("PlainScalarNode:0");
                var isEnabled = isEnabledPlaneScalarNode.Text.GetText().Equals("1");
                if (!isEnabled && (path.Equals(sceneName) || simple.Equals(sceneName)))
                {
                    using (WriteLockCookie.Create(myWarning.Argument.IsPhysical()))
                    {
                        var text = YamlTokenType.NS_PLAIN_ONE_LINE_IN.Create("1");
                        if (isEnabledPlaneScalarNode.Text != null)
                        {
                            LowLevelModificationUtil.ReplaceChildRange(isEnabledPlaneScalarNode.Text, isEnabledPlaneScalarNode.Text, text);
                        }
                        else
                        {
                            LowLevelModificationUtil.AddChild(isEnabledPlaneScalarNode.Text, text);
                        }
                    }
                }

                solution.GetComponent <IDaemon>().Invalidate();
                solution.GetComponent <UnityRefresher>().Refresh(RefreshType.Normal);
            }

            return(null);
        }
        public void AdjustLeadingAndTrailingWhitespaces(CppCodeFormatter cppCodeFormatter, CppFile cppFile)
        {
            var cgProgram = (cppFile.Parent as IInjectedFileHolder)?.OriginalNode.PrevSibling;

            var s = ShaderLabCppFormatterExtension.GetIndentInCgProgram(cgProgram);

            cppCodeFormatter.RemoveLeadingSpacesInFile(cppFile);
            cppCodeFormatter.RemoveTrailingSpaces(cppFile);

            var lineEnding = cppFile.DetectLineEnding(cppFile.GetPsiServices());

            LowLevelModificationUtil.AddChildBefore(cppFile.firstChild, cppCodeFormatter.CreateNewLine(lineEnding), cppCodeFormatter.CreateSpace(s, null));
            LowLevelModificationUtil.AddChildAfter(cppFile.lastChild, cppCodeFormatter.CreateNewLine(lineEnding), cppCodeFormatter.CreateSpace(s, null));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Remove empty comments.
        /// </summary>
        /// <param name="node">
        /// The node to process.
        /// </param>
        public static void RemoveEmptyComments(ITreeNode node)
        {
            // we don't remove empty lines from Element Doc Comments in here
            // the DeclarationHeader types take care of that.
            for (ITreeNode currentNode = node; currentNode != null; currentNode = currentNode.NextSibling)
            {
                if (currentNode is ITokenNode)
                {
                    ICommentNode commentNode = currentNode as ICommentNode;
                    if (commentNode != null && !(commentNode is IDocCommentNode))
                    {
                        if (commentNode.CommentText.Trim() == string.Empty)
                        {
                            ITokenNode leftToken = Utils.GetFirstNewLineTokenToLeft((ITokenNode)currentNode);

                            ITokenNode rightToken = Utils.GetFirstNewLineTokenToRight((ITokenNode)currentNode);

                            if (leftToken == null)
                            {
                                leftToken = (ITokenNode)currentNode;
                            }
                            else
                            {
                                leftToken = leftToken.GetNextToken();
                            }

                            if (rightToken == null)
                            {
                                rightToken = (ITokenNode)currentNode;
                            }
                            else
                            {
                                currentNode = rightToken.GetNextToken();
                            }

                            using (WriteLockCookie.Create(true))
                            {
                                LowLevelModificationUtil.DeleteChildRange(leftToken, rightToken);
                            }
                        }
                    }
                }

                if (currentNode != null && currentNode.FirstChild != null)
                {
                    RemoveEmptyComments(currentNode.FirstChild);
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Remove parenthesis from node.
        /// </summary>
        /// <param name="node">
        /// The node.
        /// </param>
        public static void RemoveParenthesisFromNode(ITreeNode node)
        {
            IParenthesizedExpression parenthesizedExpressionNode = node as IParenthesizedExpression;

            if (parenthesizedExpressionNode != null)
            {
                using (WriteLockCookie.Create(true))
                {
                    ICSharpExpression innerExpression = parenthesizedExpressionNode.Expression;

                    if (innerExpression != null && node.Parent != null)
                    {
                        NodeType innerExpressionNodeType = (innerExpression as TreeElement).NodeType;

                        if (innerExpressionNodeType != ElementType.ADDITIVE_EXPRESSION && innerExpressionNodeType != ElementType.MULTIPLICATIVE_EXPRESSION &&
                            innerExpressionNodeType != ElementType.SHIFT_EXPRESSION && innerExpressionNodeType != ElementType.AS_EXPRESSION &&
                            innerExpressionNodeType != ElementType.ASSIGNMENT_EXPRESSION && innerExpressionNodeType != ElementType.CAST_EXPRESSION &&
                            innerExpressionNodeType != ElementType.CONDITIONAL_AND_EXPRESSION && innerExpressionNodeType != ElementType.CONDITIONAL_OR_EXPRESSION &&
                            innerExpressionNodeType != ElementType.CONDITIONAL_TERNARY_EXPRESSION && innerExpressionNodeType != ElementType.POSTFIX_OPERATOR_EXPRESSION &&
                            innerExpressionNodeType != ElementType.PREFIX_OPERATOR_EXPRESSION && innerExpressionNodeType != ElementType.IS_EXPRESSION &&
                            innerExpressionNodeType != ElementType.LAMBDA_EXPRESSION && innerExpressionNodeType != ElementType.BITWISE_AND_EXPRESSION &&
                            innerExpressionNodeType != ElementType.BITWISE_INCLUSIVE_OR_EXPRESSION &&
                            innerExpressionNodeType != ElementType.BITWISE_EXCLUSIVE_OR_EXPRESSION && innerExpressionNodeType != ElementType.OBJECT_CREATION_EXPRESSION &&
                            innerExpressionNodeType != ElementType.ARRAY_CREATION_EXPRESSION && innerExpressionNodeType != ElementType.NULL_COALESCING_EXPRESSION &&
                            innerExpressionNodeType != ElementType.QUERY_EXPRESSION && innerExpressionNodeType != ElementType.RELATIONAL_EXPRESSION &&
                            innerExpressionNodeType != ElementType.UNARY_OPERATOR_EXPRESSION && innerExpressionNodeType != ElementType.EQUALITY_EXPRESSION &&
                            innerExpressionNodeType != ElementType.AWAIT_EXPRESSION)
                        {
                            LowLevelModificationUtil.ReplaceChildRange(node, node, new ITreeNode[] { innerExpression });
                            return;
                        }

                        if ((!(node.Parent is IExpression)) || node.Parent is IVariableDeclaration)
                        {
                            LowLevelModificationUtil.ReplaceChildRange(node, node, new ITreeNode[] { innerExpression });
                            return;
                        }

                        IAssignmentExpression parent = node.Parent as IAssignmentExpression;

                        if (parent != null && parent.Source == node)
                        {
                            LowLevelModificationUtil.ReplaceChildRange(node, node, new ITreeNode[] { innerExpression });
                            return;
                        }
                    }
                }
            }
        }
Ejemplo n.º 25
0
        public override IReference BindTo(IDeclaredElement element)
        {
            using (WriteLockCookie.Create(myOwner.IsPhysical()))
            {
                var text = YamlTokenType.NS_PLAIN_ONE_LINE_IN.Create(element.ShortName);
                if (myOwner.Text != null)
                {
                    LowLevelModificationUtil.ReplaceChildRange(myOwner.Text, myOwner.Text, text);
                }
                else
                {
                    LowLevelModificationUtil.AddChild(myOwner.Text, text);
                }
            }

            return(this);
        }
        public override PrefixExpressionContext FixExpression(PrefixExpressionContext context)
        {
            var expression = context.Expression;

            if (expression.Contains(Reference)) // x is T.bar => x is T
            {
                expression.GetPsiServices().DoTransaction(FixCommandName, () => {
                    var referenceName = (IReferenceName)Reference;
                    var qualifier     = referenceName.Qualifier;

                    LowLevelModificationUtil.DeleteChild(qualifier); // remove first

                    return(referenceName.ReplaceBy(qualifier));
                });
            }

            return(context);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Delete child range.
        /// </summary>
        /// <param name="first">
        /// The first token to delete.
        /// </param>
        /// <param name="last">
        /// The last token to delete.
        /// </param>
        private static void DeleteChildRange(ITokenNode first, ITokenNode last)
        {
            using (WriteLockCookie.Create(true))
            {
                List <ITokenNode> a = new List <ITokenNode>();

                ITokenNode tokenNodeToStopAt = last.GetNextToken();
                for (ITokenNode foundToken = first; foundToken != tokenNodeToStopAt; foundToken = foundToken.GetNextToken())
                {
                    a.Add(foundToken);
                }

                foreach (ITokenNode tokenNode in a)
                {
                    LowLevelModificationUtil.DeleteChild(tokenNode);
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Moves the IStartRegion specified inside the next open curly bracket and moves the corresponding end region inside too.
        /// </summary>
        /// <param name="startRegionNode">
        /// The node to move.
        /// </param>
        public static void MoveRegionInsideNextOpenCurlyBracket(IStartRegion startRegionNode)
        {
            using (WriteLockCookie.Create(true))
            {
                ITokenNode newLocationTokenNode = Utils.GetFirstNonWhitespaceTokenToRight(startRegionNode.Message);

                // if its a start region there is probably a corresponding end region
                // find it, and move it inside the block
                // find the position to delete from
                ITokenNode startOfTokensToDelete = Utils.GetFirstNewLineTokenToLeft(startRegionNode.NumberSign);
                ITokenNode endOfTokensToDelete   = Utils.GetFirstNewLineTokenToRight(startRegionNode.Message);
                ITokenNode startOfTokensToFormat = startOfTokensToDelete.GetPrevToken();

                IEndRegion   endRegionNode  = startRegionNode.EndRegion;
                IStartRegion newStartRegion = startRegionNode.Copy(null);
                ITokenNode   firstNonWhitespaceAfterBracket = Utils.GetFirstNonWhitespaceTokenToRight(newLocationTokenNode);

                LowLevelModificationUtil.AddChildBefore(firstNonWhitespaceAfterBracket, new[] { newStartRegion });

                newStartRegion.InsertNewLineAfter();

                LowLevelModificationUtil.DeleteChildRange(startOfTokensToDelete, endOfTokensToDelete);
                IStartRegion endOfTokensToFormat = newStartRegion;

                if (endRegionNode != null)
                {
                    startOfTokensToDelete = Utils.GetFirstNewLineTokenToLeft(endRegionNode.NumberSign);
                    endOfTokensToDelete   = Utils.GetFirstNewLineTokenToRight(endRegionNode.NumberSign);

                    IEndRegion newEndRegionNode = endRegionNode.Copy(null);
                    ITokenNode newLineToken     = Utils.GetFirstNonWhitespaceTokenToLeft(endRegionNode.NumberSign);
                    LowLevelModificationUtil.AddChildBefore(newLineToken, new[] { newEndRegionNode });

                    newEndRegionNode.InsertNewLineAfter();

                    LowLevelModificationUtil.DeleteChildRange(startOfTokensToDelete, endOfTokensToDelete);
                    endOfTokensToFormat = (IStartRegion)newLineToken;
                }

                ////CSharpFormatterHelper.FormatterInstance.Format(startOfTokensToFormat, endOfTokensToFormat);
                ICSharpCodeFormatter codeFormatter = (ICSharpCodeFormatter)CSharpLanguage.Instance.LanguageService().CodeFormatter;
                codeFormatter.Format(startOfTokensToFormat, endOfTokensToFormat);
            }
        }
        protected override ITreeNode Move(Direction direction)
        {
            using (PsiTransactionCookie.CreateAutoCommitCookieWithCachesUpdate(myRuleDeclaration.GetPsiServices(), "Rearrange code"))
            {
                if (direction == Direction.Up)
                {
                    var sibling = myRuleDeclaration.PrevSibling;
                    while (sibling is IWhitespaceNode)
                    {
                        sibling = sibling.PrevSibling;
                    }

                    var ruleDeclaration = sibling as IRuleDeclaration;
                    if (ruleDeclaration != null)
                    {
                        using (WriteLockCookie.Create())
                        {
                            LowLevelModificationUtil.AddChildBefore(ruleDeclaration, myRuleDeclaration);
                            LowLevelModificationUtil.AddChildBefore(ruleDeclaration, new NewLine("\r\n"));
                        }
                    }
                }

                if (direction == Direction.Down)
                {
                    var sibling = myRuleDeclaration.NextSibling;
                    while (sibling is IWhitespaceNode)
                    {
                        sibling = sibling.NextSibling;
                    }

                    var ruleDeclaration = sibling as IRuleDeclaration;
                    if (ruleDeclaration != null)
                    {
                        using (WriteLockCookie.Create())
                        {
                            LowLevelModificationUtil.AddChildAfter(ruleDeclaration, myRuleDeclaration);
                            LowLevelModificationUtil.AddChildAfter(ruleDeclaration, new NewLine("\r\n"));
                        }
                    }
                }
            }
            return(myRuleDeclaration);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Single line comments must begin with single space.
        /// </summary>
        /// <param name="node">
        /// The node to use.
        /// </param>
        public static void SingleLineCommentsMustBeginWithSingleSpace(ITreeNode node)
        {
            for (ITreeNode currentNode = node; currentNode != null; currentNode = currentNode.NextSibling)
            {
                if (currentNode is ICommentNode && !(currentNode is IDocCommentNode))
                {
                    ICommentNode commentNode = currentNode as ICommentNode;

                    if (commentNode.GetTokenType() == CSharpTokenType.END_OF_LINE_COMMENT && !(commentNode.Parent is ICSharpFile))
                    {
                        string originalCommentText = commentNode.CommentText;

                        // This check is to exclude comments starting with ////
                        if (!originalCommentText.StartsWith("//"))
                        {
                            int originalCommentTextLength = originalCommentText.Length;

                            string trimmedCommentText       = originalCommentText.TrimStart(' ');
                            int    trimmedCommentTextLength = trimmedCommentText.Length;

                            if (trimmedCommentTextLength != originalCommentTextLength - 1)
                            {
                                using (WriteLockCookie.Create(true))
                                {
                                    string       newText        = string.Format("// {0}", trimmedCommentText);
                                    ICommentNode newCommentNode =
                                        (ICommentNode)
                                        CSharpTokenType.END_OF_LINE_COMMENT.Create(
                                            new JetBrains.Text.StringBuffer(newText), new TreeOffset(0), new TreeOffset(newText.Length));
                                    LowLevelModificationUtil.ReplaceChildRange(currentNode, currentNode, new ITreeNode[] { newCommentNode });

                                    currentNode = newCommentNode;
                                }
                            }
                        }
                    }
                }

                if (currentNode.FirstChild != null)
                {
                    SingleLineCommentsMustBeginWithSingleSpace(currentNode.FirstChild);
                }
            }
        }