示例#1
0
        private void HandleInclude(
            [CanBeNull] string includeFileName,
            [NotNull] T4DirectiveAttribute fileAttr,
            [NotNull] CompositeElement parentElement,
            bool once
            )
        {
            FileSystemPath includePath = ResolveInclude(includeFileName);

            if (includePath.IsEmpty)
            {
                fileAttr.ValueError = String.Format(CultureInfo.InvariantCulture, "Unresolved file \"{0}\"", includePath);
                return;
            }

            if (!_existingIncludePaths.Add(includePath))
            {
                if (!once)
                {
                    fileAttr.ValueError = String.Format(CultureInfo.InvariantCulture, "Already included file \"{0}\"", includePath);
                }
                return;
            }

            FileSystemPath sourceLocation = _sourceFile.GetLocation();

            if (includePath == sourceLocation)
            {
                fileAttr.ValueError = "Recursive include";
                _existingIncludePaths.Add(includePath);
                return;
            }

            if (!includePath.ExistsFile)
            {
                fileAttr.ValueError = String.Format(CultureInfo.InvariantCulture, "File \"{0}\" not found", includePath);
                return;
            }

            // find the matching include in the existing solution source files
            // or create a new one if the include file is outside the solution
            IPsiSourceFile includeSourceFile = includePath.FindSourceFileInSolution(_solution) ?? CreateIncludeSourceFile(includePath);

            if (includeSourceFile == null)
            {
                fileAttr.ValueError = "No current solution";
                return;
            }

            ILexer    includeLexer = CreateLexer(includeSourceFile);
            var       builder      = new T4TreeBuilder(_t4Environment, _directiveInfoManager, includeLexer, includeSourceFile, _existingIncludePaths, _solution, _macroResolveModule);
            T4Include include      = builder.CreateIncludeT4Tree();

            include.Path = includePath;
            _includes.Add(include);

            // do not use AppendNewChild, we don't want the PsiBuilderLexer to move line breaks from the include into the main file.
            parentElement.AddChild(include);
        }
示例#2
0
        // ReSharper doesn't want us to use project files. See UnityExternalFilesModuleProcessor
        public static bool IsMeta(this IPsiSourceFile sourceFile)
        {
#if RESHARPER
            return(sourceFile is UnityYamlAssetPsiSourceFile || sourceFile.GetLocation().IsMeta());
#else
            return(sourceFile is UnityYamlExternalPsiSourceFile || sourceFile.GetLocation().IsMeta());
#endif
        }
示例#3
0
        public override void Merge(IPsiSourceFile sourceFile, object builtPart)
        {
            var oldIncludes = FindIndirectIncludesTransitiveClosure(sourceFile.GetLocation());

            base.Merge(sourceFile, builtPart);
            var newIncludes = FindIndirectIncludesTransitiveClosure(sourceFile.GetLocation());

            OnFilesIndirectlyAffected?.Invoke(oldIncludes.Concat(newIncludes));
        }
