public void Dispose() { using (WriteLockCookie.Create()) { foreach (var wrapper in _modules.Values) { wrapper.LifetimeDefinition.Terminate(); } _modules.Clear(); } }
/// <summary>Removes a child node from the file.</summary> /// <param name="node">The node to remove.</param> public void RemoveChild(IT4TreeNode node) { if (node == null) { return; } using (WriteLockCookie.Create(IsPhysical())) ModificationUtil.DeleteChild(node); }
/// <summary>Adds a new feature block.</summary> /// <param name="featureBlock">The feature block to add.</param> /// <returns>A new instance of <see cref="T4FeatureBlock"/>, representing <paramref name="featureBlock"/> in the T4 file.</returns> public T4FeatureBlock AddFeatureBlock(T4FeatureBlock featureBlock) { T4FeatureBlock anchor = GetFeatureBlocks().LastOrDefault(); using (WriteLockCookie.Create(IsPhysical())) { return(anchor == null ? ModificationUtil.AddChild(this, featureBlock) : ModificationUtil.AddChildAfter(anchor, featureBlock)); } }
public override void SetName(string name) { using (WriteLockCookie.Create()) { // TODO: Perhaps add SetName to ShaderLabIdentifier? var identifier = new ShaderLabIdentifier(); identifier.AddChild(new Identifier(name)); ModificationUtil.ReplaceChild(Name, identifier); } }
public void Accept( ITextControl textControl, TextRange nameRange, LookupItemInsertType lookupItemInsertType, Suffix suffix, ISolution solution, bool keepCaretStill) { textControl.Document.ReplaceText(nameRange, CASE_COMPLETION_NAME + "()"); var psiServices = solution.GetPsiServices(); psiServices.Files.CommitAllDocuments(); var enumMember = Info.PreferredDeclaredElement; if (enumMember == null) { return; } var invocationExpression = FindFakeInvocation(textControl, solution, nameRange.EndOffset); if (invocationExpression == null) { return; } var factory = CSharpElementFactory.GetInstance(invocationExpression); var template = (Info.IsFlagsEnum && !Info.IsZeroCase) ? (Info.IsMultiBitFlagCase ? "($0 & $1) != $1" : "($0 & $1) != 0") : "$0 == $1"; var referenceExpression = (IReferenceExpression)invocationExpression.InvokedExpression; var qualifierExpression = referenceExpression.QualifierExpression; var enumMemberCheck = factory.CreateExpression(template, qualifierExpression, enumMember); var caretPointer = psiServices.DoTransaction( commandName: typeof(EnumCaseCheckBehavior).FullName, func: () => { using (WriteLockCookie.Create()) { var memberCheck = invocationExpression.ReplaceBy(enumMemberCheck); return(memberCheck.CreateTreeElementPointer()); } }); if (caretPointer != null) { var checkExpression = caretPointer.GetTreeNode(); if (checkExpression != null) { var offset = checkExpression.GetDocumentRange().TextRange.EndOffset; textControl.Caret.MoveTo(offset, CaretVisualPlacement.DontScrollIfVisible); } } }
private void DoFormatStatementOnSemicolon(ITextControl textControl) { IFile file = CommitPsi(textControl); if (file == null) { return; } int charPos = TextControlToLexer(textControl, textControl.Caret.Offset()); if (charPos < 0) { return; } var tokenNode = file.FindTokenAt(textControl.Document, charPos - 1) as ITokenNode; if (tokenNode == null || tokenNode.GetTokenType() != PsiTokenType.SEMICOLON) { return; } var node = tokenNode.Parent; // do format if semicolon finished the statement if (node == null || tokenNode.NextSibling != null) { return; } // Select the correct start node for formatting ITreeNode startNode = node.FindFormattingRangeToLeft(); if (startNode == null) { startNode = node.FirstChild; } PsiCodeFormatter codeFormatter = GetCodeFormatter(tokenNode); using (PsiTransactionCookie.CreateAutoCommitCookieWithCachesUpdate(PsiServices, "Format code")) { using (WriteLockCookie.Create()) { codeFormatter.Format(startNode, tokenNode, CodeFormatProfile.DEFAULT); } } DocumentRange newPosition = tokenNode.GetDocumentRange(); if (newPosition.IsValid()) { textControl.Caret.MoveTo(newPosition.TextRange.EndOffset, CaretVisualPlacement.DontScrollIfVisible); } }
public void Process( IPsiSourceFile sourceFile, IRangeMarker rangeMarkerMarker, CodeCleanupProfile profile, IProgressIndicator progressIndicator) { ISolution solution = sourceFile.GetSolution(); if (!profile.GetSetting(OurDescriptor)) { return; } INTriplesFile[] files = sourceFile.GetPsiFiles <NTriplesLanguage>().Cast <INTriplesFile>().ToArray(); using (progressIndicator.SafeTotal("Reformat Psi", files.Length)) { foreach (INTriplesFile file in files) { using (IProgressIndicator pi = progressIndicator.CreateSubProgress(1)) { using (WriteLockCookie.Create()) { var languageService = file.Language.LanguageService(); Assertion.Assert(languageService != null, "languageService != null"); var formatter = languageService.CodeFormatter; Assertion.Assert(formatter != null, "formatter != null"); PsiManager.GetInstance(sourceFile.GetSolution()).DoTransaction( delegate { if (rangeMarkerMarker != null && rangeMarkerMarker.IsValid) { formatter.Format( solution, rangeMarkerMarker.DocumentRange, CodeFormatProfile.DEFAULT, true, false, pi); } else { formatter.FormatFile( file, CodeFormatProfile.DEFAULT, pi); } }, "Code cleanup"); } } } } }
public T4FileDependencyInvalidator( Lifetime lifetime, [NotNull] IT4FileGraphNotifier notifier, [NotNull] IPsiServices services, [NotNull] ISolution solution, [NotNull] IPsiServices psiServices ) { Solution = solution; PsiServices = psiServices; services.Files.ObserveAfterCommit(lifetime, () => { if (CommitStage == T4CommitStage.DependencyInvalidation) { return; } CommitStage = T4CommitStage.DependencyInvalidation; try { using (WriteLockCookie.Create()) { // Filter just in case a miracle happens and the file gets deleted before being marked as dirty foreach (var file in IndirectDependencies.Where(file => file.IsValid())) { services.Files.MarkAsDirty(file); services.Caches.MarkAsDirty(file); } } IndirectDependencies.Clear(); services.Files.CommitAllDocuments(); } finally { CommitStage = T4CommitStage.UserChangeApplication; } }); notifier.OnFilesIndirectlyAffected += paths => { if (CommitStage == T4CommitStage.DependencyInvalidation) { return; } // We want all files that were included before the update // and all the files that have become included now // to be updated, so we'll mark them as dirty later IndirectDependencies.AddRange(paths .Distinct() .SelectMany(Solution.FindProjectItemsByLocation) .OfType <IProjectFile>() .Select(PsiServices.Modules.GetPsiSourceFilesFor) .SelectMany(sourceFiles => sourceFiles.AsEnumerable())); }; }
public override IReference BindTo(IDeclaredElement element) { var factory = JsonNewElementFactory.GetInstance(myOwner.GetPsiModule()); var literalExpression = factory.CreateStringLiteral(element.ShortName); using (WriteLockCookie.Create(myOwner.IsPhysical())) { var newExpression = ModificationUtil.ReplaceChild(myOwner, literalExpression); return(newExpression.FindReference <AsmDefNameReference>() ?? this); } }
public void SetIsRecursive(bool value) { if (!value) { throw new System.NotImplementedException(); } using var _ = WriteLockCookie.Create(IsPhysical()); FirstBinding.NotNull().BindingKeyword.AddTokenAfter(FSharpTokenType.REC); }
/// <summary> /// Replacement for VBExpressionBase.ReplaceBy that does not insert unnecessary parentheses. /// </summary> /// <param name="oldExpression"></param> /// <param name="newExpression"></param> /// <returns></returns> public static IVBExpression ReplaceByExtension(this IVBExpression oldExpression, IVBExpression newExpression) { using (WriteLockCookie.Create(oldExpression.IsPhysical())) { if (oldExpression.Contains(newExpression)) { newExpression = newExpression.Copy(oldExpression.Parent); } return(ModificationUtil.ReplaceChild(oldExpression, newExpression)); } }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { using (WriteLockCookie.Create()) { this.DoCleanupLineBreaks(this._parametersOwnerDeclaration, this._paramList); this.DoPutNewIndents(this._paramList); } this._paramList.Language.LanguageService()?.CodeFormatter?.Format(this._paramList, CodeFormatProfile.DEFAULT, progress); return(null); }
/// <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); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { ITreeNode node = _highlighting.AssociatedNode; using (WriteLockCookie.Create(node.IsPhysical())) { ITokenNode nextToken = node.GetNextToken(); ITreeNode end = nextToken != null && nextToken.GetTokenType() == T4TokenNodeTypes.NewLine ? nextToken : node; ModificationUtil.DeleteChildRange(node, end); } return(null); }
public IRuleDeclaration InsertRule() { using (WriteLockCookie.Create()) { var anchor = myTarget.Anchor; var parent = anchor.Parent; var whiteSpace = ModificationUtil.AddChildAfter(parent, anchor, new NewLine("\n")); whiteSpace = ModificationUtil.AddChildAfter(parent, whiteSpace, new NewLine("\n")); return(ModificationUtil.AddChildAfter(parent, whiteSpace, myDeclarationToAdd)); } }
/// <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); } } }
/// <inheritdoc /> protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { using (WriteLockCookie.Create()) { var invocationExpression = _highlighting.InvocationExpression; ModificationUtil.ReplaceChild(invocationExpression, _migrationService.CreateMigrationExpression(invocationExpression)); } return(null); }
/// <summary> /// Swap object creation to built in type. /// </summary> /// <param name="objectCreationExpressionNode"> /// The object creation expression node. /// </param> private static void SwapObjectCreationToBuiltInType(IObjectCreationExpression objectCreationExpressionNode) { IPsiModule project = objectCreationExpressionNode.GetPsiModule(); using (WriteLockCookie.Create(true)) { IObjectCreationExpression tmpExpression = (IObjectCreationExpression) CSharpElementFactory.GetInstance(project).CreateExpression("new $0?()", new object[] { objectCreationExpressionNode.Type() }); objectCreationExpressionNode.SetCreatedTypeUsage(tmpExpression.CreatedTypeUsage); } }
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)); }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { using (WriteLockCookie.Create()) { var factory = CSharpElementFactory.GetInstance(_stringLiteral.Expression, false); var expression = factory.CreateExpression( $"\"{_stringLiteral.Expression.GetUnquotedText().Insert(_namedProperty.StartIndex + 1, "@")}\""); ModificationUtil.ReplaceChild(_stringLiteral.Expression, expression); } return(null); }
/// <summary> /// Process for each variable declaration. /// </summary> /// <param name="singleVariableDesignation"> /// The for each variable declaration. /// </param> private static void ProcessSingleVariableDesignation(ISingleVariableDesignation singleVariableDesignation) { ILocalVariable variable = singleVariableDesignation.DeclaredElement; if (!singleVariableDesignation.IsVar) { using (WriteLockCookie.Create(true)) { singleVariableDesignation.SetType(variable.Type); } } }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { using (WriteLockCookie.Create()) { var leftOperand = myExpression.LeftOperand; var rightOperand = myExpression.RightOperand; var factory = CSharpElementFactory.GetInstance(myExpression); var newExpression = factory.CreateExpression("$0?$0:$1", leftOperand, rightOperand); ModificationUtil.ReplaceChild(myExpression, newExpression); } return(null); }
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)); }
public ISentence InsertRule() { using (WriteLockCookie.Create()) { var anchor = this.myTarget.Anchor; Debug.Assert(anchor != null, "anchor != null"); var parent = anchor.Parent; var dot = ModificationUtil.AddChildAfter(parent, anchor, NTriplesTokenType.CreateDot()); var whiteSpace = ModificationUtil.AddChildAfter(parent, dot, new NewLine("\n")); return(ModificationUtil.AddChildAfter(parent, whiteSpace, this.myDeclarationToAdd)); } }
protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { using (WriteLockCookie.Create()) { // ReSharper disable once AssignNullToNotNullAttribute var factory = CSharpElementFactory.GetInstance(_argument.Expression, false); var expression = factory.CreateExpression($"\"{_suggestedName}\""); ModificationUtil.ReplaceChild(_argument.Expression, expression); } return(null); }
// When execution is said to succeed, we still cannot be sure whether temporary file exists or not. // If the process being executed was the debugger process, // it would exit normally even if the process it was debugging // (i.e. the generated transformation process) crashed private void ExecutionSucceeded([NotNull] IT4File file) { Logger.Verbose("Execution of a file succeeded"); Logger.Catch(() => { // This call is not expected to fail, but just in case using (WriteLockCookie.Create()) { TargetFileManager.TryProcessExecutionResults(file); } }); ExecutionManager.OnExecutionFinished(file); }
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); }
private bool HandleLeftBracketOrParenthTyped(ITypingContext typingContext) { ITextControl textControl = typingContext.TextControl; using (CommandProcessor.UsingCommand("Smart " + typingContext.Char)) { typingContext.CallNext(); using (WriteLockCookie.Create()) { // check if typed char is a token CachingLexer lexer = GetCachingLexer(textControl); int charPos = TextControlToLexer(textControl, textControl.Caret.Offset() - 1); if (charPos < 0 || !lexer.FindTokenAt(charPos) || lexer.TokenStart != charPos) { return(true); } if (lexer.TokenType != PsiTokenType.LBRACKET && lexer.TokenType != PsiTokenType.LPARENTH) { return(true); } // check that next token is good one TokenNodeType nextTokenType = lexer.LookaheadToken(1); if (nextTokenType != null && nextTokenType != PsiTokenType.WHITE_SPACE && nextTokenType != PsiTokenType.NEW_LINE && nextTokenType != PsiTokenType.C_STYLE_COMMENT && nextTokenType != PsiTokenType.END_OF_LINE_COMMENT && nextTokenType != PsiTokenType.SEMICOLON && nextTokenType != PsiTokenType.RBRACKET && nextTokenType != PsiTokenType.RBRACE && nextTokenType != PsiTokenType.RPARENTH) { return(true); } if (NeedAutoinsertCloseBracket(lexer)) { if (typingContext.EnsureWritable() != EnsureWritableResult.SUCCESS) { return(true); } char c = typingContext.Char; int insertPos = charPos; if (insertPos >= 0) { textControl.Document.InsertText(insertPos + 1, c == '(' ? ")" : c == '[' ? "]" : "}"); textControl.Caret.MoveTo(insertPos + 1, CaretVisualPlacement.DontScrollIfVisible); } } } } return(true); }