public ILexerFactory GetMixedLexerFactory(IBuffer buffer, IPsiSourceFile sourceFile, PsiManager manager)
        {
            var LanguageService = RaconteurLanguage.Instance.LanguageService();

            return LanguageService == null ? null
                : LanguageService.GetPrimaryLexerFactory();
        }
        /// <summary>
        /// Creates a reflector with the specified PSI manager.
        /// </summary>
        /// <param name="psiManager">The PSI manager.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="psiManager"/> is null.</exception>
        public PsiReflectionPolicy(PsiManager psiManager)
        {
            if (psiManager == null)
                throw new ArgumentNullException("psiManager");

            this.psiManager = psiManager;
        }
Exemple #3
0
        /// <summary>
        /// Performs the QuickFix, ensures the file is both writable and creates a transaction.
        /// </summary>
        /// <param name="solution">
        /// Current Solution.
        /// </param>
        /// <param name="progress">
        /// Progress Indicator for the fix.
        /// </param>
        /// <returns>
        /// The execute transaction.
        /// </returns>
        protected override Action <ITextControl> ExecuteTransaction(ISolution solution, JB::JetBrains.Application.Progress.IProgressIndicator progress)
        {
            return(delegate(ITextControl textControl)
            {
                DocumentManager.GetInstance(solution).SaveAllDocuments();

                using (DocumentManager.GetInstance(solution).EnsureWritable())
                {
                    PsiManager.GetInstance(solution).DoTransaction(() => this.ExecuteWriteLockableTransaction(solution, textControl));
                }
            });
        }
        private ICSharpFile GetCodeFile(string fileName)
        {
            PsiManager   manager     = PsiManager.GetInstance(Solution);
            IProjectFile projectFile = Project.GetAllProjectFiles(file => file.Name.Equals(fileName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

            if (projectFile != null)
            {
                return(manager.GetPsiFile(projectFile.ToSourceFile(), CSharpLanguage.Instance) as ICSharpFile);
            }

            return(null);
        }
Exemple #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T4FileDataCache"/> class.
        /// </summary>
        /// <param name="lifetime">The lifetime of this class.</param>
        /// <param name="psiManager">The PSI manager.</param>
        /// <param name="directiveInfoManager">An instance of <see cref="DirectiveInfoManager"/>.</param>
        public T4FileDataCache([NotNull] Lifetime lifetime, [NotNull] PsiManager psiManager, [NotNull] DirectiveInfoManager directiveInfoManager)
        {
            _directiveInfoManager = directiveInfoManager;
            _fileDataChanged      = new Signal <Pair <IPsiSourceFile, T4FileDataDiff> >(lifetime, "T4FileDataCache.FileDataChanged");

            lifetime.AddBracket(
                () => psiManager.PsiFileCreated += OnPsiFileChanged,
                () => psiManager.PsiFileCreated -= OnPsiFileChanged);
            lifetime.AddBracket(
                () => psiManager.PhysicalPsiChanged += OnPhysicalPsiChanged,
                () => psiManager.PhysicalPsiChanged -= OnPhysicalPsiChanged);
            lifetime.AddDispose(_fileDataBySourceFile);
        }
Exemple #6
0
        private void UpdateUI()
        {
            Shell.Instance.Invocator.ReentrancyGuard.ExecuteOrQueue("AddDependencyPage.UpdateUI", delegate
            {
                if (IsDisposed)
                {
                    return;
                }
                using (ReadLockCookie.Create())
                    PsiManager.GetInstance(_solution).CommitAllDocuments();

                FormValidator.GetInstance(this).Update();
            });
        }
Exemple #7
0
        /// <summary>
        /// Performs the QuickFix, ensures the file is both writable and creates a transaction.
        /// </summary>
        /// <param name="solution">
        /// Current Solution.
        /// </param>
        /// <param name="progress">
        /// Progress Indicator for the fix.
        /// </param>
        /// <returns>
        /// The execute transaction.
        /// </returns>
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, JB::JetBrains.Application.Progress.IProgressIndicator progress)
        {
            return(delegate(ITextControl textControl)
            {
                solution.GetComponent <DocumentManagerOperations>().SaveAllDocuments();

                using (
                    JB::JetBrains.Util.ITransactionCookie documentTransaction =
                        solution.GetComponent <DocumentTransactionManager>().CreateTransactionCookie(JB::JetBrains.Util.DefaultAction.Commit, "action name"))
                {
                    PsiManager.GetInstance(solution).DoTransaction(() => this.ExecuteWriteLockableTransaction(solution, textControl), "Code cleanup");
                }
            });
        }
Exemple #8
0
        public void Process(IPsiSourceFile sourceFile, IRangeMarker rangeMarkerMarker, CodeCleanupProfile profile, IProgressIndicator progressIndicator)
        {
            ISolution solution = sourceFile.GetSolution();

            if (!profile.GetSetting(OurDescriptor))
            {
                return;
            }

            IPsiFile[] files = sourceFile.GetPsiFiles <PsiLanguage>().Cast <IPsiFile>().ToArray();
            using (progressIndicator.SafeTotal("Reformat Psi", files.Length))
            {
                foreach (IPsiFile 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");
                        }
                    }
                }
            }
        }