示例#4
0
 public XXLanguageXXFile(FileStatistics statistics, IPsiSourceFile psiSourceFile, XXLanguageXXProject project)
     : base(null)// TODO: add statistics
 {
     _psiSourceFile = psiSourceFile;
     _fullName      = psiSourceFile.GetLocation().FullPath;
     _project       = project;
 }
        public void RestoreHierarchy(AssetDocumentHierarchyElementContainer hierarchyElementContainer, IPsiSourceFile sourceFile)
        {
            if (myIsRestored)
            {
                return;
            }

            lock (myLockObject)
            {
                if (myIsRestored)
                {
                    return;
                }

                myIsRestored = true;

                AssetDocumentHierarchyElementContainer = hierarchyElementContainer;
                IsScene = sourceFile.GetLocation().ExtensionWithDot.Equals(UnityYamlConstants.Scene);


                var offset = 0;
                // concating arrays to one by index. see GetElementByInternalIndex too
                PrepareElements(myOtherBoxedElements, offset);
                offset += myOtherBoxedElements.Count;

                PrepareElements(myTransformElements, offset);
                offset += myTransformElements.Count;

                PrepareElements(myGameObjectHierarchies, offset);
                offset += myGameObjectHierarchies.Count;

                PrepareElements(myComponentElements, offset);
                offset += myComponentElements.Count;

                PrepareElements(myScriptComponentElements, offset);
                offset += myScriptComponentElements.Count;

                foreach (var prefabInstanceHierarchy in GetPrefabInstanceHierarchies())
                {
                    var correspondingSourceObjects = new HashSet <ExternalReference>();
                    foreach (var modification in prefabInstanceHierarchy.PrefabModifications)
                    {
                        var target = modification.Target;
                        if (!(target is ExternalReference externalReference))
                        {
                            continue;
                        }
                        correspondingSourceObjects.Add(externalReference);
                    }

                    foreach (var correspondingSourceObject in correspondingSourceObjects)
                    {
                        var fakeAnchor = PrefabsUtil.GetImportedDocumentAnchor(prefabInstanceHierarchy.Location.LocalDocumentAnchor, correspondingSourceObject.LocalDocumentAnchor);
                        myOtherFakeStrippedElements.Add(new StrippedHierarchyElement(
                                                            new LocalReference(sourceFile.PsiStorage.PersistentIndex, fakeAnchor),
                                                            prefabInstanceHierarchy.Location, correspondingSourceObject));
                    }
                }
            }
        }
        private static IconId GetIcon(IPsiSourceFile sourceFile)
        {
            var location = sourceFile.GetLocation();

            if (location.IsAsset())
            {
                return(UnityFileTypeThemedIcons.FileUnityAsset.Id);
            }
            if (location.IsScene())
            {
                return(UnityFileTypeThemedIcons.FileUnity.Id);
            }
            if (location.IsPrefab())
            {
                return(UnityFileTypeThemedIcons.FileUnityPrefab.Id);
            }
            if (location.IsMeta())
            {
                return(UnityFileTypeThemedIcons.FileUnityMeta.Id);
            }
            if (location.IsControllerFile())
            {
                return(UnityFileTypeThemedIcons.FileAnimatorController.Id);
            }
            return(location.IsAnimFile()
                ? UnityFileTypeThemedIcons.FileAnimationClip.Id
                : UnityFileTypeThemedIcons.FileUnity.Id);
        }
示例#7
0
文件: File.cs 项目: derigel23/Nitra
 public XXLanguageXXFile(FileStatistics statistics, IPsiSourceFile psiSourceFile, XXLanguageXXProject project)
   : base(null)// TODO: add statistics
 {
   _psiSourceFile = psiSourceFile;
   _fullName      = psiSourceFile.GetLocation().FullPath;
   _project       = project;
 }
示例#8
0
 private void RemoveFromLocalCache(IPsiSourceFile sourceFile)
 {
     if (Map.TryGetValue(sourceFile, out var cacheItem))
     {
         var assetLocation = GetAssetLocationFromMetaFile(sourceFile.GetLocation());
         myAssetGuidToAssetFilePaths.RemoveValue(cacheItem.Guid, assetLocation);
         myAssetFilePathToGuid.Remove(assetLocation);
     }
 }
        public void Merge(IPsiSourceFile sourceFile, AssetDocumentHierarchyElement hierarchyElement, IUnityAssetDataElement unityAssetDataElement)
        {
            var element = unityAssetDataElement as AssetDocumentHierarchyElement;

            element.AssetDocumentHierarchyElementContainer = this;
            element.IsScene = sourceFile.GetLocation().ExtensionWithDot.Equals(UnityYamlConstants.Scene);
            myAssetDocumentsHierarchy[sourceFile] = element;
            element.RestoreHierarchy();

            myPrefabImportCache.Add(sourceFile, element);
        }
示例#10
0
        public static FSharpFileKind GetFSharpFileKind([CanBeNull] this IPsiSourceFile sourceFile)
        {
            var fileExtension = sourceFile?.GetLocation().ExtensionNoDot;

            if (fileExtension == "fsi" || fileExtension == "mli")
            {
                return(FSharpFileKind.SigFile);
            }

            return(FSharpFileKind.ImplFile);
        }
        public override void CommitChanges()
        {
            base.CommitChanges();

            FileSystemPath location = _sourceFile.GetLocation();

            if (!location.IsEmpty)
            {
                _t4FileDependencyManager.UpdateIncludes(location, _includedFiles);
                _t4FileDependencyManager.TryGetCurrentInvalidator()?.AddCommittedFilePath(location);
            }
        }
