Exemplo n.º 1
0
        /// <summary>Generates a C# file from a T4 file.</summary>
        /// <param name="modificationInfo">The modifications that occurred in the T4 file.</param>
        public override ISecondaryDocumentGenerationResult Generate(PrimaryFileModificationInfo modificationInfo)
        {
            if (!(modificationInfo.NewPsiFile is IT4File t4File))
            {
                return(null);
            }

            var generator           = new T4CSharpCodeGenerator(t4File, _directiveInfoManager);
            GenerationResult result = generator.Generate();

            LanguageService csharpLanguageService = CSharpLanguage.Instance.LanguageService();

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

            var includedFiles = new OneToSetMap <FileSystemPath, FileSystemPath>();

            includedFiles.AddRange(modificationInfo.SourceFile.GetLocation(), t4File.GetNonEmptyIncludePaths());

            ISolution solution = modificationInfo.SourceFile.GetSolution();
            var       t4FileDependencyManager = solution.GetComponent <T4FileDependencyManager>();

            return(new T4SecondaryDocumentGenerationResult(
                       modificationInfo.SourceFile,
                       result.Builder.ToString(),
                       csharpLanguageService.LanguageType,
                       new RangeTranslatorWithGeneratedRangeMap(result.GeneratedRangeMap),
                       csharpLanguageService.GetPrimaryLexerFactory(),
                       t4FileDependencyManager,
                       t4File.GetNonEmptyIncludePaths()
                       ));
        }
Exemplo n.º 2
0
		/// <summary>
		/// Generates a C# file from a T4 file.
		/// </summary>
		/// <param name="modificationInfo">The modifications that occurred in the T4 file.</param>
		public override ISecondaryDocumentGenerationResult Generate(PrimaryFileModificationInfo modificationInfo) {
			var t4File = modificationInfo.NewPsiFile as IT4File;
			if (t4File == null)
				return null;
			 
			var generator = new T4CSharpCodeGenerator(t4File, _directiveInfoManager);
			GenerationResult result = generator.Generate();

			LanguageService csharpLanguageService = CSharpLanguage.Instance.LanguageService();
			if (csharpLanguageService == null)
				return null;

			var includedFiles = new OneToSetMap<FileSystemPath, FileSystemPath>();
			includedFiles.AddRange(modificationInfo.SourceFile.GetLocation(), t4File.GetNonEmptyIncludePaths());

			ISolution solution = modificationInfo.SourceFile.GetSolution();
			var t4FileDependencyManager = solution.GetComponent<T4FileDependencyManager>();

			return new T4SecondaryDocumentGenerationResult(
				modificationInfo.SourceFile,
				result.Builder.ToString(),
				csharpLanguageService.LanguageType,
				new RangeTranslatorWithGeneratedRangeMap(result.GeneratedRangeMap),
				csharpLanguageService.GetPrimaryLexerFactory(),
				t4FileDependencyManager,
				t4File.GetNonEmptyIncludePaths());
		}
Exemplo n.º 3
0
 private UnitySceneData(OneToListMap <MonoBehaviourProperty, MonoBehaviourPropertyValue> propertiesData, OneToSetMap <string, FileID> eventHandlers, OneToSetMap <string, string> scriptMapping, SceneHierarchy sceneHierarchy)
 {
     PropertiesData          = propertiesData;
     SceneHierarchy          = sceneHierarchy;
     ShortNameToScriptFileId = eventHandlers;
     ScriptMapping           = scriptMapping;
 }