Exemple #9
0
        public override IDeclaredElement GetDeclaredElement()
        {
            ISolution solution = GetSolution();

            if (solution == null)
            {
                return(null);
            }

            using (ReadLockCookie.Create())
            {
                DeclarationsCacheScope scope = DeclarationsCacheScope.SolutionScope(solution, false);
                IDeclarationsCache     cache = PsiManager.GetInstance(solution).GetDeclarationsCache(scope, true);
                return(cache.GetTypeElementByCLRName(GetTypeClrName()));
            }
        }
        protected ITypeElement GetDeclaredType()
        {
            ISolution solution = GetSolution();

            if (solution == null)
            {
                return(null);
            }

            using (ReadLockCookie.Create())
            {
                IDeclarationsScope scope = DeclarationsScopeFactory.SolutionScope(solution, false);
                IDeclarationsCache cache = PsiManager.GetInstance(solution).GetDeclarationsCache(scope, true);
                return(cache.GetTypeElementByCLRName(_declaringTypeName));
            }
        }
        protected ITypeElement GetDeclaredType()
        {
            IProject project = GetProject();

            if (project == null)
            {
                return(null);
            }
            PsiManager manager = PsiManager.GetInstance(project.GetSolution());

            using (ReadLockCookie.Create())
            {
                IDeclarationsCache declarationsCache = manager.GetDeclarationsCache(DeclarationsScopeFactory.ModuleScope(PsiModuleManager.GetInstance(project.GetSolution()).GetPrimaryPsiModule(project), true), true);
                return(declarationsCache.GetTypeElementByCLRName(myTypeName));
            }
        }
        public override void SetUp()
        {
            base.SetUp();
            WrapperAssert.SupportsSpecialFeatures            = false;
            WrapperAssert.SupportsSpecialName                = false;
            WrapperAssert.SupportsCallingConventions         = false;
            WrapperAssert.SupportsReturnAttributes           = false;
            WrapperAssert.SupportsEventFields                = false;
            WrapperAssert.SupportsGenericParameterAttributes = false;
            WrapperAssert.SupportsFinalizers         = false;
            WrapperAssert.SupportsStaticConstructors = false; // compiler generated static constructors introduced by static readonly fields are not supported

            PsiManager manager = PsiManager.GetInstance(SolutionManager.Instance.CurrentSolution);

            reflectionPolicy = new PsiReflectionPolicy(manager);
        }
        public void Execute(ISolution solution, ITextControl textControl)
        {
            using (ReadLockCookie.Create())
            {
                var manager = PsiManager.GetInstance(solution);
                manager.CommitAllDocuments();

                IProjectItem parentFolder = GetParentFolder(_sourceTypeDeclaration);
                MoveToOuterFile();

                IProjectItem sourceFile = GetSourceFile(parentFolder, _sourceTypeDeclaration);
                IProjectFile newFile    = MoveFileToProject(sourceFile);
                OpenFileInEditor(solution, newFile);
                sourceFile.Remove();
            }
        }
        private void UpdateUI()
        {
            var shellLocks = Shell.Instance.GetComponent <IShellLocks>();

            shellLocks.ReentrancyGuard.ExecuteOrQueue(
                "AddDependencyPage.UpdateUI",
                delegate
            {
                if (IsDisposed)
                {
                    return;
                }
                using (ReadLockCookie.Create())
                    PsiManager.GetInstance(_solution).CommitAllDocuments();

                Shell.Instance.GetComponent <FormValidators>().GetOrCreate(this).Update();
            });
        }