示例#12
0
        public static FSharpFileKind GetFSharpFileKind([NotNull] this IPsiSourceFile sourceFile)
        {
            var fileExtension = sourceFile.GetLocation().ExtensionNoDot;

            if (fileExtension == "fs" || fileExtension == "ml")
            {
                return(FSharpFileKind.ImplFile);
            }
            if (fileExtension == "fsi" || fileExtension == "mli")
            {
                return(FSharpFileKind.SigFile);
            }
            throw new ArgumentOutOfRangeException();
        }
        public void SetContext(IPsiSourceFile psiSourceFile, CppFileLocation?root)
        {
            using (ReadLockCookie.Create())
            {
                if (root.HasValue)
                {
                    Assertion.Assert(root.Value.RootRange.IsValid, "root.RootRange.IsValid()");
                    var range = myManager.CreateRangeMarker(new DocumentRange(root.Value.GetDocument(mySolution),
                                                                              root.Value.RootRange));
                    myShaderContext.AddToCache(psiSourceFile.GetLocation(), range);
                }
                else
                {
                    myShaderContext.RemoveFromCache(psiSourceFile.GetLocation());
                }
            }

            var solution = psiSourceFile.GetSolution();
            var psiFiles = solution.GetPsiServices().Files;

            psiFiles.InvalidatePsiFilesCache(psiSourceFile);
            solution.GetComponent <IDaemon>().Invalidate();
        }
示例#14
0
        private void AddToLocalCache(IPsiSourceFile metaFile, [CanBeNull] MetaFileCacheItem cacheItem)
        {
            if (cacheItem == null)
            {
                return;
            }

            var metaFileLocation = metaFile.GetLocation();

            if (!metaFileLocation.IsEmpty)
            {
                var assetLocation = GetAssetLocationFromMetaFile(metaFileLocation);
                myAssetGuidToAssetFilePaths.AddValue(cacheItem.Guid, assetLocation);
                myAssetFilePathToGuid.Add(assetLocation, cacheItem.Guid);
            }
        }
        public virtual IReference[] GetReferences(ITreeNode element, IReference[] oldReferences)
        {
            if (ResolveUtil.CheckThatAllReferencesBelongToElement <IRazorReference>(oldReferences, element))
            {
                return(oldReferences);
            }
            if (!IsAppropriateNode(element))
            {
                return(EmptyArray <IReference> .Instance);
            }

            IExpression annotatedSectionExpression = razorServices.GetAnnotatedLiteralExpression(element, RazorSectionExternalAttributeName, assignmentChecker);

            if (annotatedSectionExpression is TLiteralExpression && annotatedSectionExpression.ConstantValue.IsString())
            {
                return(new IReference[]
                {
                    new RazorSectionDeclarationReference <TLiteralExpression>(annotatedSectionExpression)
                });
            }

            IExpression annotatedLiteralExpression = razorServices.GetAnnotatedLiteralExpression(element, RazorLayoutExternalAttributeName, assignmentChecker);

            if (annotatedLiteralExpression == null || !annotatedLiteralExpression.ConstantValue.IsString())
            {
                return(EmptyArray <IReference> .Instance);
            }

            IPsiSourceFile sourceFile = element.GetDocumentRange()
                                        .Document.IfNotNull(_ => _.GetPsiSourceFiles(solution),
                                                            EmptyList <IPsiSourceFile> .InstanceList)
                                        .Concat(element.GetSourceFile())
                                        .WhereNotNull()
                                        .FirstOrDefault();

            FileSystemPath location      = sourceFile.GetLocation();
            PathQualifier  pathQualifier = (!location.IsEmpty) ? new PathQualifier(solution, location.Directory) : null;

            return(new IReference[]
            {
                new NancyRazorLayoutReference <ITreeNode>(annotatedLiteralExpression, pathQualifier,
                                                          annotatedLiteralExpression,
                                                          TreeTextRange.FromLength(annotatedLiteralExpression.GetTextLength()),
                                                          sourceFile.IfNotNull(_ => _.LanguageType), true, true)
            });
        }
        private static AssetFindUsagesResultBase CreateRequest(FileSystemPath solutionDirPath, AssetHierarchyProcessor assetDocumentHierarchy,
                                                               LocalReference location, IPsiSourceFile sourceFile, bool needExpand = false)
        {
            if (!GetPathFromAssetFolder(solutionDirPath, sourceFile, out var pathFromAsset, out var fileName, out var extension))
            {
                return(null);
            }

            if (sourceFile.GetLocation().ExtensionWithDot.EndsWith(UnityYamlFileExtensions.AssetFileExtensionWithDot))
            {
                return(new AssetFindUsagesResult(needExpand, pathFromAsset, fileName, extension));
            }

            var consumer = new UnityScenePathGameObjectConsumer();

            assetDocumentHierarchy.ProcessSceneHierarchyFromComponentToRoot(location, consumer, true, true);

            return(new HierarchyFindUsagesResult(consumer.NameParts.ToArray(), consumer.RootIndexes.ToArray(), needExpand, pathFromAsset, fileName, extension));
        }