Exemplo n.º 4
0
        public AnnotationsLoader(SimpleExtensionManager extensionManager)
        {
            this.extensionManager = extensionManager;

            var location = FileSystemPath.CreateByCanonicalPath(Assembly.GetExecutingAssembly().Location)
                           .Directory.Combine("ExternalAnnotations");

            myAnnotations = new OneToSetMap <string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);

            // Cache the annotation filenames to save scanning the directory multiple times.
            // Safe to cache as the user shouldn't be changing files in the install dir. If
            // they want to add extra annotations, use an extension.
            // The rules are simple: either the file is named after the assembly, or the folder
            // is (or both, but that doesn't matter)
            foreach (var file in location.GetChildFiles("*.xml"))
            {
                myAnnotations.Add(file.NameWithoutExtension, file);
            }
            foreach (var directory in location.GetChildDirectories())
            {
                foreach (var file in directory.GetChildFiles("*.xml", PathSearchFlags.RecurseIntoSubdirectories))
                {
                    myAnnotations.Add(file.NameWithoutExtension, file);
                    myAnnotations.Add(file.Directory.Name, file);
                }
            }
        }
        private IList<MethodArgumentStatus> CalculateArgumentStatuses()
        {
            var argumentStatuses = new List<MethodArgumentStatus>();
            var allInvokedExpressions = new OneToSetMap<IVariableDeclaration, InvokedExpressionData>();
            var allStatuses = new OneToSetMap<IVariableDeclaration, VariableDisposeStatus>();
            DoForEachExit(data =>
            {
                data.InvokedExpressions.ForEach(kvp => allInvokedExpressions.AddRange(kvp.Key, kvp.Value));
                data.Status.ForEach(kvp => allStatuses.Add(kvp.Key, kvp.Value));
            });
            var generalStatuses = new Dictionary<IVariableDeclaration, VariableDisposeStatus>();
            allStatuses.ForEach(kvp => generalStatuses[kvp.Key] = GetGeneralStatus(kvp.Value));
            if (_disposableArguments == null)
                return null;
            _disposableArguments.ForEach(
                kvp => argumentStatuses.Add(new MethodArgumentStatus(kvp.Value, generalStatuses[kvp.Key],
                    allInvokedExpressions[kvp.Key].OrderBy(im => im.Offset).ToList(), _psiSourceFile)));

            if (_processThis)
            {
                var allThisInvokedExpressions = new HashSet<InvokedExpressionData>();
                var allThisStatuses = new HashSet<VariableDisposeStatus>();
                DoForEachExit(data =>
                {
                    allThisInvokedExpressions.UnionWith(data.ThisInvokedExpressions);
                    if (data.ThisStatus.HasValue)
                        allThisStatuses.Add(data.ThisStatus.Value);
                });
                argumentStatuses.Add(new MethodArgumentStatus(0, GetGeneralStatus(allThisStatuses),
                    allThisInvokedExpressions.OrderBy(im => im.Offset).ToList(), _psiSourceFile));
            }

            return argumentStatuses.OrderBy(mas => mas.Number).ToList();
        }
        public XunitTestClassElement GetOrCreateTestClass(string id, IProject project,
                                                          IClrTypeName typeName,
                                                          string assemblyLocation,
                                                          OneToSetMap <string, string> traits)
        {
            lock (lockObject)
            {
                var elementId = services.CreateId(project, id);
                var element   = GetElementById <XunitTestClassElement>(elementId);
                if (element == null)
                {
                    element = new XunitTestClassElement(services, elementId, typeName.GetPersistent(), assemblyLocation);
                    CacheElement(elementId, element);
                }

                element.State = UnitTestElementState.Valid;
                // Assembly location might have changed if someone e.g. switches from debug to release
                element.AssemblyLocation = assemblyLocation;

                services.ElementManager.RemoveElements(element.Children.Where(c => c.State == UnitTestElementState.Invalid).ToSet());

                UpdateCategories(element, traits);

                return(element);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Collects the handlers that implement installation against the assembly attributes, see <see cref="InstallAttributesAttribute"/>.
        /// Do not call, use <see cref="MapAttributeToInstallers"/>.
        /// </summary>
        protected void CollectAttributeInstallers()
        {
            // Init only once
            if (myMapAttributeToInstallers != null)
            {
                return;
            }
            myMapAttributeToInstallers = new OneToSetMap <Type, IInstallAttributes>();

            // Cache the installer objects to singleton them in case they handle multiple attrs
            myMapInstallerTypeToInstance = new Dictionary <Type, IInstallAttributes>();

            foreach (Assembly assembly in Assemblies)            // All the assemblies
            {
                try
                {
                    foreach (Type typeInstaller in assembly.GetTypes())                    // All the types
                    {
                        // Does the current type declare it installs any attrs?
                        object[] attributes = typeInstaller.GetCustomAttributes(typeof(InstallAttributesAttribute), false);
                        if (attributes.Length == 0)
                        {
                            continue;
                        }

                        // Create the installer instance, if not created yet
                        IInstallAttributes installer;
                        if (!myMapInstallerTypeToInstance.TryGetValue(typeInstaller, out installer))
                        {
                            object objectInstaller = Activator.CreateInstance(typeInstaller);
                            installer = objectInstaller as IInstallAttributes;
                            if (installer == null)
                            {
                                throw new InvalidOperationException(string.Format("The attribute-installer object of type “{0}” does not implement the required “{1}” interface.", typeInstaller.FullName, typeof(IInstallAttributes).FullName));
                            }
                            myMapInstallerTypeToInstance.Add(typeInstaller, installer);
                        }

                        // Add attributes
                        foreach (InstallAttributesAttribute attribute in attributes)
                        {
                            if (attribute.AttributeToInstall != null)                            // A single-time installer
                            {
                                // Duplicate?
                                if ((myMapAttributeToInstallers.ContainsKey(attribute.AttributeToInstall)) && (myMapAttributeToInstallers[attribute.AttributeToInstall].Contains(installer)))
                                {
                                    throw new InvalidOperationException(string.Format("The installer class “{0}” registers for the “{1}” attribute twice.", typeInstaller.FullName, attribute.AttributeToInstall.FullName));
                                }
                                myMapAttributeToInstallers.Add(attribute.AttributeToInstall, installer);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException(string.Format("Failed to collect attribute-installers from the “{0}” assembly. {1}", assembly.FullName, ex.Message), ex);
                }
            }
        }
Exemplo n.º 8
0
 public T4SecondaryDocumentGenerationResult([NotNull] IPsiSourceFile sourceFile, [NotNull] string text, [NotNull] PsiLanguageType language,
                                            [NotNull] ISecondaryRangeTranslator secondaryRangeTranslator, [NotNull] ILexerFactory lexerFactory,
                                            [NotNull] FileDependency fileDependency, [NotNull] OneToSetMap <FileSystemPath, FileSystemPath> includedFiles)
     : base(sourceFile, text, language, secondaryRangeTranslator, lexerFactory)
 {
     _fileDependency = fileDependency;
     _includedFiles  = includedFiles;
 }
        public XunitTestClassElement GetOrCreateTestClass(IProject project, IClrTypeName typeName,
                                                          string assemblyLocation,
                                                          OneToSetMap <string, string> traits)
        {
            var id = typeName.FullName;

            return(GetOrCreateTestClass(id, project, typeName, assemblyLocation, traits));
        }
 public SerializedPropertyChildrenRenderer(IUnityOptions unityOptions)
 {
     myUnityOptions         = unityOptions;
     myPerTypeFieldNames    = GetPerTypeFieldNames();
     myHandledPropertyTypes = myPerTypeFieldNames.Keys.ToSet();
     myHandledPropertyTypes.Add(SerializedPropertyKind.Generic); // Special handling
     myKnownFieldNames = myPerTypeFieldNames.Values.ToSet();
 }
 // ReSharper disable once UnusedParameter.Local
 public T4SecondaryDocumentGenerationResult([NotNull] IPsiSourceFile sourceFile, [NotNull] string text, [NotNull] PsiLanguageType language,
     [NotNull] ISecondaryRangeTranslator secondaryRangeTranslator, [NotNull] ILexerFactory lexerFactory,
     [NotNull] FileDependency fileDependency, [NotNull] OneToSetMap<FileSystemPath, FileSystemPath> includedFiles)
     : base(text, language, secondaryRangeTranslator, lexerFactory)
 {
     _fileDependency = fileDependency;
     _includedFiles = includedFiles;
 }
Exemplo n.º 12
0
        public TempAnnotationsLoader()
        {
            myAnnotations = new OneToSetMap <string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);
            var annotationsPath = GetType().Assembly.GetPath().Directory / "Extensions" / "JetBrains.Unity" / "annotations";
            var annotationFiles = annotationsPath.GetChildFiles();

            foreach (var annotationFile in annotationFiles)
            {
                myAnnotations.Add(annotationFile.NameWithoutExtension, annotationFile);
            }
        }
Exemplo n.º 13
0
 private void UpdateIndex(AttributedTypesTrieNode node, OneToSetMap <IPsiSourceFile, AttributedTypesTrieNode> sourceFileToNodes)
 {
     foreach (var annotationData in node.Annotations)
     {
         sourceFileToNodes.Add(annotationData.SourceFile, node);
     }
     foreach (var childNode in node.Children.Values)
     {
         UpdateIndex(childNode, sourceFileToNodes);
     }
 }
Exemplo n.º 14
0
        public bool Merge(AttributedTypesTrieCollection part, OneToSetMap <IPsiSourceFile, AttributedTypesTrieNode> sourceFileToNodes)
        {
            bool ret = false;

            foreach (var pair in part.Roots)
            {
                var node = EnsureNode(pair.Key);
                ret = node.Merge(pair.Value, sourceFileToNodes) || ret;
            }
            return(ret);
        }
Exemplo n.º 15
0
        private IEnumerable <UnitTestElementCategory> GetCategories(OneToSetMap <string, string> traits)
        {
            var categories = from key in traits.Keys
                             where !key.IsNullOrEmpty() && !key.IsWhitespace()
                             from value in traits[key]
                             where !value.IsNullOrEmpty() && !value.IsWhitespace()
                             select string.Compare(key, "category", StringComparison.InvariantCultureIgnoreCase) != 0
                                 ? string.Format("{0}[{1}]", key.Trim(), value.Trim())
                                 : value;

            return(services.CategoryFactory.Create(categories));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ReferencedAnalyzersCache"/> class.
        /// </summary>
        /// <param name="lifetime">The lifetime of the component</param>
        /// <param name="solution">The current solution</param>
        /// <param name="threading">The threading API</param>
        /// <param name="solutionLoadTasksScheduler">Solution load task scheduler</param>
        /// <param name="projectModelSynchronizer">The project model synchronizer</param>
        /// <param name="packageInstallerServices">NuGet installer services API</param>
        /// <param name="packageInstallerEvents">NuGet installer events API</param>
        public ReferencedAnalyzersCache(
            Lifetime lifetime,
            ISolution solution,
            IThreading threading,
            ISolutionLoadTasksScheduler solutionLoadTasksScheduler,
            ProjectModelSynchronizer projectModelSynchronizer,
            Lazy <Optional <IVsPackageInstallerServices> > packageInstallerServices,
            Lazy <Optional <IVsPackageInstallerEvents> > packageInstallerEvents)
        {
            this.solution  = solution;
            this.threading = threading;
            this.projectModelSynchronizer = projectModelSynchronizer;
            this.packageInstallerEvents   = packageInstallerEvents.Value.CanBeNull;
            this.packageInstallerServices = packageInstallerServices.Value.CanBeNull;

            this.syncObject = new object();

            this.referencedAnalyzers = new OneToSetMap <string, string>();

            this.groupingEvent = threading.GroupingEvents.CreateEvent(
                lifetime,
                "StyleCop::AnalyzersCache",
                TimeSpan.FromSeconds(2),
                Rgc.Guarded,
                this.DoResetAnalyzersCache);

            if (!this.IsNuGetAvailable)
            {
                Logger.LogMessage(
                    LoggingLevel.VERBOSE,
                    "[StyleCop::AnalyzersCache] Unable to get NuGet interfaces. No exception thrown");
            }
            else
            {
                lifetime.AddBracket(
                    () =>
                {
                    this.packageInstallerEvents.PackageInstalled   += this.ResetAnalyzersCache;
                    this.packageInstallerEvents.PackageUninstalled += this.ResetAnalyzersCache;
                },
                    () =>
                {
                    this.packageInstallerEvents.PackageInstalled   -= this.ResetAnalyzersCache;
                    this.packageInstallerEvents.PackageUninstalled -= this.ResetAnalyzersCache;
                });
                solutionLoadTasksScheduler.EnqueueTask(new SolutionLoadTask("StyleCop.ReferencedAnalyzersCache", SolutionLoadTaskKinds.AfterDone,
                                                                            () =>
                {
                    this.ResetAnalyzersCache(null);
                }));
            }
        }
Exemplo n.º 17
0
        private static OneToSetMap<string, string> GetTraitsFromAttributes(IEnumerable<IAttributeInfo> attributes)
        {
            var traits = new OneToSetMap<string, string>();
            foreach (var attributeInfo in attributes)
            {
                var name = attributeInfo.GetPropertyValue<string>("Name");
                var value = attributeInfo.GetPropertyValue<string>("Value");
                if (name != null && value != null)
                    traits.Add(name, value);
            }

            return traits;
        }
Exemplo n.º 18
0
        public AnnotationsLoader()
        {
            myAnnotations = new OneToSetMap <string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);
            var testDataPathBase = TestUtil.GetTestDataPathBase(GetType().Assembly);
            var annotationsPath  = testDataPathBase.Parent.Parent / "src" / "resharper-unity" / "annotations";

            Assertion.Assert(annotationsPath.ExistsDirectory, $"Cannot find annotations: {annotationsPath}");
            var annotationFiles = annotationsPath.GetChildFiles();

            foreach (var annotationFile in annotationFiles)
            {
                myAnnotations.Add(annotationFile.NameWithoutExtension, annotationFile);
            }
        }
Exemplo n.º 19
0
        private static void FillTargetAndMethod(IBuffer buffer, OneToSetMap <string, FileID> eventHandlerToScriptTarget)
        {
            var lexer = new YamlLexer(buffer, false, false);

            lexer.Start();


            TokenNodeType currentToken;

            FileID currentTarget = null;
            string currentMethod = null;

            while ((currentToken = lexer.TokenType) != null)
            {
                if (currentToken == YamlTokenType.NS_PLAIN_ONE_LINE_IN)
                {
                    var text = buffer.GetText(new TextRange(lexer.TokenStart, lexer.TokenEnd));
                    lexer.Advance();
                    SkipWhitespace(lexer);
                    currentToken = lexer.TokenType;
                    if (currentToken == YamlTokenType.COLON)
                    {
                        if (text.Equals("m_Target"))
                        {
                            if (currentMethod != null && currentTarget != null)
                            {
                                eventHandlerToScriptTarget.Add(currentMethod, currentTarget);
                            }

                            lexer.Advance();
                            currentTarget = GetFileId(buffer, lexer);
                        }
                        else if (text.Equals("m_MethodName"))
                        {
                            Assertion.Assert(currentTarget != null, "currentTarget != null");
                            lexer.Advance();
                            currentMethod = GetPrimitiveValue(buffer, lexer);
                        }
                    }
                }
                lexer.Advance();
            }

            if (currentMethod != null && currentTarget != null)
            {
                eventHandlerToScriptTarget.Add(currentMethod, currentTarget);
            }
        }
Exemplo n.º 20
0
        private static OneToSetMap <string, string> GetTraitsFromAttributes(IEnumerable <IAttributeInfo> attributes)
        {
            var traits = new OneToSetMap <string, string>();

            foreach (var attributeInfo in attributes)
            {
                var name  = attributeInfo.GetPropertyValue <string>("Name");
                var value = attributeInfo.GetPropertyValue <string>("Value");
                if (name != null && value != null)
                {
                    traits.Add(name, value);
                }
            }

            return(traits);
        }
        public ExternalAnnotationsProvider()
        {
            var location = TestDataPath2;
            annotations = new OneToSetMap<string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);

            foreach (var file in location.GetChildFiles("*.xml"))
                annotations.Add(file.NameWithoutExtension, file);
            foreach (var directory in location.GetChildDirectories())
            {
                foreach (var file in directory.GetChildFiles("*.xml", PathSearchFlags.RecurseIntoSubdirectories))
                {
                    annotations.Add(file.NameWithoutExtension, file);
                    annotations.Add(file.Directory.Name, file);
                }
            }
        }
Exemplo n.º 22
0
        public XunitTestMethodElement GetOrCreateTestMethod(IProject project,
                                                            XunitTestClassElement testClassElement,
                                                            IClrTypeName typeName, string methodName, string skipReason,
                                                            OneToSetMap <string, string> traits, bool isDynamic)
        {
            var baseTypeName = string.Empty;

            if (!testClassElement.TypeName.Equals(typeName))
            {
                baseTypeName = typeName.ShortName + ".";
            }

            var id = string.Format("{0}.{1}{2}", testClassElement.Id.Id, baseTypeName, methodName);

            return(GetOrCreateTestMethod(id, project, testClassElement, typeName, methodName, skipReason, traits,
                                         isDynamic));
        }
        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);
                }
            }
        }
 // Применяем результат к data и заодно проверяем были ли изменения
 private static void Apply(ControlFlowElementData data, ref bool changesAre,
     IDictionary<IVariableDeclaration, VariableDisposeStatus> resultStatusDictionary,
     OneToSetMap<IVariableDeclaration, InvokedExpressionData> invokedExpressions)
 {
     foreach (var resultStatus in resultStatusDictionary)
     {
         var status = data[resultStatus.Key];
         if (status != resultStatus.Value)
         {
             changesAre = true;
             data[resultStatus.Key] = resultStatus.Value;
         }
     }
     changesAre = changesAre || invokedExpressions.Keys.Except(data.InvokedExpressions.Keys).Any();
         // или вычисляется лениво
     data.InvokedExpressions = invokedExpressions;
 }