Exemple #15
0
        protected ITypeElement GetDeclaredType()
        {
            IProject project = GetProject();

            if (project == null)
            {
                return(null);
            }

            using (ReadLockCookie.Create())
            {
                var solution                         = GetSolution();
                var module                           = PsiModuleManager.GetInstance(solution).GetPsiModule(GetProject().ProjectFile);
                IDeclarationsScope scope             = DeclarationsScopeFactory.ModuleScope(module, true);
                IDeclarationsCache declarationsCache = PsiManager.GetInstance(solution).GetDeclarationsCache(scope, true);

                return(declarationsCache.GetTypeElementByCLRName(myTypeName));
            }
        }
Exemple #16
0
        /// <summary>
        /// Executes the process.
        /// The process should check for <see cref="P:JetBrains.ReSharper.Daemon.IDaemonProcess.InterruptFlag"/> periodically (with intervals less than 100 ms)
        /// and throw <see cref="T:JetBrains.Application.Progress.ProcessCancelledException"/> if it is true.
        /// Failing to do so may cause the program to prevent user from typing while analysing the code.
        /// Stage results should be passed to <param name="commiter"/>. If DaemonStageResult is <c>null</c>, it means that no highlightings available
        /// </summary>
        public void Execute(Action <DaemonStageResult> commiter)
        {
            if (DaemonProcess.InterruptFlag)
            {
                return;
            }

            PsiManager manager    = PsiManager.GetInstance(DaemonProcess.Solution);
            var        sourceFile = manager.GetPsiFile(DaemonProcess.SourceFile, CSharpLanguage.Instance) as ICSharpFile;

            if (sourceFile != null)
            {
                List <INamingConsistencyChecker> list =
                    LanguageManager.Instance.GetServices <INamingConsistencyChecker>(sourceFile.Language).Where(x => x.IsApplicable(DaemonProcess.SourceFile)).ToList();

                list.ForEach(Console.WriteLine);

                var highlights = new List <HighlightingInfo>();

                // highlight field declarations
                var processor = new RecursiveElementProcessor <IFieldDeclaration>(
                    declaration =>
                {
                    DocumentRange docRange = declaration.GetNameDocumentRange();

                    highlights.Add(new HighlightingInfo(docRange, new NameInfoHighlighting(declaration)));
                });
                sourceFile.ProcessDescendants(processor);

                // highlight local var declarations
                var localVarsProcessor = new RecursiveElementProcessor <ILocalVariableDeclaration>(
                    declaration =>
                {
                    DocumentRange docRange = declaration.GetNameDocumentRange();

                    highlights.Add(new HighlightingInfo(docRange, new NameInfoHighlighting(declaration)));
                });
                sourceFile.ProcessDescendants(localVarsProcessor);

                commiter(new DaemonStageResult(highlights));
            }
        }
Exemple #17
0
        private bool FileIsValid()
        {
            PsiManager manager = PsiManager.GetInstance(this.daemonProcess.Solution);

            if (!this.daemonProcess.SourceFile.ToProjectFile().IsValid())
            {
                return(false);
            }

            IFile file = this.daemonProcess.SourceFile.GetPsiFile(CSharpLanguage.Instance);

            if (file == null)
            {
                return(false);
            }

            bool hasErrorElements = new RecursiveElementCollector <ErrorElement>().ProcessElement(file).GetResults().Any();

            return(!hasErrorElements);
        }