示例#17
0
        /// <returns>
        /// whether an includer was added in a cache entry for some include
        /// </returns>
        private bool UpdateIncluders(
            [NotNull] IDictionary <IPsiSourceFile, T4ReversedFileDependencyData> map,
            [NotNull] IPsiSourceFile includer,
            [NotNull, ItemNotNull] IEnumerable <IPsiSourceFile> allNewIncludes,
            [NotNull, ItemNotNull] IEnumerable <IPsiSourceFile> removedIncludes
            )
        {
            var includerLocation = includer.GetLocation();

            foreach (var removedInclude in removedIncludes.WhereNotNull())
            {
                var existingData = map.TryGetValue(removedInclude);
                existingData?.Includers.Remove(includerLocation);
                if (existingData?.Includers.Count == 0)
                {
                    map.Remove(removedInclude);
                }
            }

            bool handChange = false;

            foreach (var addedInclude in allNewIncludes.WhereNotNull())
            {
                var existingData = map.TryGetValue(addedInclude);
                if (existingData == null)
                {
                    handChange = true;
                    var includers = new List <FileSystemPath> {
                        includerLocation
                    };
                    map[addedInclude] = new T4ReversedFileDependencyData(includers);
                }
                else if (!existingData.Includers.Contains(includerLocation))
                {
                    handChange = true;
                    existingData.Includers.Add(includerLocation);
                }
            }

            return(handChange);
        }
示例#18
0
        private bool GetPathFromAssetFolder([NotNull] IPsiSourceFile file, out string filePath, out string fileName, out string extension)
        {
            extension = null;
            filePath  = null;
            fileName  = null;
            var path        = file.GetLocation().MakeRelativeTo(mySolutionDirectoryPath);
            var assetFolder = path.Components.FirstOrEmpty;

            if (!assetFolder.Equals(UnityYamlConstants.AssetsFolder))
            {
                return(false);
            }

            var pathComponents = path.Components;

            extension = path.ExtensionWithDot;
            fileName  = path.NameWithoutExtension;
            filePath  = String.Join("/", pathComponents);

            return(true);
        }
        public static string GetUnityPathFor([NotNull] IPsiSourceFile psiSourceFile)
        {
            var solution     = psiSourceFile.GetSolution();
            var solutionPath = solution.SolutionFilePath;
            var psiPath      = psiSourceFile.GetLocation();
            var components   = psiPath.MakeRelativeTo(solutionPath).Components.ToArray();

            var sb = new StringBuilder();

            // skip "../Assets/

            for (int i = 2; i < components.Length - 1; i++)
            {
                sb.Append(components[i]);
                sb.Append('/');
            }

            sb.Append(psiPath.NameWithoutExtension);

            return(sb.ToString());
        }
        private static AssetFindUsagesResultBase CreateRequest(FileSystemPath solutionDirPath,
                                                               AssetHierarchyProcessor assetDocumentHierarchy,
                                                               [NotNull]
                                                               AnimatorScriptUsagesElementContainer animatorContainer,
                                                               LocalReference location, IPsiSourceFile sourceFile,
                                                               [NotNull] IDeclaredElement declaredElement,
                                                               bool needExpand = false)
        {
            if (!GetPathFromAssetFolder(solutionDirPath, sourceFile, out var pathFromAsset, out var fileName, out var extension))
            {
                return(null);
            }

            var path = sourceFile.GetLocation();

            if (path.IsControllerFile() &&
                animatorContainer.GetElementsNames(location, declaredElement, out var names, out var isStateMachine) &&
                names != null)
            {
                return(new AnimatorFindUsagesResult(names,
                                                    isStateMachine ? AnimatorUsageType.StateMachine : AnimatorUsageType.State, needExpand,
                                                    pathFromAsset, fileName, extension));
            }
            if (path.ExtensionWithDot.EndsWith(UnityYamlFileExtensions.AssetFileExtensionWithDot))
            {
                return(new AssetFindUsagesResult(needExpand, pathFromAsset, fileName, extension));
            }

            if (path.IsAnimFile())
            {
                return(new AnimationFindUsagesResult(needExpand, pathFromAsset, fileName, extension));
            }

            var consumer = new UnityScenePathGameObjectConsumer();

            assetDocumentHierarchy.ProcessSceneHierarchyFromComponentToRoot(location, consumer, true, true);

            return(new HierarchyFindUsagesResult(consumer.NameParts.ToArray(), consumer.RootIndexes.ToArray(), needExpand, pathFromAsset, fileName, extension));
        }
