// Return a context object for the item being searched for, or null if the element isn't interesting. // CanContainReferences isn't called if we return null. Do the work once here, then use it multiple times for // each file in CanContainReferences public object GetElementId(IDeclaredElement element) { if (!UnityYamlUsageSearchFactory.IsInterestingElement(element)) { return(null); } var set = new JetHashSet <IPsiSourceFile>(); switch (element) { case IClass _class: foreach (var sourceFile in myAssetScriptUsagesElementContainer.GetPossibleFilesWithUsage(_class)) { set.Add(sourceFile); } break; case IProperty _: case IMethod _: foreach (var sourceFile in myUnityEventsElementContainer.GetPossibleFilesWithUsage(element)) { set.Add(sourceFile); } break; case IField field: if (field.Type.GetTypeElement().DerivesFromUnityEvent()) { foreach (var sourceFile in myUnityEventsElementContainer.GetPossibleFilesWithUsage(element)) { set.Add(sourceFile); } } else { foreach (var sourceFile in myInspectorValuesContainer.GetPossibleFilesWithUsage(field)) { set.Add(sourceFile); } } break; } return(new UnityYamlSearchGuruId(set)); }
void ICache.OnPsiChange(ITreeNode elementContainingChanges, PsiChangedElementType type) { if (elementContainingChanges == null) { return; } var sourceFile = elementContainingChanges.GetSourceFile(); if ((sourceFile != null) && sourceFile.PrimaryPsiLanguage.Is <JavaScriptLanguage>()) { lock (_lock) { _dirtyFiles.Add(sourceFile); } } }
private void QueueInstall(UnityPluginDetector.InstallationInfo installationInfo, bool force = false) { myQueue.Enqueue(() => { Install(installationInfo, force); myPluginInstallations.Add(mySolution.SolutionFilePath); }); }
public IEnumerable <string> GetAllPossibleWordsInFile(IDeclaredElement element) { var names = new JetHashSet <string>(); names.Add(element.ShortName); return(names); }
private void HandleAssemblyDirective([NotNull] IT4AssemblyDirective directive) { // i.e. non-empty if (!(directive.Path is T4PathWithMacros path)) { return; } ReferencedAssemblies.Add(path); }
private JetHashSet <string> CreateSemanticsSet() { var result = new JetHashSet <string>(StringComparer.InvariantCultureIgnoreCase); foreach (var semantic in ourParametrizedSemantics) { result.Add(semantic); for (int i = 0; i < 9; i++) { result.Add($"{semantic}{i}"); } } foreach (var semantic in ourFixedSemantics) { result.Add(semantic); } return(result); }
private void HandleAssemblyDirective([NotNull] IT4AssemblyDirective directive) { // i.e. non-empty var existingPath = directive.ResolvedPath; if (!existingPath.ResolvedPath.IsNotEmpty()) { return; } ReferencedAssemblies.Add(existingPath); }
private static JetHashSet <string> ReadSet(UnsafeReader reader) { var count = reader.ReadInt32(); var list = new JetHashSet <string>(); for (int i = 0; i < count; i++) { list.Add(reader.ReadString()); } return(list); }
private List <string> InitElementsMap(IEnumerable <IUnitTestElement> unitTestElements, Dictionary <string, IUnitTestElement> elementToIdMap) { var result = new JetHashSet <string>(); foreach (var unitTestElement in unitTestElements) { if (unitTestElement is NUnitTestElement) { var unityName = string.Format(unitTestElement.Id); elementToIdMap[unityName] = unitTestElement; result.Add(unityName); } if (unitTestElement is UnityTestElement) { var unityName = string.Format(unitTestElement.Id); elementToIdMap[unityName] = unitTestElement; result.Add(unityName); } } return(result.ToList()); }
private List <string> InitElementsMap(IEnumerable <IUnitTestElement> unitTestElements) { var result = new JetHashSet <string>(); foreach (var unitTestElement in unitTestElements) { if (unitTestElement is NUnitTestElement || unitTestElement is NUnitRowTestElement || unitTestElement is UnityTestElement) { var unityName = unitTestElement.Id; myElements[unitTestElement.Id] = unitTestElement; result.Add(unityName); } } return(result.ToList()); }
public NitraReferenceSearcher(NitraSearcherFactory factory, IEnumerable <IDeclaredElement> elements, bool findCandidates, bool searchForLateBound) { myFindCandidates = findCandidates; mySearchForLateBound = searchForLateBound; myElements = new JetHashSet <IDeclaredElement>(elements); myNames = new JetHashSet <string>(); myWordsInText = new JetHashSet <string>(); foreach (var element in myElements) { myNames.Add(element.ShortName); myWordsInText.UnionWith(factory.GetAllPossibleWordsInFile(element)); } myWordIndex = myElements.First().GetPsiServices().WordIndex; }
private static void AddWords(OneToSetMap <string, string> wordsPerAssembly, JetHashSet <string> abbreviations, IAssemblyPsiModule assemblyPsiModule, string name) { var textParts = TextSplitter.Split(name); foreach (var textPart in textParts.Where(tp => tp.Type == TextPartType.Word)) { if (textPart.Text == textPart.Text.ToUpperInvariant()) { abbreviations.Add(textPart.Text); } else { wordsPerAssembly.Add(assemblyPsiModule.Assembly.AssemblyName.Name, textPart.Text); } } }
internal static void GetMacros([CanBeNull] string stringWithMacros, [NotNull] JetHashSet <string> outMacros) { if (String.IsNullOrEmpty(stringWithMacros) || stringWithMacros.IndexOf("$(", StringComparison.Ordinal) < 0) { return; } MatchCollection matches = _vsMacroRegEx.Matches(stringWithMacros); foreach (Match match in matches) { if (match.Success) { outMacros.Add(match.Groups[1].Value); } } }
/// <summary> /// Handles an assembly directive. /// </summary> /// <param name="directive">The directive containing a potential assembly reference.</param> private void HandleAssemblyDirective([NotNull] IT4Directive directive) { string assemblyNameOrFile = directive.GetAttributeValue(_directiveInfoManager.Assembly.NameAttribute.Name); if (assemblyNameOrFile == null || (assemblyNameOrFile = assemblyNameOrFile.Trim()).Length == 0) { // Handle <#@ assembly name="" completion="someassembly" #>, which is a ForTea-specific way // to get completion for an implicit assembly (for example, added by a custom directive). assemblyNameOrFile = directive.GetAttributeValue("completion"); if (assemblyNameOrFile == null || (assemblyNameOrFile = assemblyNameOrFile.Trim()).Length == 0) { return; } } VsBuildMacroHelper.GetMacros(assemblyNameOrFile, _macros); _referencedAssemblies.Add(assemblyNameOrFile); }
public static MemberDecoration GetDecoration(IAccessModifiers accessModifiers, TreeNodeEnumerable <IFSharpAttribute> attributes) { var decoration = MemberDecoration.DefaultValue; var modifiers = new JetHashSet <TokenNodeType>(); if (accessModifiers != null) { foreach (var modifier in accessModifiers.Modifiers) { modifiers.Add(modifier.GetTokenType()); } } if (modifiers.Contains(FSharpTokenType.PUBLIC)) { decoration.Modifiers |= Modifiers.PUBLIC; } if (modifiers.Contains(FSharpTokenType.INTERNAL)) { decoration.Modifiers |= Modifiers.INTERNAL; } if (modifiers.Contains(FSharpTokenType.PRIVATE)) { decoration.Modifiers |= Modifiers.PRIVATE; } foreach (var attr in attributes) { switch (attr.GetShortName()) { case FSharpImplUtil.AbstractClass: decoration.Modifiers |= Modifiers.ABSTRACT; break; case FSharpImplUtil.Sealed: decoration.Modifiers |= Modifiers.SEALED; break; } } return(Normalize(decoration)); }
protected override bool AddLookupItems(ISpecificCodeCompletionContext context, IItemsCollector collector) { var languageCaseProvider = LanguageManager.Instance.TryGetService <LanguageCaseProvider>(language); var templateNames = new JetHashSet <string>(languageCaseProvider.IfNotNull(cp => cp.IsCaseSensitive() ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase)); IEnumerable <TemplateLookupItem> templateItems = TemplateActionsUtil.GetLookupItems(context.BasicContext.TextControl, context.BasicContext.CompletionManager.Solution, false, false); var prefix = LiveTemplatesManager.GetPrefix(context.BasicContext.CaretDocumentOffset, JsAllowedPrefixes.Chars); if (collector.Ranges == null) { var caretOffset = context.BasicContext.CaretDocumentOffset; var prefixRange = new DocumentRange(caretOffset - prefix.Length, caretOffset); collector.AddRanges(new TextLookupRanges(prefixRange, prefixRange)); } if (!string.IsNullOrEmpty(prefix)) { var identifierMatcher = LookupUtil.CreateMatcher(prefix, context.BasicContext.IdentifierMatchingStyle); templateItems = templateItems.Where(item => identifierMatcher.Matches(item.Template.Shortcut)); } foreach (var templateItem in templateItems) { templateNames.Add(templateItem.DisplayName.Text); } if (templateItems.IsEmpty()) { return(false); } context.BasicContext.PutData(TemplateNamesKey, templateNames); foreach (var templateItem in templateItems) { collector.Add(templateItem); } return(true); }
public static MemberDecoration GetDecoration(IAccessModifiers accessModifiers, TreeNodeEnumerable <IFSharpAttribute> attributes) { var decoration = MemberDecoration.DefaultValue; var modifiers = new JetHashSet <TokenNodeType>(); foreach (var modifier in accessModifiers.Modifiers) { modifiers.Add(modifier.GetTokenType()); } if (modifiers.Contains(FSharpTokenType.PUBLIC)) { decoration.Modifiers |= Modifiers.PUBLIC; } if (modifiers.Contains(FSharpTokenType.INTERNAL)) { decoration.Modifiers |= Modifiers.INTERNAL; } if (modifiers.Contains(FSharpTokenType.PRIVATE)) { decoration.Modifiers |= Modifiers.PRIVATE; } foreach (var attr in attributes) { var ids = attr.LongIdentifier.Identifiers; if (ids.IsEmpty) { continue; } var attributeShortName = ids.Last().GetText().GetAttributeShortName(); if (attributeShortName.Equals(AbstractClass, StringComparison.Ordinal)) { decoration.Modifiers |= Modifiers.ABSTRACT; break; } } return(Normalize(decoration)); }
private void InstallPluginIfRequired(ICollection <IProject> projects) { if (projects.Count == 0) { return; } InstallFromResource(@"Library\resharper-unity-libs\nunit3.5.0\nunit.framework.dll", ".Unity3dRider.Library.resharper_unity_libs.nunit3._5._0.nunit.framework.dll"); InstallFromResource(@"Library\resharper-unity-libs\pdb2mdb.exe", ".Unity3dRider.Library.resharper_unity_libs.pdb2mdb.exe"); if (myPluginInstallations.Contains(mySolution.SolutionFilePath)) { return; } if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.InstallUnity3DRiderPlugin)) { return; } // forcing fresh install due to being unable to provide proper setting until InputField is patched in Rider // ReSharper disable once ArgumentsStyleNamedExpression var installationInfo = myDetector.GetInstallationInfo(projects, previousInstallationDir: FileSystemPath.Empty); if (!installationInfo.ShouldInstallPlugin) { myLogger.Info("Plugin should not be installed."); if (installationInfo.ExistingFiles.Count > 0) { myLogger.Info("Already existing plugin files:\n{0}", string.Join("\n", installationInfo.ExistingFiles)); } return; } myQueue.Enqueue(() => { Install(installationInfo); myPluginInstallations.Add(mySolution.SolutionFilePath); }); }
private Pair <AttributedTypesTrieCollection, JetHashSet <IPsiSourceFile> > LoadTrie(BinaryReader reader, IProgressIndicator progress) { var otherFilesCount = reader.ReadInt32(); var otherFiles = new JetHashSet <IPsiSourceFile>(); for (int i = 0; i < otherFilesCount; i++) { int persistentId = reader.ReadInt32(); var timestamp = reader.ReadInt64(); var file = myPersistentIndexManager.GetSourceFileById(persistentId); if (file != null && file.IsValid() && file.LastWriteTimeUtc.Ticks == timestamp) { otherFiles.Add(file); } } var map = new AttributedTypesTrieCollection(); map.Read(reader, myPersistentIndexManager); return(Pair.Of(map, otherFiles)); }
object IChangeProvider.Execute(IChangeMap changeMap) { var projectModelChange = changeMap.GetChange <ProjectModelChange>(mySolution); if (projectModelChange == null) { return(null); } // ReSharper hasn't necessarily processed all references when it adds the IProject // to the IViewableProjectsCollection. Keep an eye on reference changes, add the // project settings if/when the project becomes a unity project var projects = new JetHashSet <IProject>(); var changes = ReferencedAssembliesService.TryGetAssemblyReferenceChanges(projectModelChange, ProjectExtensions.UnityReferenceNames); foreach (var change in changes) { if (change.IsAdded) { var project = change.GetNewProject(); if (project.IsUnityProject()) { projects.Add(project); } } } foreach (var project in projects) { myChangeManager.ExecuteAfterChange(() => { Handle(project); }); } return(null); }
private void InstallPluginIfRequired(ICollection <IProject> projects) { if (projects.Count == 0) { return; } if (myPluginInstallations.Contains(mySolution.SolutionFilePath)) { return; } if (!myBoundSettingsStore.GetValue((UnitySettings s) => s.InstallUnity3DRiderPlugin)) { return; } // forcing fresh install due to being unable to provide proper setting until InputField is patched in Rider // ReSharper disable once ArgumentsStyleNamedExpression var installationInfo = myDetector.GetInstallationInfo(myCurrentVersion, previousInstallationDir: FileSystemPath.Empty); if (!installationInfo.ShouldInstallPlugin) { myLogger.Info("Plugin should not be installed."); if (installationInfo.ExistingFiles.Count > 0) { myLogger.Info("Already existing plugin files:\n{0}", string.Join("\n", installationInfo.ExistingFiles)); } return; } myQueue.Enqueue(() => { Install(installationInfo); myPluginInstallations.Add(mySolution.SolutionFilePath); }); }
public void Merge(IPsiSourceFile sourceFile, object builtPart) { myShellLocks.AssertWriteAccessAllowed(); // remove old annotations from all tries foreach (var node in mySourceFileToNodes[sourceFile]) { node.Clear(sourceFile); } mySourceFileToNodes.RemoveKey(sourceFile); myFilesWithoutAnnotations.Remove(sourceFile); // add built annotations. var part = (AttributedTypesTrieCollection)builtPart; if (!myRoot.Merge(part, mySourceFileToNodes)) { myFilesWithoutAnnotations.Add(sourceFile); } myDirtyFiles.Remove(sourceFile); }
object IChangeProvider.Execute(IChangeMap changeMap) { var projectModelChange = changeMap.GetChange <ProjectModelChange>(mySolution); if (projectModelChange == null) { return(null); } var changes = ReferencedAssembliesService.TryGetAssemblyReferenceChanges(projectModelChange, ProjectExtensions.UnityReferenceNames, myLogger); var newUnityProjects = new JetHashSet <IProject>(); foreach (var change in changes) { if (change.IsAdded) { var project = change.GetNewProject(); if (project.IsUnityProject()) { newUnityProjects.Add(project); } } } myChangeManager.ExecuteAfterChange(() => { foreach (var project in newUnityProjects) { OnUnityProjectAdded(project); } }); return(null); }
private JetHashSet<VariableDisposeStatus> GetPreviousElemsThisStatusSet( IEnumerable<ControlFlowElementData> previousElems) { var result = new JetHashSet<VariableDisposeStatus>(); foreach (var previousElementData in previousElems) { if (previousElementData == null || !previousElementData.IsVisited()) result.Add(VariableDisposeStatus.Unknown); else { if (previousElementData.ThisStatus == null) return null; result.Add(previousElementData.ThisStatus.Value); } } return result; }
private void CreateProtocols(FileSystemPath protocolInstancePath) { if (!protocolInstancePath.ExistsFile) { return; } List <ProtocolInstance> protocolInstanceList; try { protocolInstanceList = ProtocolInstance.FromJson(protocolInstancePath.ReadAllText2().Text); } catch (Exception e) { myLogger.Warn($"Unable to parse {protocolInstancePath}" + Environment.NewLine + e); return; } var protocolInstance = protocolInstanceList?.SingleOrDefault(a => a.SolutionName == mySolution.SolutionFilePath.NameWithoutExtension); if (protocolInstance == null) { return; } myLogger.Info($"EditorPlugin protocol port {protocolInstance.Port} for Solution: {protocolInstance.SolutionName}."); try { var lifetime = mySessionLifetimes.Next(); myLogger.Info("Create protocol..."); myLogger.Info("Creating SocketWire with port = {0}", protocolInstance.Port); var wire = new SocketWire.Client(lifetime, myDispatcher, protocolInstance.Port, "UnityClient"); var protocol = new Protocol("UnityEditorPlugin", new Serializers(), new Identities(IdKind.Client), myDispatcher, wire, lifetime); protocol.ThrowErrorOnOutOfSyncModels = false; protocol.OutOfSyncModels.AdviseOnce(lifetime, e => { if (myPluginInstallations.Contains(mySolution.SolutionFilePath)) { return; } myPluginInstallations.Add(mySolution.SolutionFilePath); // avoid displaying Notification multiple times on each AppDomain.Reload in Unity var appVersion = myUnityVersion.GetActualVersionForSolution(); if (appVersion < new Version(2019, 2)) { var entry = myBoundSettingsStore.Schema.GetScalarEntry((UnitySettings s) => s.InstallUnity3DRiderPlugin); var isEnabled = myBoundSettingsStore.GetValueProperty <bool>(lifetime, entry, null).Value; if (!isEnabled) { myHost.PerformModelAction(model => model.OnEditorModelOutOfSync()); } } else { var notification = new NotificationModel("Advanced Unity integration is unavailable", $"Please update External Editor to {myHostProductInfo.VersionMarketingString} in Unity Preferences.", true, RdNotificationEntryType.WARN); mySolution.Locks.ExecuteOrQueue(lifetime, "OutOfSyncModels.Notify", () => myNotificationsModel.Notification(notification)); } }); wire.Connected.WhenTrue(lifetime, lf => { myLogger.Info("WireConnected."); var editor = new EditorPluginModel(lf, protocol); editor.IsBackendConnected.Set(rdVoid => true); if (PlatformUtil.RuntimePlatform == PlatformUtil.Platform.Windows) { var frontendProcess = Process.GetCurrentProcess().GetParent(); // RiderProcessId is not used on non-Windows, but this line gives bad warning in the log if (frontendProcess != null) { editor.RiderProcessId.SetValue(frontendProcess.Id); } } myHost.PerformModelAction(m => m.SessionInitialized.Value = true); SubscribeToLogs(lf, editor); SubscribeToOpenFile(editor); editor.Play.Advise(lf, b => myHost.PerformModelAction(rd => rd.Play.SetValue(b))); editor.Pause.Advise(lf, b => myHost.PerformModelAction(rd => rd.Pause.SetValue(b))); editor.ClearOnPlay.Advise(lf, time => myHost.PerformModelAction(rd => rd.ClearOnPlay(time))); editor.UnityProcessId.View(lf, (_, pid) => myHost.PerformModelAction(t => t.UnityProcessId.Set(pid))); // I have split this into groups, because want to use async api for finding reference and pass them via groups to Unity myHost.PerformModelAction(t => t.ShowFileInUnity.Advise(lf, v => editor.ShowFileInUnity.Fire(v))); myHost.PerformModelAction(t => t.ShowPreferences.Advise(lf, v => { editor.ShowPreferences.Fire(); })); editor.EditorLogPath.Advise(lifetime, s => myHost.PerformModelAction(a => a.EditorLogPath.SetValue(s))); editor.PlayerLogPath.Advise(lifetime, s => myHost.PerformModelAction(a => a.PlayerLogPath.SetValue(s))); // Note that these are late-init properties. Once set, they are always set and do not allow nulls. // This means that if/when the Unity <-> Backend protocol closes, they still retain the last value // they had - so the front end will retain the log and application paths of the just-closed editor. // Opening a new editor instance will reconnect and push a new value through to the front end editor.UnityApplicationData.Advise(lifetime, s => myHost.PerformModelAction(a => { var version = UnityVersion.Parse(s.ApplicationVersion); a.UnityApplicationData.SetValue(new UnityApplicationData(s.ApplicationPath, s.ApplicationContentsPath, s.ApplicationVersion, UnityVersion.RequiresRiderPackage(version))); })); editor.ScriptCompilationDuringPlay.Advise(lifetime, s => myHost.PerformModelAction(a => a.ScriptCompilationDuringPlay.Set(ConvertToScriptCompilationEnum(s)))); myHost.PerformModelAction(rd => { rd.GenerateUIElementsSchema.Set((l, u) => editor.GenerateUIElementsSchema.Start(l, u).ToRdTask(l)); }); TrackActivity(editor, lf); if (!myComponentLifetime.IsTerminated) { myLocks.ExecuteOrQueueEx(myComponentLifetime, "setModel", () => { UnityModel.SetValue(editor); }); } lf.AddAction(() => { if (!myComponentLifetime.IsTerminated) { myLocks.ExecuteOrQueueEx(myComponentLifetime, "clearModel", () => { myLogger.Info("Wire disconnected."); myHost.PerformModelAction(m => m.SessionInitialized.Value = false); UnityModel.SetValue(null); }); } }); }); } catch (Exception ex) { myLogger.Error(ex); } }
private static void ReportClosureAllocations( [NotNull] ITreeNode topDeclaration, [CanBeNull] IFunction thisElement, [CanBeNull] ILocalScope topScope, [NotNull] ClosureInspector inspector, [NotNull] IHighlightingConsumer consumer) { var scopesMap = new Dictionary <IDeclaredElement, ILocalScope>(); var captureScopes = new Dictionary <ILocalScope, JetHashSet <IDeclaredElement> >(); // group captures by their scope, report non-cached delegates foreach (var closure in inspector.Closures) { foreach (var capture in closure.Value) { ILocalScope scope = null; if (capture is IFunction) { scope = topScope; // 'this' capture } else { var declarations = capture.GetDeclarations(); if (declarations.Count == 0) // accessors 'value' parameter { var accessor = thisElement as IAccessor; if (accessor != null && Equals(accessor.ValueVariable, capture)) { scope = topScope; } } else { foreach (var declaration in declarations) { if (declaration is IRegularParameterDeclaration) { scope = topScope; } else { scope = declaration.GetContainingNode <ILocalScope>(); } break; } } } if (scope == null) { continue; } JetHashSet <IDeclaredElement> captures; if (!captureScopes.TryGetValue(scope, out captures)) { captureScopes[scope] = captures = new JetHashSet <IDeclaredElement>(); } captures.Add(capture); scopesMap[capture] = scope; } { var highlightingRange = GetClosureRange(closure.Key); if (highlightingRange.IsValid()) { if (IsExpressionLambda(closure.Key)) { consumer.AddHighlighting( new ObjectAllocationHighlighting(closure.Key, "expression tree construction"), highlightingRange); } else { consumer.AddHighlighting( new DelegateAllocationHighlighting(closure.Key, "capture of " + FormatClosureDescription(closure.Value)), highlightingRange); } } } } // highlight first captured entity per every scope foreach (var scopeToCaptures in captureScopes) { var firstOffset = TreeOffset.MaxValue; IDeclaredElement firstCapture = null; foreach (var capture in scopeToCaptures.Value) { if (capture is IFunction) { continue; } var offset = GetCaptureStartOffset(capture); if (offset < firstOffset) { firstOffset = offset; firstCapture = capture; } } var scopeClosure = FormatClosureDescription(scopeToCaptures.Value); // collect outer captures JetHashSet <IDeclaredElement> outerCaptures = null; foreach (var closureToCaptures in inspector.Closures) { if (!scopeToCaptures.Key.Contains(closureToCaptures.Key)) { continue; } foreach (var capture in closureToCaptures.Value) { ILocalScope scope; if (!scopesMap.TryGetValue(capture, out scope)) { continue; } if (scopeToCaptures.Key.Contains(scope)) { continue; } outerCaptures = outerCaptures ?? new JetHashSet <IDeclaredElement>(); outerCaptures.Add(capture); } } if (outerCaptures != null) { scopeClosure += string.Format(" + (outer closure of {0})", FormatClosureDescription(outerCaptures)); } if (firstCapture != null) { DocumentRange highlightingRange; var anchor = GetCaptureHighlightingRange( topDeclaration, thisElement, firstCapture, out highlightingRange); if (anchor != null && highlightingRange.IsValid()) { consumer.AddHighlighting( new ClosureAllocationHighlighting(anchor, scopeClosure), highlightingRange); } } } }
private ISearchDomain NarrowSearchDomain(ISolution solution, IEnumerable<string> words, IEnumerable<string> extendedWords, ISearchDomain domain) { List<string> allWords = words.ToList(); List<string> allExtendedWords = extendedWords.ToList(); if (domain.IsEmpty || allWords.IsEmpty()) return domain; IWordIndex wordIndex = solution.GetPsiServices().CacheManager.WordIndex; var jetHashSet1 = new JetHashSet<IPsiSourceFile>(wordIndex.GetFilesContainingWord(allWords.First()), null); foreach (string word in allWords.Skip(1)) jetHashSet1.IntersectWith(wordIndex.GetFilesContainingWord(word)); if (allExtendedWords.Any()) { var jetHashSet2 = new JetHashSet<IPsiSourceFile>(null); using (JetHashSet<IPsiSourceFile>.ElementEnumerator enumerator = jetHashSet1.GetEnumerator()) { while (enumerator.MoveNext()) { IPsiSourceFile file = enumerator.Current; if (allExtendedWords.Any(word => wordIndex.CanContainWord(file, word))) jetHashSet2.Add(file); } } jetHashSet1 = jetHashSet2; } return domain.Intersect(searchDomainFactory.CreateSearchDomain(jetHashSet1)); }
public IEnumerable <string> GetAllPossibleWordsInFile(IDeclaredElement element) { var names = new JetHashSet <string>(); var constructor = element as IConstructor; if (constructor != null) { ITypeElement typeElement = constructor.GetContainingType(); if (typeElement != null) { names.Add(typeElement.ShortName); } names.Add(DeclaredElementConstants.CONSTRUCTOR_NAME); return(names); } names.Add(element.ShortName); if (PsiDeclaredElementUtil.IsCollectionInitializerAddMethod(element)) { names.Add("new"); } if (PsiDeclaredElementUtil.IsForeachEnumeratorPatternMember(element)) { names.Add("foreach"); } if (DeclaredElementUtil.IsAsyncAwaitablePatternMember(element)) { names.Add("async"); names.Add("await"); } // LINQ var method = element as IMethod; if (method != null) { if (method.ShortName == "Cast" && method.TypeParameters.Count == 1 && IsCorrectParametersNumberForQueryPatternMethod(method, 0)) { names.Add("from"); } if (method.ShortName == "Select" && IsCorrectParametersNumberForQueryPatternMethod(method, 1)) { names.Add("from"); } if (method.ShortName == "SelectMany" && IsCorrectParametersNumberForQueryPatternMethod(method, 2)) { names.Add("from"); } if (method.ShortName == "Where" && IsCorrectParametersNumberForQueryPatternMethod(method, 1)) { names.Add("where"); } if ((method.ShortName == "Join" || method.ShortName == "GroupJoin") && IsCorrectParametersNumberForQueryPatternMethod(method, 4)) { names.Add("join"); } if ((method.ShortName == "OrderBy" || method.ShortName == "OrderByDescending" || method.ShortName == "ThenBy" || method.ShortName == "ThenByDescending") && IsCorrectParametersNumberForQueryPatternMethod(method, 1)) { names.Add("orderby"); } if (method.ShortName == "GroupBy" && (IsCorrectParametersNumberForQueryPatternMethod(method, 1) || IsCorrectParametersNumberForQueryPatternMethod(method, 2))) { names.Add("group"); } } return(names); }
public IEnumerable<string> GetAllPossibleWordsInFile(IDeclaredElement element) { var names = new JetHashSet<string>(); var constructor = element as IConstructor; if (constructor != null) { ITypeElement typeElement = constructor.GetContainingType(); if (typeElement != null) { names.Add(typeElement.ShortName); } names.Add(DeclaredElementConstants.CONSTRUCTOR_NAME); return names; } names.Add(element.ShortName); if (PsiDeclaredElementUtil.IsCollectionInitializerAddMethod(element)) { names.Add("new"); } if (PsiDeclaredElementUtil.IsForeachEnumeratorPatternMember(element)) { names.Add("foreach"); } if (DeclaredElementUtil.IsAsyncAwaitablePatternMember(element)) { names.Add("async"); names.Add("await"); } // LINQ var method = element as IMethod; if (method != null) { if (method.ShortName == "Cast" && method.TypeParameters.Count == 1 && IsCorrectParametersNumberForQueryPatternMethod(method, 0)) { names.Add("from"); } if (method.ShortName == "Select" && IsCorrectParametersNumberForQueryPatternMethod(method, 1)) { names.Add("from"); } if (method.ShortName == "SelectMany" && IsCorrectParametersNumberForQueryPatternMethod(method, 2)) { names.Add("from"); } if (method.ShortName == "Where" && IsCorrectParametersNumberForQueryPatternMethod(method, 1)) { names.Add("where"); } if ((method.ShortName == "Join" || method.ShortName == "GroupJoin") && IsCorrectParametersNumberForQueryPatternMethod(method, 4)) { names.Add("join"); } if ((method.ShortName == "OrderBy" || method.ShortName == "OrderByDescending" || method.ShortName == "ThenBy" || method.ShortName == "ThenByDescending") && IsCorrectParametersNumberForQueryPatternMethod(method, 1)) { names.Add("orderby"); } if (method.ShortName == "GroupBy" && (IsCorrectParametersNumberForQueryPatternMethod(method, 1) || IsCorrectParametersNumberForQueryPatternMethod(method, 2))) { names.Add("group"); } } return names; }
public void SelectElement(string name) { myInputElements.Add(name); }
public void MarkAsDirty(IPsiSourceFile sourceFile) { lock (_lockObject) _dirtyFiles.Add(sourceFile); }
protected override bool AddLookupItems(CSharpCodeCompletionContext context, GroupedItemsCollector collector) { var settingsStore = context.BasicContext.File.GetSettingsStore(); if (!settingsStore.GetValue(PostfixSettingsAccessor.ShowPostfixItems)) { return(false); } var executionContext = new ReparsedPostfixExecutionContext(myLifetime, context.BasicContext, context.UnterminatedContext, "__"); var postfixContext = myTemplatesManager.IsAvailable(context.UnterminatedContext.TreeNode, executionContext); if (postfixContext == null) // try unterminated context if terminated sucks { executionContext = new ReparsedPostfixExecutionContext(myLifetime, context.BasicContext, context.TerminatedContext, "__;"); postfixContext = myTemplatesManager.IsAvailable(context.TerminatedContext.TreeNode, executionContext); } if (postfixContext == null) { return(false); } // nothing to check :( if (postfixContext.Expressions.Count == 0 && postfixContext.TypeExpression == null) { return(false); } var lookupItems = myTemplatesManager.CollectItems(postfixContext); if (lookupItems.Count == 0) { return(false); } ICollection <string> toRemove = EmptyList <string> .InstanceList; // double completion support var parameters = context.BasicContext.Parameters; var isDoubleCompletion = (parameters.CodeCompletionTypes.Length > 1); if (!executionContext.IsAutoCompletion && isDoubleCompletion) { var firstCompletion = parameters.CodeCompletionTypes[0]; if (firstCompletion != CodeCompletionType.AutomaticCompletion) { return(false); } // run postfix templates like we are in auto completion executionContext.IsAutoCompletion = true; var automaticPostfixItems = myTemplatesManager.CollectItems(postfixContext); if (automaticPostfixItems.Count > 0) { toRemove = new JetHashSet <string>(StringComparer.Ordinal); foreach (var lookupItem in automaticPostfixItems) { toRemove.Add(lookupItem.Identity); } } } foreach (var lookupItem in lookupItems) { if (toRemove.Contains(lookupItem.Identity)) { continue; } if (isDoubleCompletion) { collector.AddToTop(lookupItem); } else { collector.AddSomewhere(lookupItem); } } return(lookupItems.Count > 0); }
private void InstallPluginIfRequired(Lifetime lifetime, [NotNull] IProject project) { if (!myBoundSettingsStore.GetValue((UnityPluginSettings s) => s.InstallUnity3DRiderPlugin)) { return; } if (myPluginInstallations.Contains(project.ProjectFileLocation)) { return; } var installationInfo = myDetector.GetInstallationInfo(project); if (!installationInfo.ShouldInstallPlugin) { return; } var currentVersion = typeof(UnityPluginInstaller).Assembly.GetName().Version; if (currentVersion <= installationInfo.Version) { return; } var isFreshInstall = installationInfo.Version == new Version(); if (isFreshInstall) { myLogger.LogMessage(LoggingLevel.INFO, "Fresh install"); } lock (mySyncObj) { if (myPluginInstallations.Contains(project.ProjectFileLocation)) { return; } FileSystemPath installedPath; if (!TryInstall(installationInfo, out installedPath)) { myLogger.LogMessage(LoggingLevel.WARN, "Plugin was not installed"); } else { string userTitle; string userMessage; if (isFreshInstall) { userTitle = "Unity: plugin installed"; userMessage = $@"Rider plugin v{currentVersion} for the Unity Editor was automatically installed for the project '{mySolution.Name}' This allows better integration between the Unity Editor and Rider IDE. The plugin file can be found on the following path: {installedPath.MakeRelativeTo(mySolution.SolutionFilePath)}"; } else { userTitle = "Unity: plugin updated"; userMessage = $"Rider plugin was succesfully upgraded from version {installationInfo.Version} to {currentVersion}"; } myLogger.LogMessage(LoggingLevel.INFO, userTitle); var notification = new RdNotificationEntry(userTitle, userMessage, true, RdNotificationEntryType.INFO); myNotifications.Notification.Fire(notification); } myPluginInstallations.Add(project.ProjectFileLocation); } }