Exemple #18
0
        private bool ReferenceModuleImpl([NotNull] IPsiModule module, [NotNull] IPsiModule moduleToReference, [CanBeNull] string ns)
        {
            if (!CanReferenceModule(module, moduleToReference))
            {
                return(false);
            }

            var t4PsiModule = (T4PsiModule)module;
            var assembly    = (IAssembly)moduleToReference.ContainingProjectModule;

            Assertion.AssertNotNull(assembly, "assembly != null");

            var t4File = t4PsiModule.SourceFile.GetNonInjectedPsiFile <T4Language>() as IT4File;

            if (t4File == null)
            {
                return(false);
            }

            Action action = () => {
                // add assembly directive
                AddDirective(t4File, _directiveInfoManager.Assembly.CreateDirective(assembly.FullAssemblyName));

                // add import directive if necessary
                if (!String.IsNullOrEmpty(ns) &&
                    !t4File.GetDirectives(_directiveInfoManager.Import).Any(d => String.Equals(ns, d.GetAttributeValue(_directiveInfoManager.Import.NamespaceAttribute.Name), StringComparison.Ordinal)))
                {
                    AddDirective(t4File, _directiveInfoManager.Import.CreateDirective(ns));
                }
            };

            PsiManager psiManager = PsiManager.GetInstance(module.GetSolution());

            if (psiManager.HasActiveTransaction)
            {
                action();
                return(true);
            }
            return(psiManager.DoTransaction(action, "T4 Assembly Reference").Succeded);
        }
Exemple #19
0
        public void ExecuteTemplate()
        {
            IDeclaration newDeclaration = myDeclaration;

            newDeclaration.AssertIsValid();

            ISolution solution = newDeclaration.GetPsiModule().GetSolution();

            Shell.Instance.Invocator.Dispatcher.AssertAccess();

            Assertion.Assert(!PsiManager.GetInstance(solution).HasActiveTransaction, "PSI transaction is active");
            solution.GetComponent <SolutionDocumentTransactionManager>().AssertNotUnderTransaction();

            IFile file = myAnchor.GetContainingFile();

            Assertion.Assert(file != null, "file!= null");
            var item = file.GetSourceFile().ToProjectFile();

            var infos = GetFieldInfos(newDeclaration, myHolders);

            var textControl = EditorManager.GetInstance(solution).OpenProjectFile(item, true, TabOptions.DefaultTab);

            if (textControl == null)
            {
                if (Shell.Instance.IsInInternalMode || Shell.Instance.IsTestShell)
                {
                    Logger.Fail("textControl != null");
                }
                return;
            }

            if (infos.Length > 0)
            {
                HotspotSession hotspotSession = LiveTemplatesManager.Instance.CreateHotspotSessionAtopExistingText(solution,
                                                                                                                   TextRange.InvalidRange, textControl, LiveTemplatesManager.EscapeAction.LeaveTextAndCaret, infos);
                hotspotSession.Execute();
            }

            Shell.Instance.GetComponent <PsiIntentionResultBehavior>().OnHotspotSessionExecutionStarted(this, textControl);
        }