Exemplo n.º 25
0
        public ExternalAnnotationsProvider()
        {
            var location = TestDataPath2;

            annotations = new OneToSetMap <string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);

            foreach (var file in location.GetChildFiles("*.xml"))
            {
                annotations.Add(file.NameWithoutExtension, file);
            }
            foreach (var directory in location.GetChildDirectories())
            {
                foreach (var file in directory.GetChildFiles("*.xml", PathSearchFlags.RecurseIntoSubdirectories))
                {
                    annotations.Add(file.NameWithoutExtension, file);
                    annotations.Add(file.Directory.Name, file);
                }
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// return true when some data was added
        /// </summary>
        public bool Merge(AttributedTypesTrieNode builtPart, OneToSetMap <IPsiSourceFile, AttributedTypesTrieNode> sourceFileToNodes)
        {
            var ret = false;

            if (builtPart.myAnnotations != null && builtPart.myAnnotations.Count > 0)
            {
                ret = true;
                foreach (var data in builtPart.myAnnotations)
                {
                    sourceFileToNodes.Add(data.SourceFile, this);
                }
            }

            if (myAnnotations == null && builtPart.myAnnotations != null)
            {
                myAnnotations = builtPart.myAnnotations;
            }
            else if (myAnnotations != null && builtPart.myAnnotations != null)
            {
                myAnnotations = myAnnotations.Concat(builtPart.myAnnotations).ToList();
            }

            if (builtPart.myChildren != null)
            {
                foreach (var child in builtPart.myChildren)
                {
                    AttributedTypesTrieNode ownChild;
                    var childTrie = child.Value;
                    if (Children.TryGetValue(child.Key, out ownChild))
                    {
                        ret = ownChild.Merge(childTrie, sourceFileToNodes) || ret;
                    }
                    else
                    {
                        Children[child.Key] = childTrie;
                        ret = true;
                        UpdateIndex(childTrie, sourceFileToNodes);
                    }
                }
            }
            return(ret);
        }
Exemplo n.º 27
0
        public static UnitySceneData Build(IUnityYamlFile file)
        {
            Assertion.Assert(file.IsValid(), "file.IsValid()");
            Assertion.Assert(file.GetSolution().Locks.IsReadAccessAllowed(), "ReadLock is required");

            var interruptChecker            = new SeldomInterruptChecker();
            var unityPropertyValueCacheItem = new OneToListMap <MonoBehaviourProperty, MonoBehaviourPropertyValue>();
            var sceneHierarchy = new SceneHierarchy();

            var anchorToEventHandler       = new OneToSetMap <string, string>();
            var scriptMapping              = new OneToSetMap <string, string>();
            var eventHandlerToScriptTarget = new OneToSetMap <string, FileID>();

            foreach (var document in file.DocumentsEnumerable)
            {
                interruptChecker.CheckForInterrupt();
                var buffer = document.GetTextAsBuffer();
                if (ourPrefabModificationSearcher.Find(buffer, 0, Math.Min(buffer.Length, 100)) > 0)
                {
                    sceneHierarchy.AddPrefabModification(buffer);
                }
                else
                {
                    var simpleValues    = new Dictionary <string, string>();
                    var referenceValues = new Dictionary <string, FileID>();
                    UnitySceneDataUtil.ExtractSimpleAndReferenceValues(buffer, simpleValues, referenceValues, eventHandlerToScriptTarget);

                    FillProperties(simpleValues, referenceValues, unityPropertyValueCacheItem);
                    FillScriptMapping(simpleValues, referenceValues, scriptMapping);

                    sceneHierarchy.AddSceneHierarchyElement(simpleValues, referenceValues);
                }
            }

            if (unityPropertyValueCacheItem.Count == 0 && sceneHierarchy.Elements.Count == 0)
            {
                return(null);
            }

            return(new UnitySceneData(unityPropertyValueCacheItem, eventHandlerToScriptTarget, scriptMapping, sceneHierarchy));
        }
        public void Execute(ISolution solution, ITextControl textControl)
        {
            var jetPopupMenus = solution.GetPsiServices().GetComponent <JetPopupMenus>();
            var cache         = solution.GetComponent <SpecflowStepsDefinitionsCache>();

            jetPopupMenus.ShowModal(JetPopupMenu.ShowWhen.AutoExecuteIfSingleEnabledItem,
                                    (lifetime, menu) =>
            {
                menu.Caption.Value = WindowlessControlAutomation.Create("Where to create the step ?");

                var availableSteps  = cache.GetBindingTypes(_reference.GetElement().GetPsiModule());
                var filesPerClasses = new OneToSetMap <string, SpecflowStepsDefinitionsCache.AvailableBindingClass>();
                foreach (var availableBindingClass in availableSteps)
                {
                    filesPerClasses.Add(availableBindingClass.ClassClrName, availableBindingClass);
                }

                menu.ItemKeys.AddRange(filesPerClasses);
                menu.DescribeItem.Advise(lifetime, e =>
                {
                    var(classClrFullName, _) = (KeyValuePair <string, ISet <SpecflowStepsDefinitionsCache.AvailableBindingClass> >)e.Key;

                    e.Descriptor.Icon  = PsiSymbolsThemedIcons.Class.Id;
                    e.Descriptor.Style = MenuItemStyle.Enabled;

                    var clrTypeName           = new ClrTypeName(classClrFullName);
                    e.Descriptor.Text         = new RichText(clrTypeName.ShortName, DeclaredElementPresenterTextStyles.ParameterInfo.GetStyle(DeclaredElementPresentationPartKind.Type));
                    e.Descriptor.ShortcutText = clrTypeName.GetNamespaceName();
                });
                menu.ItemClicked.Advise(lifetime, key =>
                {
                    var(_, availableBindingClasses) = (KeyValuePair <string, ISet <SpecflowStepsDefinitionsCache.AvailableBindingClass> >)key;
                    OpenFileSelectionModal(jetPopupMenus, textControl, availableBindingClasses, _reference.GetStepKind(), _reference.GetStepText());
                });
                menu.PopupWindowContextSource = textControl.PopupWindowContextFactory.ForCaret();
            });
        }
Exemplo n.º 29
0
        public XunitTestMethodElement GetOrCreateTestMethod(string id, IProject project,
                                                            XunitTestClassElement testClassElement,
                                                            IClrTypeName typeName, string methodName,
                                                            string skipReason, OneToSetMap <string, string> traits,
                                                            bool isDynamic)
        {
            lock (lockObject)
            {
                var elementId = services.CreateId(project, id);
                var element   = GetElementById <XunitTestMethodElement>(elementId);
                if (element == null)
                {
                    element = new XunitTestMethodElement(services, elementId, typeName, methodName, skipReason, isDynamic);
                    CacheElement(elementId, element);
                }

                element.Parent = testClassElement;
                element.State  = UnitTestElementState.Valid;

                UpdateCategories(element, traits);

                return(element);
            }
        }
        public AnnotationsLoader(SimpleExtensionManager extensionManager)
        {
            this.extensionManager = extensionManager;

            var location = FileSystemPath.CreateByCanonicalPath(Assembly.GetExecutingAssembly().Location)
                .Directory.Combine("ExternalAnnotations");
            myAnnotations = new OneToSetMap<string, FileSystemPath>(StringComparer.OrdinalIgnoreCase);

            // Cache the annotation filenames to save scanning the directory multiple times.
            // Safe to cache as the user shouldn't be changing files in the install dir. If
            // they want to add extra annotations, use an extension.
            // The rules are simple: either the file is named after the assembly, or the folder
            // is (or both, but that doesn't matter)
            foreach (var file in location.GetChildFiles("*.xml"))
                myAnnotations.Add(file.NameWithoutExtension, file);
            foreach (var directory in location.GetChildDirectories())
            {
                foreach (var file in directory.GetChildFiles("*.xml", PathSearchFlags.RecurseIntoSubdirectories))
                {
                    myAnnotations.Add(file.NameWithoutExtension, file);
                    myAnnotations.Add(file.Directory.Name, file);
                }
            }
        }
Exemplo n.º 31
0
        private static void FillScriptMapping(Dictionary <string, string> simpleValues, Dictionary <string, FileID> referenceValues, OneToSetMap <string, string> scriptMapping)
        {
            var anchor = simpleValues.GetValueSafe("&anchor");

            if (referenceValues.TryGetValue(UnityYamlConstants.ScriptProperty, out var fileID))
            {
                scriptMapping.Add(anchor, fileID.guid);
            }
        }
Exemplo n.º 32
0
        public static void ExtractSimpleAndReferenceValues(IBuffer buffer, Dictionary <string, string> simpleValues, Dictionary <string, FileID> referenceValues, OneToSetMap <string, FileID> eventHandlerToScriptTarget)
        {
            // special field for accessing anchor id
            simpleValues["&anchor"] = GetAnchorFromBuffer(buffer);

            var lexer = new YamlLexer(buffer, true, false);

            lexer.Start();

            TokenNodeType currentToken;
            bool          noColon = true;

            while ((currentToken = lexer.TokenType) != null)
            {
                if (noColon)
                {
                    if (currentToken == YamlTokenType.COLON)
                    {
                        noColon = false;
                    }

                    if (currentToken == YamlTokenType.NS_PLAIN_ONE_LINE_OUT)
                    {
                        var key = buffer.GetText(new TextRange(lexer.TokenStart, lexer.TokenEnd));

                        // special filed for checking stripped documents
                        if (key.Equals("stripped"))
                        {
                            simpleValues["stripped"] = "1";
                        }
                    }
                }

                if (currentToken == YamlTokenType.INDENT)
                {
                    lexer.Advance();
                    currentToken = lexer.TokenType;
                    if (currentToken == YamlTokenType.NS_PLAIN_ONE_LINE_IN)
                    {
                        var key = buffer.GetText(new TextRange(lexer.TokenStart, lexer.TokenEnd));

                        lexer.Advance();
                        SkipWhitespace(lexer);

                        currentToken = lexer.TokenType;
                        if (currentToken == YamlTokenType.COLON)
                        {
                            lexer.Advance();
                            SkipWhitespace(lexer);

                            currentToken = lexer.TokenType;
                            if (currentToken == YamlTokenType.LBRACE)
                            {
                                lexer.Advance();
                                var result = GetFileIdInner(buffer, lexer);
                                if (result != null)
                                {
                                    referenceValues[key] = result;
                                }
                            }
                            else if (YamlTokenType.CHAMELEON_BLOCK_MAPPING_ENTRY_CONTENT_WITH_ANY_INDENT.Equals(currentToken))
                            {
                                var chameleonBuffer = ProjectedBuffer.Create(buffer, new TextRange(lexer.TokenStart, lexer.TokenEnd));
                                if (ourStringSearcher.Find(chameleonBuffer, 0, Math.Min(chameleonBuffer.Length, 150)) > 0)
                                {
                                    FillTargetAndMethod(chameleonBuffer, eventHandlerToScriptTarget);
                                }
                                else
                                {
                                    // sometimes, FileId is multiline
                                    var result = GetFileId(chameleonBuffer);
                                    if (result != null)
                                    {
                                        referenceValues[key] = result;
                                    }
                                }
                            }
                            else
                            {
                                var result = GetPrimitiveValue(buffer, lexer);
                                if (result != null)
                                {
                                    simpleValues[key] = result;
                                }
                            }
                        }
                    }
                    else
                    {
                        FindNextIndent(lexer);
                    }
                }
                else
                {
                    lexer.Advance();
                }
            }
        }
        public void Execute(IDataContext context, DelegateExecute nextExecute)
        {
            var solution = context.GetData(ProjectModelDataConstants.SOLUTION);

            if (solution == null)
            {
                return;
            }

            var wordsPerAssembly = new OneToSetMap <string, string>(valueComparer: StringComparer.InvariantCultureIgnoreCase);
            var abbreviations    = new JetHashSet <string>();

            // TODO: This should be in a background task
            var psiModules  = solution.GetComponent <IPsiModules>();
            var symbolCache = solution.GetComponent <ISymbolCache>();

            foreach (var assemblyPsiModule in psiModules.GetAssemblyModules().OrderBy(m => m.DisplayName))
            {
                if (!ShouldProcessAssembly(assemblyPsiModule))
                {
                    continue;
                }

                var symbolScope  = symbolCache.GetSymbolScope(assemblyPsiModule, false, true);
                var typeElements = symbolScope.GetAllTypeElementsGroupedByName();
                foreach (var typeElement in typeElements)
                {
                    if (!typeElement.CanBeVisibleToSolution())
                    {
                        continue;
                    }

                    AddWords(wordsPerAssembly, abbreviations, assemblyPsiModule, typeElement.ShortName);

                    foreach (var namespaceName in typeElement.GetClrName().NamespaceNames)
                    {
                        AddWords(wordsPerAssembly, abbreviations, assemblyPsiModule, namespaceName);
                    }

                    // TODO: Should we skip enum values?
                    // It's unlikely that a user would name a method or variable after a value such as AdvertisingNetwork.Aarki,
                    // but on the other hand, if it's used in a comment, it'll show up as a typo.

                    foreach (var typeMember in typeElement.GetMembers())
                    {
                        if (!ShouldProcessTypeMember(typeMember))
                        {
                            continue;
                        }

                        if (typeElement is IEnum)
                        {
                            // Don't use any enum values as abbreviations. Avoids false positives with ALL_UPPER_CASE style
                            AddWords(wordsPerAssembly, new JetHashSet <string>(), assemblyPsiModule,
                                     typeMember.ShortName);
                        }
                        else
                        {
                            AddWords(wordsPerAssembly, abbreviations, assemblyPsiModule, typeMember.ShortName);
                        }

                        // TODO: Include parameter names?
                        // Respeller will not check parameter names of overriding or implementing functions, so this is
                        // probably unnecessary
                    }
                }
            }

            // Case insensitive. There will not be duplicates
            var allWords = (from pair in wordsPerAssembly
                            from word in pair.Value
                            select word).ToJetHashSet(StringComparer.InvariantCultureIgnoreCase);

            var spellService = solution.GetComponent <ISpellService>();

            var unknownWords = (from word in allWords
                                where !spellService.CheckWordSpelling(word)
                                select word).ToJetHashSet(StringComparer.InvariantCultureIgnoreCase);

            // Add abbreviations separately. If added to the dictionary, we don't get typo warnings, but we can get
            // naming standard inspection warnings. E.g. BlahBlahAABB is converted to BlahBlahAabb. Don't add anything
            // that's already known, but the spell checker will only check for words of 4 characters or more.
            // TODO: Ideally, we should disable AbbreviationsSettingsProvider. But just merge results in for now
            var unknownAbbreviations = (from word in abbreviations
                                        where (word.Length > 1 && word.Length < 4) || !spellService.CheckWordSpelling(word)
                                        select word).ToJetHashSet();

            // Remove the non-abbreviations
            unknownAbbreviations.Remove("TEXTMESHPRO");
            unknownAbbreviations.Remove("GRAIDENT");

            // Remove known typos or exclusions. Yes, this is all done by hand
            RemoveTyposAndExclusions(unknownWords);

            // Dump all words for diagnostics
            Dumper.DumpToNotepad(w =>
            {
                w.WriteLine("All words");
                w.WriteLine();

                foreach (var(assembly, words) in wordsPerAssembly)
                {
                    w.WriteLine("Words for assembly: " + assembly);
                    w.WriteLine();

                    foreach (var word in words.OrderBy(IdentityFunc <string> .Instance))
                    {
                        w.WriteLine(word.ToLowerInvariant());
                    }
                    w.WriteLine();
                }
            });

            // Dump all abbreviations, so we can avoid naming standards inspections when an abbreviation is used.
            // E.g. BlahBlahAABB is accepted instead of converted to BlahBlahAabb
            Dumper.DumpToNotepad(w =>
            {
                w.WriteLine("Abbreviations");
                w.WriteLine();

                foreach (var abbreviation in unknownAbbreviations.OrderBy(IdentityFunc <string> .Instance))
                {
                    w.WriteLine(abbreviation.ToUpperInvariant());
                }
            });

            // Dump all unknown words, minus abbreviations, for use as a dictionary
            Dumper.DumpToNotepad(w =>
            {
                var dictionary = new JetHashSet <string>(unknownWords, StringComparer.InvariantCultureIgnoreCase);
                dictionary.ExceptWith(abbreviations);

                w.WriteLine("Dictionary (unknown words minus abbreviations)");
                w.WriteLine();
                w.WriteLine(dictionary.Count);    // Hunspell dictionaries start with the number of words

                foreach (var word in dictionary.OrderBy(IdentityFunc <string> .Instance))
                {
                    w.WriteLine(word.ToLowerInvariant());
                }
            });
        }
 // Обновляет список вызванных методов для переменных со статусом DependsOnInvocation.
 // Удаляет список вызванных методов для переменных, лишившихся этого статуса.
 private OneToSetMap<IVariableDeclaration, InvokedExpressionData> GetInvokedExpressions(ICollection<ControlFlowElementData> previousElems,
         IDictionary<IVariableDeclaration, VariableDisposeStatus> statusDictionary,
         OneToSetMap<IVariableDeclaration, InvokedExpressionData> invokedExpressions)
 {
     var result = new OneToSetMap<IVariableDeclaration, InvokedExpressionData>(invokedExpressions);
     foreach (var status in statusDictionary)
     {
         if (status.Value != VariableDisposeStatus.DependsOnInvocation)
         {
             if (invokedExpressions.ContainsKey(status.Key))
                 result.RemoveKey(status.Key);
             continue;
         }
         foreach (var previousElem in previousElems)
         {
             if (previousElem == null || !previousElem.IsVisited())
                 continue;
             var previousStatus = previousElem[status.Key];
             if (previousStatus == null)
                 continue;
             if (previousStatus != VariableDisposeStatus.DependsOnInvocation)
                 continue;
             if (previousElem.InvokedExpressions.ContainsKey(status.Key))
                 result.AddRange(status.Key, previousElem.InvokedExpressions[status.Key]);
         }
     }
     return result;
 }
Exemplo n.º 35
0
 private void UpdateCategories(XunitBaseElement element, OneToSetMap <string, string> traits)
 {
     UpdateCategories(element, GetCategories(traits));
 }
Exemplo n.º 36
0
        public void Execute(IDataContext context, DelegateExecute nextExecute)
        {
            var solution = context.GetData(ProjectModelDataConstants.SOLUTION);

            if (solution == null)
            {
                return;
            }

            var symbolCache = solution.GetComponent <ISymbolCache>();

            var types       = new OneToSetMap <string, string>();
            var symbolScope = symbolCache.GetSymbolScope(LibrarySymbolScope.FULL, true);

            foreach (var typeElement in symbolScope.GetAllTypeElementsGroupedByName().OfType <ITypeMember>())
            {
                // Non-nested, public or protected types. Essentially what would appear in completion
                if (typeElement.GetContainingType() == null && IsVisible(typeElement))
                {
                    var typeParametersOwner = (ITypeParametersOwner)typeElement;
                    var shortName           = typeElement.ShortName + (typeParametersOwner.TypeParameters.Count > 0
                                        ? $"`{typeParametersOwner.TypeParameters.Count}"
                                        : string.Empty);
                    types.Add(shortName, ((ITypeElement)typeElement).GetClrName().FullName);
                }
            }

            Dumper.DumpToNotepad(writer =>
            {
                var toDump = (from pair in types
                              where pair.Value.Count > 1 && pair.Value.Any(x => !x.StartsWith("System"))
                              let skipped = IsSkipped(pair)
                                            select new { pair, skipped }).OrderBy(x => x.pair.Key).ToList();

                writer.WriteLine($"Found {toDump.Count} items. Skipping {toDump.Count(x => x.skipped)}");
                writer.WriteLine();

                foreach (var(key, value) in toDump.Where(x => !x.skipped).Select(x => x.pair))
                {
                    writer.WriteLine("Short name: " + key);
                    foreach (var fullName in value)
                    {
                        writer.WriteLine($"  {fullName}");
                    }
                    writer.WriteLine();
                }

                writer.WriteLine();
                writer.WriteLine();
                writer.WriteLine();
                writer.WriteLine("Skipping:");
                writer.WriteLine();

                foreach (var(key, value) in toDump.Where(x => x.skipped).Select(x => x.pair))
                {
                    writer.WriteLine("Short name: " + key);
                    foreach (var fullName in value)
                    {
                        writer.WriteLine($"  {fullName}");
                    }
                    writer.WriteLine();
                }
            });
        }
        public override void Rename(IRenameRefactoring executer, IProgressIndicator pi, bool hasConflictsWithDeclarations, IRefactoringDriver driver)
        {
            BuildDeclarations();

            //Logger.Assert(myDeclarations.Count > 0, "myDeclarations.Count > 0");

            IDeclaredElement declaredElement = myOriginalElementPointer.FindDeclaredElement();

            if (declaredElement == null)
            {
                return;
            }

            IPsiServices psiServices = declaredElement.GetPsiServices();

            IList <IReference> primaryReferences = executer.Workflow.GetElementReferences(PrimaryDeclaredElement);
            List <Pair <IDeclaredElement, IList <IReference> > > secondaryElementWithReferences = SecondaryDeclaredElements.Select(x => Pair.Of(x, executer.Workflow.GetElementReferences(x))).ToList();

            pi.Start(myDeclarations.Count + primaryReferences.Count);

            foreach (IDeclaration declaration in myDeclarations)
            {
                InterruptableActivityCookie.CheckAndThrow(pi);
                declaration.SetName(myNewName);
                pi.Advance();
            }

            psiServices.Caches.Update();

            IDeclaredElement newDeclaredElement;

            if (myDeclarations.Count > 0)
            {
                newDeclaredElement = myDeclarations[0].DeclaredElement;
            }
            else
            {
                if (myElement is RoleDeclaredElement)
                {
                    newDeclaredElement = myElement;
                    ((RoleDeclaredElement)myElement).ChangeName = true;
                    ((RoleDeclaredElement)myElement).NewName    = NewName;
                    ((RoleDeclaredElement)newDeclaredElement).SetName(NewName);
                }
                else
                {
                    newDeclaredElement = null;
                }
            }
            Assertion.Assert(newDeclaredElement != null, "The condition (newDeclaredElement != null) is false.");

            myNewElementPointer = newDeclaredElement.CreateElementPointer();
            Assertion.Assert(newDeclaredElement.IsValid(), "myNewDeclaredElement.IsValid()");


            myNewReferences.Clear();
            OneToSetMap <PsiLanguageType, IReference> references = LanguageUtil.SortReferences(primaryReferences.Where(x => x.IsValid()));
            IList <IReference> referencesToRename = new List <IReference>();

            foreach (var pair in references)
            {
                List <IReference> sortedReferences = pair.Value.ToList();//LanguageUtil.GetSortedReferences(pair.Value);
                foreach (IReference reference in sortedReferences)
                {
                    IReference oldReferenceForConflict = reference;
                    InterruptableActivityCookie.CheckAndThrow(pi);
                    if (reference.IsValid()) // reference may invalidate during additional reference processing
                    {
                        RenameHelperBase        rename     = executer.Workflow.LanguageSpecific[reference.GetTreeNode().Language];
                        IReference              reference1 = rename.TransformProjectedInitializer(reference);
                        DeclaredElementInstance subst      = GetSubst(newDeclaredElement, executer);
                        IReference              newReference;
                        if (subst != null)
                        {
                            if (subst.Substitution.Domain.IsEmpty())
                            {
                                newReference = reference1.BindTo(subst.Element);
                            }
                            else
                            {
                                newReference = reference1.BindTo(subst.Element, subst.Substitution);
                            }
                        }
                        else
                        {
                            newReference = reference1.BindTo(newDeclaredElement);
                        }
                        if (!(newReference is IImplicitReference))
                        {
                            IDeclaredElement element = newReference.Resolve().DeclaredElement;
                            if (!hasConflictsWithDeclarations && !myDoNotShowBindingConflicts && (element == null || !element.Equals(newDeclaredElement)) && !rename.IsAlias(newDeclaredElement))
                            {
                                driver.AddLateConflict(() => new Conflict(newReference.GetTreeNode().GetSolution(), "Usage {0} can not be updated correctly.", ConflictSeverity.Error, oldReferenceForConflict), "not bound");
                            }
                            referencesToRename.Add(newReference);
                        }
                        myNewReferences.Insert(0, newReference);
                        rename.AdditionalReferenceProcessing(newDeclaredElement, newReference, myNewReferences);
                    }

                    pi.Advance();
                }
            }

            foreach (var pair in secondaryElementWithReferences)
            {
                IDeclaredElement   element             = pair.First;
                IList <IReference> secondaryReferences = pair.Second;
                foreach (IReference reference in secondaryReferences)
                {
                    InterruptableActivityCookie.CheckAndThrow(pi);
                    if (reference.IsValid())
                    {
                        reference.BindTo(element);
                    }
                }
            }

            if (myElement is RoleDeclaredElement)
            {
                ((RoleDeclaredElement)myElement).ChangeName = false;
                ((RoleDeclaredElement)myElement).SetName(NewName);
                foreach (IReference reference in referencesToRename)
                {
                    ((PsiRoleReference)reference).SetName(NewName);
                    reference.CurrentResolveResult = null;
                    ((PsiFile)((RoleDeclaredElement)myElement).File).ClearTables();
                }
            }
        }