示例#21
0
        public override void Drop(IPsiSourceFile sourceFile)
        {
            // Calculate them here, because following actions
            // will disturb the graph and change the dependencies
            var includePaths         = Map.TryGetValue(sourceFile);
            var indirectDependencies = FindIndirectIncludesTransitiveClosure(sourceFile);

            // First of all, this file itself should be removed from Map and ReversedMap
            base.Drop(sourceFile);
            ReversedMap.Remove(sourceFile);

            // Then, all its includes should no longer view this file as an includer.
            // This deletion might be a genuine deletion of the file from the file system,
            // and nonexistent files obviously don't include anything.
            // If this drop was caused by moving the file between PSI modules,
            // it will be re-added into lists of includers by the Merge method.
            var location = sourceFile.GetLocation();
            var includes = includePaths?.Includes
                           .Select(includePath => PsiFileSelector.FindMostSuitableFile(includePath, sourceFile))
                           .WhereNotNull() ?? EmptyList <IPsiSourceFile> .InstanceList;

            foreach (var include in includes)
            {
                ReversedMap.TryGetValue(include)?.Includers.Remove(location);
            }

            // Finally, we trigger indirect include invalidation.
            // Deletion can happen either when the file is genuinely deleted,
            // or when it is transferred between PSI modules
            // (e.g. a file that used to be preprocessed becomes executable).
            // In either case, we need to update its indirect dependencies.
            // However, that cannot be done in Merge,
            // because Merge happens on the new PSI file.
            // That's why we update dependencies here.
            var data = new T4FileInvalidationData(indirectDependencies.Except(sourceFile), sourceFile);

            OnFilesIndirectlyAffected.Fire(data);
        }
示例#22
0
        private static IconId GetIcon(IPsiSourceFile sourceFile)
        {
            var location = sourceFile.GetLocation();

            if (location.IsAsset())
            {
                return(UnityFileTypeThemedIcons.FileUnityAsset.Id);
            }
            if (location.IsScene())
            {
                return(UnityFileTypeThemedIcons.FileUnity.Id);
            }
            if (location.IsPrefab())
            {
                return(UnityFileTypeThemedIcons.FileUnityPrefab.Id);
            }
            if (location.IsMeta())
            {
                return(UnityFileTypeThemedIcons.FileUnityMeta.Id);
            }

            return(UnityFileTypeThemedIcons.FileUnity.Id);
        }
示例#23
0
 public static bool IsMeta(this IPsiSourceFile sourceFile)
 {
     return(sourceFile is UnityYamlExternalPsiSourceFile || sourceFile.GetLocation().IsMeta());
 }
示例#24
0
 public static bool IsAsmDef(this IPsiSourceFile sourceFile)
 {
     return(sourceFile.GetLocation().ExtensionWithDot.Equals(".asmdef", StringComparison.InvariantCultureIgnoreCase));
 }
        private static bool IsAsmDefFile(IPsiSourceFile sourceFile)
        {
            var location = sourceFile.GetLocation();

            return(!location.IsEmpty && location.ExtensionNoDot.Equals("asmdef", StringComparison.OrdinalIgnoreCase));
        }
 public bool IsApplicable(IPsiSourceFile currentAssetSourceFile)
 {
     return(currentAssetSourceFile.GetLocation().IsControllerFile());
 }
示例#27
0
 // ReSharper doesn't want us to use project files. See UnityExternalFilesModuleProcessor
 public static bool IsMeta(this IPsiSourceFile sourceFile)
 {
     return(sourceFile.GetLocation().IsMeta());
 }
示例#28
0
        public override PsiLanguageType GetPsiLanguageType(IPsiSourceFile sourceFile)
        {
            if (UnityYamlFileExtensions.IsMetaOrProjectSettings(sourceFile.GetSolution(), sourceFile.GetLocation()))
            {
                return(base.GetPsiLanguageType(sourceFile));
            }

            return(UnityYamlLanguage.Instance ?? throw new InvalidOperationException("Unexpected state"));
        }
 public bool IsApplicable(IPsiSourceFile sourceFile)
 {
     return(sourceFile.Name.Equals("EditorBuildSettings.asset") && sourceFile.GetLocation().SniffYamlHeader());
 }
示例#30
0
 public static bool IsAsset(this IPsiSourceFile sourceFile)
 {
     return(sourceFile is UnityYamlAssetPsiSourceFile || sourceFile.GetLocation().IsInterestingAsset());
 }
示例#31
0
 public T4IncludeAwareDaemonProcessVisitor([NotNull] IPsiSourceFile initialFile)
 {
     Guard = new T4IncludeGuard();
     Guard.StartProcessing(initialFile.GetLocation());
     IncludeResolver = initialFile.GetSolution().GetComponent <IT4IncludeResolver>();
 }