Exemple #20
0
        /// <summary>
        /// This code changes PSI documents. It is executed usder PSI transaction, Command cookies, Reentrancy guard ets.
        /// All documents are committed (PSI is valid).
        /// </summary>
        public override bool Execute(IProgressIndicator pi)
        {
            pi.Start(6);

            //check if data stored in workflow is valid...
            Method    = Workflow.MethodPointer.FindDeclaredElement();
            Parameter = Workflow.ParameterPointer.FindDeclaredElement();

            if (Method == null || Parameter == null)
            {
                return(false);
            }

            IPsiServices services = Parameter.GetPsiServices();

            IReference[] referencesToParameter;
            IReference[] referencesToRootOverrides;

            // search for method overrides (OverridesFinder is util class that
            // allows to find all overrides and problems with quasi implementations)
            OverridesFinder overridesFinder = OverridesFinder.CreateInstance(Method);

            using (var subPi = new SubProgressIndicator(pi, 1))
                overridesFinder.Find(subPi);

            JetHashSet <HierarchyMember> hierarchyMembers = overridesFinder.Overrides;

            List <IMethod>    methods    = ScanHierarchyConflicts(hierarchyMembers).ToList();
            List <IParameter> parameters = GetAllParameters(methods).ToList();

            // find parameters and methods usages...
            using (var subPi = new SubProgressIndicator(pi, 1))
            {
                subPi.TaskName = "Searching parameter usages:";
                IEnumerable <IPsiSourceFile> projectFiles = from param in parameters
                                                            let projectFilesOfOneParameter = param.GetSourceFiles()
                                                                                             from projectFile in projectFilesOfOneParameter
                                                                                             select projectFile;
                ISearchDomain searchDomain = mySearchDomainFactory.CreateSearchDomain(projectFiles.ToList());
                referencesToParameter = services.Finder.FindReferences(parameters, searchDomain, subPi);
            }

            using (var subPi = new SubProgressIndicator(pi, 1))
            {
                subPi.TaskName            = "Searching method usages:";
                referencesToRootOverrides = services.Finder.FindReferences(methods,
                                                                           mySearchDomainFactory.CreateSearchDomain(Solution,
                                                                                                                    false), subPi);
            }

            // this step processes method usages, removes argument and stores reference specific data to the 'MethodInvocation'.
            List <MethodInvocation> usages;

            using (var subPi = new SubProgressIndicator(pi, 1))
                usages = PreProcessMethodUsages(referencesToRootOverrides, subPi).ToList();

            // replace usages of parameters with typeof(TNewTypeParameter) expression.
            using (var subPi = new SubProgressIndicator(pi, 1))
                ProcessParameterUsages(referencesToParameter, subPi);

            // Remove parameters from method declarations and insert new type parmeter. Map contains method -> new type parameter relation.
            Dictionary <IMethod, ITypeParameter> map = UpdateDeclarations(methods);

            // We have changed declarations. cashes should be updated)
            PsiManager.GetInstance(Solution).UpdateCaches();

            // Process method usages one more time to insert correct type arguments to the call.
            using (var subPi = new SubProgressIndicator(pi, 1))
                BindUsages(usages, map, subPi);

            return(true);
        }
 private void RegisterPsiChanged([NotNull] Lifetime lifetime, [NotNull] PsiManager psiFiles)
 {
     lifetime.AddBracket(
         () => psiFiles.PhysicalPsiChanged += OnPsiChanged,
         () => psiFiles.PhysicalPsiChanged -= OnPsiChanged);
 }
        public ILexerFactory GetMixedLexerFactory(IBuffer buffer, IPsiSourceFile sourceFile, PsiManager manager)
        {
            var LanguageService = RaconteurLanguage.Instance.LanguageService();

            return(LanguageService == null ? null
                : LanguageService.GetPrimaryLexerFactory());
        }
        protected bool ConfigureService()
        {
            Logger.Info <SactaProxy>("Configurando Servicio");
            cfgManager.Get((cfg =>
            {
                // Se utiliza 'siempre' version 0 para CD30 y version 1 para ULISES.
                cfg.ProtocolVersion = Properties.Settings.Default.ScvType;
                History.Configure(cfg.General.HistoryMaxDays, cfg.General.HistoryMaxItems);
                Managers.Clear();
                cfg.Psi.Sectorization.Positions = "";
                cfg.Psi.Sectorization.Sectors = "";
                cfg.Psi.Sectorization.Virtuals = "";

                var manager = new PsiManager(cfg.ProtocolVersion, cfg.Psi, () => History);
                manager.EventActivity += OnPsiEventActivity;
                manager.EventSectRequest += OnPsiEventSectorizationAsk;
                Managers.Add(new DependencyControl(cfg.Psi.Id)
                {
                    IsMain = true,
                    Cfg = cfg.Psi,
                    Manager = manager
                });
                cfg.Dependencies.ForEach(dep =>
                {
                    var dependency = new ScvManager(cfg.ProtocolVersion, dep, () => History);
                    dependency.EventActivity += OnScvEventActivity;
                    dependency.EventSectorization += OnScvEventSectorization;

                    /** Construyendo la configuracion de Sectorizacion general */
                    var sectorsMap = dep.Sectorization.SectorsMap.Split(',')
                                     .Where(i => Configuration.MapOfSectorsEntryValid(i))
                                     .ToDictionary(k => int.Parse(k.Split(':')[0]), v => int.Parse(v.Split(':')[1]));
                    var positionsMap = dep.Sectorization.PositionsMap.Split(',')
                                       .Where(i => Configuration.MapOfSectorsEntryValid(i))
                                       .ToDictionary(k => int.Parse(k.Split(':')[0]), v => int.Parse(v.Split(':')[1]));
                    var virtuals = Configuration.ListString2String(
                        dep.Sectorization.VirtualsList()
                        .Select(v => sectorsMap.Keys.Contains(v) ? sectorsMap[v].ToString() : v.ToString())
                        .ToList());
                    var reals = String.Join(",", dep.Sectorization.SectorsList()
                                            .Select(r => sectorsMap.Keys.Contains(r) ? sectorsMap[r].ToString() : r.ToString())
                                            .ToList());
                    //.Aggregate((i, j) => i + "," + j.ToString());
                    var positions = String.Join(",", dep.Sectorization.PositionsList()
                                                .Select(p => positionsMap.Keys.Contains(p) ? positionsMap[p].ToString() : p.ToString())
                                                .ToList());
                    //.Aggregate((i, j) => i + "," + j.ToString());

                    cfg.Psi.Sectorization.Positions = Configuration.AgreggateString(cfg.Psi.Sectorization.Positions, positions);
                    cfg.Psi.Sectorization.Virtuals = Configuration.AgreggateString(cfg.Psi.Sectorization.Virtuals, virtuals);
                    cfg.Psi.Sectorization.Sectors = Configuration.AgreggateString(cfg.Psi.Sectorization.Sectors, reals);

                    Managers.Add(new DependencyControl(dep.Id)
                    {
                        IsMain = false,
                        Cfg = dep,
                        Manager = dependency,
                        SectorsMap = sectorsMap,
                        PositionsMap = positionsMap
                    });
                });
                /** Test de la configuracion que maneja la PSI, que debe coincidir con la configurada en BD */
                SectorizationHelper.CompareWithDb(cfg.Psi.Sectorization.Positions,
                                                  cfg.Psi.Sectorization.Sectors, cfg.Psi.Sectorization.Virtuals, (error) =>
                {
                    // Marcar el Warning...
                    PS.SignalWarning <SactaProxy>($"Incoherencia de Configuración con Base de Datos: {error}", History);
                });
                /** */
                var ids = cfg.Dependencies.Select(d => d.Id).ToList();
                ids.Add(cfg.Psi.Id);
                SectorizationPersistence.Sanitize(ids);
                Cfg = cfg;
                cfgManager.Write(Cfg);
                Logger.Info <SactaProxy>("Servicio Configurado...");
            }));
            return(true);
        }
