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(); }
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)); } }
IReferenceExpression IReferenceExpression.SetName(string name) { var newToken = new FSharpIdentifierToken(name); LowLevelModificationUtil.ReplaceChildRange(this, this, newToken); return(newToken); }
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)); } }
IReferenceExpression IReferenceExpression.SetName(string name) { if (IdentifierToken is var id && id != null) { LowLevelModificationUtil.ReplaceChildRange(id, id, new FSharpIdentifierToken(name)); } return(this); }
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)); }
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 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 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)); }
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 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); } } }
/// <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; } } } } }
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); }
/// <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); } } }
public override IReference BindTo(IDeclaredElement element) { using (WriteLockCookie.Create(myOwner.IsPhysical())) { var shaderLabIdentifier = new ShaderLabIdentifier(); shaderLabIdentifier.AddChild(new Identifier(element.ShortName)); if (myOwner.Identifier != null) { LowLevelModificationUtil.ReplaceChildRange(myOwner.Identifier, myOwner.Identifier, shaderLabIdentifier); } else { LowLevelModificationUtil.AddChild(myOwner.Identifier, shaderLabIdentifier); } } return(myOwner.Reference); }
public override CSharpPostfixExpressionContext FixExpression(CSharpPostfixExpressionContext context) { var expression = context.Expression; if (expression.Contains(Reference)) // x is T.bar => x is T { var psiServices = expression.GetPsiServices(); psiServices.Transactions.Execute(FixCommandName, () => { var referenceName = (IReferenceName)Reference; var qualifier = referenceName.Qualifier; LowLevelModificationUtil.DeleteChild(qualifier); // remove first LowLevelModificationUtil.ReplaceChildRange(referenceName, referenceName, qualifier); }); } return(context); }
/// <summary> /// Replace empty strings with string dot empty. /// </summary> /// <param name="node"> /// The node to process. /// </param> public static void ReplaceEmptyStringsWithStringDotEmpty(ITreeNode node) { for (ITreeNode currentNode = node; currentNode != null; currentNode = currentNode.NextSibling) { if (currentNode is ITokenNode) { ITokenNode tokenNode = currentNode as ITokenNode; if (tokenNode.GetTokenType().IsStringLiteral) { IAttribute attribute = tokenNode.GetContainingNode <IAttribute>(true); ISwitchLabelStatement switchLabelStatement = tokenNode.GetContainingNode <ISwitchLabelStatement>(true); IConstantDeclaration constantDeclaration = tokenNode.GetContainingNode <IConstantDeclaration>(true); IRegularParameterDeclaration parameterDeclaration = tokenNode.GetContainingNode <IRegularParameterDeclaration>(true); // Not for attributes, switch labels, constant declarations, or parameter declarations if (attribute == null && switchLabelStatement == null && constantDeclaration == null && parameterDeclaration == null) { string text = currentNode.GetText(); if (text == "\"\"" || text == "@\"\"") { const string NewText = "string.Empty"; ITokenNode newLiteral = (ITokenNode) CSharpTokenType.STRING_LITERAL_REGULAR.Create(new JetBrains.Text.StringBuffer(NewText), new TreeOffset(0), new TreeOffset(NewText.Length)); using (WriteLockCookie.Create(true)) { LowLevelModificationUtil.ReplaceChildRange(currentNode, currentNode, new ITreeNode[] { newLiteral }); } } } } } if (currentNode.FirstChild != null) { ReadabilityRules.ReplaceEmptyStringsWithStringDotEmpty(currentNode.FirstChild); } } }
public override CSharpPostfixExpressionContext FixExpression(CSharpPostfixExpressionContext context) { var referenceExpression = (IReferenceExpression)Reference; var expression = context.Expression; if (expression.Parent == referenceExpression) // foo.bar => foo { var psiServices = expression.GetPsiServices(); psiServices.Transactions.Execute(FixCommandName, () => { LowLevelModificationUtil.DeleteChild(expression); LowLevelModificationUtil.ReplaceChildRange(referenceExpression, referenceExpression, expression); }); Assertion.Assert(expression.IsPhysical(), "expression.IsPhysical()"); return(new CSharpPostfixExpressionContext(this, expression)); } if (expression.Contains(referenceExpression)) // boo > foo.bar => boo > foo { var qualifier = referenceExpression.QualifierExpression; var psiServices = expression.GetPsiServices(); psiServices.Transactions.Execute(FixCommandName, () => { LowLevelModificationUtil.DeleteChild(qualifier); LowLevelModificationUtil.ReplaceChildRange(referenceExpression, referenceExpression, qualifier); }); Assertion.AssertNotNull(qualifier, "qualifier != null"); Assertion.Assert(qualifier.IsPhysical(), "qualifier.IsPhysical()"); } return(context); }
private static void SwapFileHeaderNode(ICSharpFile file, string newHeader) { ITreeRange existingHeaderRange = Utils.GetFileHeaderTreeRange(file); using (WriteLockCookie.Create(file.IsPhysical())) { ICommentNode newCommentNode; if (existingHeaderRange.IsEmpty) { // existing header missing so add on a new line for our new header newHeader += Environment.NewLine; IWhitespaceNode node = file.FirstChild as IWhitespaceNode; bool insertNewLine = true; while (node != null) { if (node.IsNewLine) { insertNewLine = false; break; } node = node.NextSibling as IWhitespaceNode; } if (insertNewLine) { newHeader += Environment.NewLine; } newCommentNode = (ICommentNode) CSharpTokenType.END_OF_LINE_COMMENT.Create(new JB::JetBrains.Text.StringBuffer(newHeader), new TreeOffset(0), new TreeOffset(newHeader.Length)); LowLevelModificationUtil.AddChildBefore(file.FirstChild, new ITreeNode[] { newCommentNode }); } else { ITokenNode lastToken = (ITokenNode)existingHeaderRange.Last; ITokenNode nextToken = lastToken.GetNextToken(); if (nextToken != null) { ITokenNode nextNextToken = nextToken.GetNextToken(); if (nextNextToken != null) { ITokenNode nextNextNextToken = nextNextToken.GetNextToken(); if (!nextToken.IsNewLine() || !nextNextToken.IsNewLine()) { newHeader += Environment.NewLine; } if (nextNextNextToken.GetTokenType() == CSharpTokenType.PP_SHARP && nextToken.IsNewLine() && nextNextToken.IsNewLine()) { newHeader += Environment.NewLine; } newCommentNode = (ICommentNode) CSharpTokenType.END_OF_LINE_COMMENT.Create( new JB::JetBrains.Text.StringBuffer(newHeader), new TreeOffset(0), new TreeOffset(newHeader.Length)); LowLevelModificationUtil.ReplaceChildRange(existingHeaderRange.First, existingHeaderRange.Last, new ITreeNode[] { newCommentNode }); } } } } }
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())) { var srcIsUri = Uri.IsWellFormedUriString(name, UriKind.Absolute); var dstIsUri = parent is IUriString || parent is IPrefixUri; if (srcIsUri && !dstIsUri) { var uri = new Uri(name); if (uri.Fragment.Length < 2) { throw new FormatException("The new name provided in rename operation is invalid."); } name = uri.Fragment.Substring(1); } else if (!srcIsUri && dstIsUri) { if (parent.Parent == null) { throw new InvalidOperationException("The element being replaced doesn't have a parent."); } var uriIdentifier = (IUriIdentifier)parent.Parent; var ns = uriIdentifier.GetNamespace(); name = ns + name; } ITreeNode newNode; if (parent is IPrefixName) { newNode = NTriplesElementFactory.GetInstance(parent.GetPsiModule()).CreatePrefixNameExpression(name).FirstChild; } else if (parent is IPrefix) { newNode = NTriplesElementFactory.GetInstance(parent.GetPsiModule()).CreatePrefixExpression(name).FirstChild; } else if (parent is IPrefixUri) { newNode = NTriplesElementFactory.GetInstance(parent.GetPsiModule()).CreatePrefixUriExpression(name).FirstChild; } else if (parent is ILocalName) { newNode = NTriplesElementFactory.GetInstance(parent.GetPsiModule()).CreateLocalNameExpression(name).FirstChild; } else if (parent is IUriString) { newNode = NTriplesElementFactory.GetInstance(parent.GetPsiModule()).CreateUriStringExpression(name).FirstChild; } else { throw new NotSupportedException(); } LowLevelModificationUtil.ReplaceChildRange(nameNode, nameNode, newNode); } }