Exemple #24
0
    private static IEnumerable <ICSharpFile> GetAllCSharpFilesInProject(IPsiModule projectModule)
    {
        PsiManager psiManager = projectModule.GetPsiServices().PsiManager;

        return(projectModule.SourceFiles.SelectMany(f => psiManager.GetPsiFiles <CSharpLanguage>(f).OfType <ICSharpFile>()));
    }
        private void DoSmartIndentOnEnter(ITextControl textControl)
        {
            var originalOffset = textControl.Caret.Offset();

            var offset     = TextControlToLexer(textControl, originalOffset);
            var mixedLexer = GetCachingLexer(textControl);

            // if there is something on that line, then use existing text
            if (offset <= 0 || !mixedLexer.FindTokenAt(offset - 1))
            {
                return;
            }

            if (mixedLexer.TokenType == PsiTokenType.C_STYLE_COMMENT || mixedLexer.TokenType == PsiTokenType.STRING_LITERAL)
            {
                return;
            }

            if (offset <= 0 || !mixedLexer.FindTokenAt(offset))
            {
                return;
            }

            while (mixedLexer.TokenType == PsiTokenType.WHITE_SPACE)
            {
                mixedLexer.Advance();
            }

            offset = mixedLexer.TokenType == null ? offset : mixedLexer.TokenStart;
            var extraText = (mixedLexer.TokenType == PsiTokenType.NEW_LINE || mixedLexer.TokenType == null) ? "foo " : String.Empty;

            var projectItem = textControl.Document.GetPsiSourceFile(Solution);

            if (projectItem == null || !projectItem.IsValid())
            {
                return;
            }

            using (PsiManager.GetInstance(Solution).DocumentTransactionManager.CreateTransactionCookie(DefaultAction.Commit, "Typing assist"))
            {
                // If the new line is empty, the do default indentation
                int lexerOffset = offset;
                if (extraText.Length > 0)
                {
                    textControl.Document.InsertText(lexerOffset, extraText);
                }

                PsiServices.PsiManager.CommitAllDocuments();
                var file = projectItem.GetPsiFile <PsiLanguage>(new DocumentRange(textControl.Document, offset));

                if (file == null)
                {
                    return;
                }

                var rangeInJsTree = file.Translate(new DocumentOffset(textControl.Document, offset));

                if (!rangeInJsTree.IsValid())
                {
                    if (extraText.Length > 0)
                    {
                        textControl.Document.DeleteText(new TextRange(lexerOffset, lexerOffset + extraText.Length));
                    }
                    return;
                }

                var tokenNode = file.FindTokenAt(rangeInJsTree) as ITokenNode;
                if (tokenNode == null)
                {
                    if (extraText.Length > 0)
                    {
                        textControl.Document.DeleteText(new TextRange(lexerOffset, lexerOffset + extraText.Length));
                    }
                    return;
                }

                PsiCodeFormatter codeFormatter = GetCodeFormatter(file);
                int offsetInToken = rangeInJsTree.Offset - tokenNode.GetTreeStartOffset().Offset;

                using (PsiTransactionCookie.CreateAutoCommitCookieWithCachesUpdate(PsiServices, "Typing assist"))
                {
                    Lifetimes.Using(
                        lifetime =>
                    {
                        var boundSettingsStore = SettingsStore.CreateNestedTransaction(lifetime, "PsiTypingAssist").BindToContextTransient(textControl.ToContextRange());
                        var prevToken          = tokenNode.GetPrevToken();
                        if (prevToken == null)
                        {
                            return;
                        }

                        if (tokenNode.Parent is IParenExpression || prevToken.Parent is IParenExpression)
                        {
                            var node = tokenNode.Parent;
                            if (prevToken.Parent is IParenExpression)
                            {
                                node = prevToken.Parent;
                            }
                            codeFormatter.Format(node.FirstChild, node.LastChild,
                                                 CodeFormatProfile.DEFAULT, NullProgressIndicator.Instance, boundSettingsStore);
                        }
                        else
                        {
                            codeFormatter.Format(prevToken, tokenNode,
                                                 CodeFormatProfile.INDENT, NullProgressIndicator.Instance, boundSettingsStore);
                        }
                    });
                    offset = file.GetDocumentRange(tokenNode.GetTreeStartOffset()).TextRange.StartOffset +
                             offsetInToken;
                }

                if (extraText.Length > 0)
                {
                    lexerOffset = offset;
                    textControl.Document.DeleteText(new TextRange(lexerOffset, lexerOffset + extraText.Length));
                }
            }

            textControl.Caret.MoveTo(offset, CaretVisualPlacement.DontScrollIfVisible);
        }
Exemple #26
0
        public bool Execute(IProgressIndicator progressIndicator)
        {
            var ctor = _ctor.FindDeclaredElement();

            if (ctor == null)
            {
                return(false);
            }
            var definingClass = _class.FindDeclaredElement();

            if (definingClass == null)
            {
                return(false);
            }
            if (ctor.Module == null)
            {
                return(false);
            }
            var factory  = CSharpElementFactory.GetInstance(ctor.Module);
            var ctorDecl = ctor.GetDeclarations().FirstOrDefault();

            if (ctorDecl == null)
            {
                var typeDecl = definingClass.GetDeclarations().FirstOrDefault() as IClassLikeDeclarationNode;
                if (typeDecl == null)
                {
                    return(false);
                }
                var typeBody = typeDecl.Body;
                ctorDecl = factory.CreateTypeMemberDeclaration("public $0() {}", typeDecl.DeclaredName);
                if (typeBody.FirstChild == null)
                {
                    return(false);
                }
                if (ctorDecl == null)
                {
                    return(false);
                }

                ctorDecl = ModificationUtil.AddChildBefore(
                    typeBody,
                    typeBody.FirstChild.NextSibling,
                    ctorDecl.ToTreeNode()).GetContainingElement <IConstructorDeclaration>(true);
            }
            if (ctorDecl == null)
            {
                return(false);
            }
            var type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.ToTreeNode());

            if (!type.IsResolved)
            {
                type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.GetPsiModule());
            }
            string recommendedName = null;
            var    naming          = PsiManager.GetInstance(_solution).Naming;

            if (!type.IsResolved)
            {
                var presentableName = type.GetPresentableName(CSharpLanguageService.CSHARP);
                var indexOfGeneric  = presentableName.IndexOf('<');
                if (indexOfGeneric != -1)
                {
                    var interfaceName   = presentableName.Substring(1, indexOfGeneric - 1);
                    var genericArgument = presentableName.Substring(indexOfGeneric).Trim('<', '>');
                    recommendedName = naming.Suggestion.GetDerivedName(
                        genericArgument + interfaceName,
                        NamedElementKinds.Parameters,
                        ScopeKind.Common,
                        CSharpLanguageService.CSHARP,
                        new SuggestionOptions());
                }
                var interfaceDecl = factory.CreateTypeMemberDeclaration("public interface IFoo {}");
                if (interfaceDecl == null)
                {
                    return(false);
                }
                interfaceDecl.SetName(presentableName);
                interfaceDecl.LanguageService.CodeFormatter.Format(interfaceDecl.ToTreeNode(), CodeFormatProfile.GENERATOR);
                var containingType = ctor.GetContainingType();
                if (containingType == null)
                {
                    return(false);
                }
                var containingTypeDecl = containingType.GetDeclarations().First();
                ModificationUtil.AddChildBefore(containingTypeDecl.ToTreeNode(), interfaceDecl.ToTreeNode());
            }
            type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.ToTreeNode());
            if (recommendedName == null)
            {
                var suggestionOptions = new SuggestionOptions();
                recommendedName = naming.Suggestion.GetDerivedName(
                    type.GetPresentableName(CSharpLanguageService.CSHARP),
                    NamedElementKinds.Parameters, ScopeKind.Common,
                    CSharpLanguageService.CSHARP, suggestionOptions);
            }
            var parametersOwner = ctorDecl as ICSharpParametersOwnerDeclaration;
            var references      = FindReferences(parametersOwner, progressIndicator);

            if (parametersOwner == null)
            {
                return(false);
            }
            parametersOwner.AddParameterDeclarationAfter(
                ParameterKind.VALUE, type, recommendedName,
                parametersOwner.ParameterDeclarations.LastOrDefault());

            foreach (var reference in references)
            {
                ChangeReference(reference, recommendedName, type);
            }

            return(true);
        }