Esempio n. 1
0
        public IEnumerable <RegistrationInfo> Analyze(IPsiSourceFile sourceFile)
        {
            ICSharpFile cSharpFile;

#if SDK70
            cSharpFile = sourceFile.GetTheOnlyPsiFile(CSharpLanguage.Instance) as ICSharpFile;
#else
            cSharpFile = sourceFile.GetPsiFile(CSharpLanguage.Instance) as ICSharpFile;
#endif
            if (cSharpFile == null)
            {
                return(EmptyList <RegistrationInfo> .InstanceList);
            }

            var usingStatements = cSharpFile.Imports
                                  .Where(directive => !directive.ImportedSymbolName.QualifiedName.StartsWith("System"))
                                  .Select(directive => directive.ImportedSymbolName.QualifiedName).ToList();

            IContainerInfo matchingContainer = GetMatchingContainer(usingStatements);
            if (matchingContainer == null)
            {
                return(EmptyList <RegistrationInfo> .InstanceList);
            }

            ISearchDomain searchDomain = searchDomainFactory.CreateSearchDomain(sourceFile);

            return(ScanRegistrations(matchingContainer, searchDomain));
        }
Esempio n. 2
0
        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));
        }
Esempio n. 3
0
 protected override SearchDeclaredElementUsagesRequest CreateSearchRequest(IDataContext context,
                                                                           ICollection <DeclaredElementInstance> elements,
                                                                           ICollection <DeclaredElementInstance> initialTargets,
                                                                           ISearchDomain searchDomain)
 {
     return(RequestUtil.CreateRequest(context, elements, initialTargets));
 }
 public SearchGenericImplementationsRequest(DeclaredElementTypeUsageInfo declaredElement,
                                            ITypeElement originType,
                                            ISearchDomain searchDomain,
                                            IEnumerable<IDeclaredType> originTypeParams)
     : base(declaredElement, originType, searchDomain) {
     _originTypeParams = originTypeParams;
 }
 public SearchGenericUsagesRequest(ICollection<DeclaredElementInstance> elements,
                                   ICollection<DeclaredElementInstance> initialTargets,
                                   ISearchDomain searchDomain,
                                   IEnumerable<IDeclaredType> originTypeParams)
     : base(elements, initialTargets, SearchPattern.FIND_USAGES, searchDomain) {
     _originTypeParams = originTypeParams;
 }
Esempio n. 6
0
        public void Execute(Action <DaemonStageResult> committer)
        {
            IPsiSourceFile sourceFile  = DaemonProcess.SourceFile;
            IPsiServices   psiServices = sourceFile.GetPsiServices();
            ISymbolScope   symbolScope = psiServices.Symbols.GetSymbolScope(LibrarySymbolScope.FULL, false, sourceFile.ResolveContext);

            ITypeElement typeElement = symbolScope.GetTypeElementByCLRName("TestStack.BDDfy.BDDfyExtensions");

            if (typeElement == null)
            {
                return;
            }

            IEnumerable <IMethod> bddfyMethods = typeElement.Methods.Where(method => method.ShortName == "BDDfy" || method.ShortName == "LazyBDDfy");
            ISearchDomain         searchDomain = searchDomainFactory.CreateSearchDomain(sourceFile);

            IReference[] references = bddfyMethods.SelectMany(method => psiServices.Finder.FindReferences(method, searchDomain, NullProgressIndicator.Instance)).ToArray();
            foreach (IReference reference in references)
            {
                var node = reference.GetTreeNode() as ICSharpTreeNode;
                if (node != null)
                {
                    var classDeclaration = node.GetContainingTypeDeclaration() as IClassDeclaration;
                    if (classDeclaration != null)
                    {
                        SetClassAndMembersUsed(classDeclaration);
                    }
                }
            }
        }
        public IEnumerable<IStructuralMatchResult> Search(IStructuralPatternHolder pattern, ISearchDomain searchDomain)
        {
            var results = new List<IStructuralMatchResult>();
            var consumer = new FindResultConsumer<IStructuralMatchResult>(result =>
            {
                var findResultStructural = result as FindResultStructural;
                if (findResultStructural != null && findResultStructural.DocumentRange.IsValid())
                {
                    return findResultStructural.MatchResult;
                }

                return null;
            }, match =>
            {
                if (match != null)
                {
                    results.Add(match);
                }
                return FindExecution.Continue;
            });

            DoSearch(pattern.Matcher, consumer, searchDomain);

            return results;
        }
Esempio n. 8
0
        public WebSearch(ISearchDomain searchDomain, IKeywordExtractor keywordExtractor)
        {
            SearchDomain     = searchDomain;
            KeywordExtractor = keywordExtractor;

            SearchSettings.MaxLinks      = _maxLinks;
            SearchSettings.MaxParagraphs = _maxParagraphs;
        }
Esempio n. 9
0
 public SearchGenericUsagesRequest(ICollection <DeclaredElementInstance> elements,
                                   ICollection <DeclaredElementInstance> initialTargets,
                                   ISearchDomain searchDomain,
                                   IEnumerable <IDeclaredType> originTypeParams)
     : base(elements, initialTargets, SearchPattern.FIND_USAGES, searchDomain)
 {
     _originTypeParams = originTypeParams;
 }
Esempio n. 10
0
 public SearchGenericImplementationsRequest(DeclaredElementTypeUsageInfo declaredElement,
                                            ITypeElement originType,
                                            ISearchDomain searchDomain,
                                            IEnumerable <IDeclaredType> originTypeParams)
     : base(declaredElement, originType, searchDomain)
 {
     _originTypeParams = originTypeParams;
 }
Esempio n. 11
0
        static TestDomainData[] GenTest(IHeuristic heuristic, int numTasks = 100, int numSteps = Global.MAXSTEPS, bool writeCSV = true, bool computeCost = true)
        {
            TestDomainData[] data = new TestDomainData[numTasks];

            string csvWritePath = string.Format(Global.ROOTPATH, Global.TESTTASKFN);

            CSVWriter csv = new CSVWriter(csvWritePath, ',');

            for (int i = 0; i < numTasks; i++)
            {
                DomainContainer domainContainer = new DomainContainer(heuristic, numSteps);

                ISearchDomain domain = domainContainer.Domain;

                IState initState = domain.Initial();

                string initStateStr = string.Join(" ", initState.Arr);

                int cost = 0;

                long generated = 0;

                if (computeCost == true)
                {
                    if (Global.DOMAINTYPE == typeof(BlocksWorld.BlocksWorld) && heuristic == null)
                    {
                        cost = PostBlocksWorld(initState, domain.Goal());
                    }
                    else
                    {
                        IDAStar <ISearchDomain> planner = new IDAStar <ISearchDomain>(domain);
                        List <IState>           plan    = planner.Search(initState);
                        cost      = (plan.Count - 1);
                        generated = planner.Generated;
                    }
                }


                data[i] = new TestDomainData(initState.Arr, cost, generated);

                csv.Add(initStateStr);

                csv.Add(cost.ToString());

                csv.Add(generated.ToString());

                csv.EndLine();
            }

            if (writeCSV == true)
            {
                csv.Write();
            }

            return(data);
        }
 private void DoSearch(IStructuralMatcher matcher, IFindResultConsumer<IStructuralMatchResult> consumer, ISearchDomain searchDomain)
 {
     // todo add support for VB (eventually)
     var searcher = new StructuralSearcher(documentManager, CSharpLanguage.Instance, matcher);
     var searchDomainSearcher = new StructuralSearchDomainSearcher<IStructuralMatchResult>(
         searchDomain, searcher, consumer, NullProgressIndicator.Instance, true);
     //NarrowSearchDomain(matcher.Words, matcher.GetExtendedWords(solution), searchDomain, searchDomainFactory),
     //searcher, consumer, NullProgressIndicator.Instance, true);
     searchDomainSearcher.Run();
 }
Esempio n. 13
0
        private static ISearchDomain GetSearchDomain(IPsiModule module, IModuleReferenceResolveContext context)
        {
            IPsiServices  psiServices  = module.GetPsiServices();
            ISearchDomain searchDomain = psiServices.SearchDomainFactory.CreateSearchDomain(
                module.GetPsiServices().Modules.GetModules()
                .Where(m => m.References(module, context) || module.References(m, context))
                .Prepend(module));

            return(searchDomain);
        }
 public UnityEditorFindUsageResultCreator(Lifetime lifetime, ISolution solution, SearchDomainFactory searchDomainFactory, IShellLocks locks,
                                          UnitySceneDataLocalCache sceneDataCache, UnityHost unityHost, UnityExternalFilesModuleFactory externalFilesModuleFactory, [CanBeNull] RiderBackgroundTaskHost backgroundTaskHost = null)
 {
     myLifetime = lifetime;
     mySolution = solution;
     myLocks    = locks;
     myUnitySceneDataLocalCache = sceneDataCache;
     myBackgroundTaskHost       = backgroundTaskHost;
     myYamlSearchDomain         = searchDomainFactory.CreateSearchDomain(externalFilesModuleFactory.PsiModule);
     myUnityHost             = unityHost;
     mySolutionDirectoryPath = solution.SolutionDirectory;
 }
Esempio n. 15
0
        public IEnumerable <RegistrationInfo> Analyze([NotNull] IPsiSourceFile sourceFile)
        {
            IContainerInfo matchingContainer = GetMatchingContainer(sourceFile);

            if (matchingContainer == null)
            {
                return(EmptyList <RegistrationInfo> .InstanceList);
            }

            ISearchDomain searchDomain = searchDomainFactory.CreateSearchDomain(sourceFile);

            return(ScanRegistrations(matchingContainer, searchDomain));
        }
Esempio n. 16
0
        public static OneToListMap <string, IClass> GetAvailableModules([NotNull] IPsiModule module,
                                                                        [NotNull] ISearchDomain searchDomain,
                                                                        IModuleReferenceResolveContext contex,
                                                                        bool includingIntermediateControllers = false,
                                                                        ITypeElement baseClass = null)
        {
            ITypeElement[] typeElements;

            ITypeElement nancyModuleInterface = GetNancyModuleInterface(module, contex);

            if (baseClass != null)
            {
                if (baseClass.IsDescendantOf(nancyModuleInterface))
                {
                    typeElements = new[] { baseClass };
                }
                else
                {
                    return(new OneToListMap <string, IClass>(0));
                }
            }
            else
            {
                typeElements = new[] { nancyModuleInterface };
            }

            var found = new List <IClass>();

            foreach (ITypeElement typeElement in typeElements.WhereNotNull())
            {
                module.GetPsiServices()
                .Finder.FindInheritors(typeElement, searchDomain, found.ConsumeDeclaredElements(),
                                       NullProgressIndicator.Instance);
            }

            IEnumerable <IClass> classes = found.Where(@class => @class.GetAccessRights() == AccessRights.PUBLIC);

            if (!includingIntermediateControllers)
            {
                classes = classes.Where(@class => [email protected] &&
                                        @class.ShortName.EndsWith(ModuleClassSuffix,
                                                                  StringComparison.OrdinalIgnoreCase));
            }

            return(new OneToListMap <string, IClass>(
                       classes.GroupBy(GetControllerName,
                                       (name, enumerable) => new KeyValuePair <string, IList <IClass> >(name, enumerable.ToList())),
                       StringComparer.OrdinalIgnoreCase));
        }
 public UnityEditorFindUsageResultCreator(Lifetime lifetime, ISolution solution, SearchDomainFactory searchDomainFactory, IShellLocks locks,
                                          AssetHierarchyProcessor assetHierarchyProcessor, UnityHost unityHost, UnityExternalFilesModuleFactory externalFilesModuleFactory,
                                          UnityEditorProtocol editorProtocol, IPersistentIndexManager persistentIndexManager,
                                          [CanBeNull] RiderBackgroundTaskHost backgroundTaskHost = null)
 {
     myLifetime = lifetime;
     mySolution = solution;
     myLocks    = locks;
     myAssetHierarchyProcessor = assetHierarchyProcessor;
     myBackgroundTaskHost      = backgroundTaskHost;
     myYamlSearchDomain        = searchDomainFactory.CreateSearchDomain(externalFilesModuleFactory.PsiModule);
     myUnityHost              = unityHost;
     myEditorProtocol         = editorProtocol;
     myPersistentIndexManager = persistentIndexManager;
     mySolutionDirectoryPath  = solution.SolutionDirectory;
 }
Esempio n. 18
0
 public DomainContainer(NNBaseHeuristic heuristic, double maxUncert, int maxSteps = 1000)
 {
     if (Global.DOMAINTYPE == typeof(SlidingPuzzle.SlidingPuzzle))
     {
         domain = new SlidingPuzzle.SlidingPuzzle(heuristic, maxUncert, maxSteps);
     }
     else if (Global.DOMAINTYPE == typeof(PancakePuzzle.PancakePuzzle))
     {
         domain = new PancakePuzzle.PancakePuzzle(heuristic, maxUncert, maxSteps);
     }
     else if (Global.DOMAINTYPE == typeof(BlocksWorld.BlocksWorld))
     {
         domain = new BlocksWorld.BlocksWorld(heuristic, maxUncert, maxSteps);
     }
     else
     {
         throw new ArgumentOutOfRangeException();
     }
 }
Esempio n. 19
0
 public DomainContainer(IHeuristic heuristic, int steps)
 {
     if (Global.DOMAINTYPE == typeof(SlidingPuzzle.SlidingPuzzle))
     {
         domain = new SlidingPuzzle.SlidingPuzzle(heuristic, steps);
     }
     else if (Global.DOMAINTYPE == typeof(PancakePuzzle.PancakePuzzle))
     {
         domain = new PancakePuzzle.PancakePuzzle(heuristic, steps);
     }
     else if (Global.DOMAINTYPE == typeof(BlocksWorld.BlocksWorld))
     {
         domain = new BlocksWorld.BlocksWorld(heuristic, steps);
     }
     else
     {
         throw new ArgumentOutOfRangeException();
     }
 }
 public UnityEditorFindUsageResultCreator(Lifetime lifetime, ISolution solution,
                                          SearchDomainFactory searchDomainFactory, IShellLocks locks,
                                          AssetHierarchyProcessor assetHierarchyProcessor,
                                          BackendUnityHost backendUnityHost,
                                          FrontendBackendHost frontendBackendHost,
                                          UnityExternalFilesModuleFactory externalFilesModuleFactory,
                                          IPersistentIndexManager persistentIndexManager,
                                          [NotNull] AnimatorScriptUsagesElementContainer animatorContainer,
                                          [CanBeNull] RiderBackgroundTaskHost backgroundTaskHost = null)
 {
     myLifetime = lifetime;
     mySolution = solution;
     myLocks    = locks;
     myAssetHierarchyProcessor = assetHierarchyProcessor;
     myBackendUnityHost        = backendUnityHost;
     myBackgroundTaskHost      = backgroundTaskHost;
     myYamlSearchDomain        = searchDomainFactory.CreateSearchDomain(externalFilesModuleFactory.PsiModule);
     myFrontendBackendHost     = frontendBackendHost;
     myAnimatorContainer       = animatorContainer;
     myPersistentIndexManager  = persistentIndexManager;
     mySolutionDirectoryPath   = solution.SolutionDirectory;
 }
Esempio n. 21
0
        public IEnumerable <RegistrationInfo> Analyze(IEnumerable <IPsiSourceFile> sourceFiles)
        {
            ISearchDomain searchDomain = searchDomainFactory.CreateSearchDomain(sourceFiles);

            return(knownContainers.SelectMany(info => ScanRegistrations(info, searchDomain)));
        }
 public ProductController(IProductDomain productDomain, ISearchDomain searchDomain)
 {
     ProductDomain = productDomain;
     SearchDomain  = searchDomain;
 }
Esempio n. 23
0
        private void DoSearch(IStructuralPatternHolder pattern, IFindResultConsumer <IStructuralMatchResult> consumer, ISearchDomain searchDomain)
        {
            var searcher             = new StructuralSearcher(documentManager, pattern.Language, pattern.Matcher);
            var searchDomainSearcher = new StructuralSearchDomainSearcher <IStructuralMatchResult>(
                searchDomain, searcher, consumer, NullProgressIndicator.Instance, true);

            searchDomainSearcher.Run();
        }
Esempio n. 24
0
        /// <summary>
        /// This code changes PSI documents. It is executed usder PSI transaction, Command cookies, Reentrancy guard ets.
        /// All documents are committed (PSI is valid).
        /// </summary>
        public override bool Execute(IProgressIndicator pi)
        {
            pi.Start(6);

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

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

            IPsiServices services = Parameter.GetPsiServices();

            IReference[] referencesToParameter;
            IReference[] referencesToRootOverrides;

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

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

            JetHashSet <HierarchyMember> hierarchyMembers = overridesFinder.Overrides;

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

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

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

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

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

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

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

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

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

            return(true);
        }
Esempio n. 25
0
        public static void Train(int run, int iter, int numOutputSolve, bool genDomainFromUncert, int lengthInc, bool effRun)
        {
            string runType = GetRunType(numOutputSolve, genDomainFromUncert, lengthInc, effRun);

            string csvWritePath = string.Format(Global.RUNPATH, run, runType, Global.TRAINFN);

            int numHiddenSolve = 20;

            if (multHeuristic != null)
            {
                numHiddenSolve = 8;
            }

            int?numHiddenUncert = numHiddenSolve;

            if (genDomainFromUncert == false)
            {
                numHiddenUncert = null;
            }

            float dropout = 0F;

            if (multHeuristic == null && numOutputSolve > 1)
            {
                dropout = 0.025F;
            }


            NNBayesHeuristic heuristic = new NNBayesHeuristic(representationSolve, representationUncert, numHiddenSolve, numOutputSolve, numHiddenUncert, dropout, true);

            heuristic.ConfLevel = null;

            if (numOutputSolve > 1)
            {
                heuristic.ConfLevel = 0.01;
            }

            double incConfLevel = 0.05;

            double percSolvedThresh = 0.6;

            int numTasks = 10;

            int tMax;

            if (effRun == true)
            {
                tMax = 1000;
            }
            else if (multHeuristic == null)
            {
                tMax = 60000;
            }
            else
            {
                tMax = 5 * 60000;
            }

            CSVWriter csv = new CSVWriter(csvWritePath, ',');

            Stopwatch sw = new Stopwatch();

            sw.Start();

            int length = lengthInc;

            for (int n = 0; n < iter; n++)
            {
                List <List <IState> > plans = new List <List <IState> >(numTasks);

                int countSolved = 0;

                for (int i = 0; i < numTasks; i++)
                {
                    heuristic.ClearCache();

                    DomainContainer domainContainer;

                    if (genDomainFromUncert == true)
                    {
                        if (heuristic.IsTrained)
                        {
                            domainContainer = new DomainContainer(heuristic, Global.UNCERTTHRESH, Global.MAXSTEPS);
                        }
                        else
                        {
                            domainContainer = new DomainContainer(heuristic, 1);
                        }
                    }
                    else
                    {
                        domainContainer = new DomainContainer(heuristic, length);
                    }

                    ISearchDomain domain = domainContainer.Domain;

                    heuristic.ClearCache();

                    GC.Collect();

                    IDAStar <ISearchDomain> planner = new IDAStar <ISearchDomain>(domain);

                    List <IState> plan = planner.Search(domain.Initial(), tMax);

                    Console.WriteLine("expanded: " + planner.Expanded);
                    Console.WriteLine("generated: " + planner.Generated);
                    Console.WriteLine("elapsed: " + planner.SwopWatch.ElapsedMilliseconds);

                    if (plan.Count > 0)
                    {
                        countSolved++;
                        Console.WriteLine("solved solution length:" + plan.Count);
                        plans.Add(plan);
                    }

                    csv.Add(n.ToString());
                    csv.Add(planner.SwopWatch.ElapsedMilliseconds.ToString());
                    csv.Add(planner.Expanded.ToString());
                    csv.Add(planner.Generated.ToString());
                    csv.Add(heuristic.ConfLevel == null ? "NULL" : heuristic.ConfLevel.ToString());
                    csv.Add(plan.Count.ToString());
                    csv.Add(domain.NumSteps.ToString());

                    csv.EndLine();
                }

                string nnFileName = string.Format(Global.NNFN, n);

                string nnSavePath = string.Format(Global.RUNPATH, run, runType, nnFileName);

                heuristic.NNSolve.Save(nnSavePath, true);

                double percSolved = countSolved / (double)numTasks;


                if (percSolved < percSolvedThresh)
                {
                    heuristic.UpdateBeta = false;

                    if (heuristic.ConfLevel != null && heuristic.ConfLevel < 0.5)
                    {
                        heuristic.ConfLevel += incConfLevel;

                        if (heuristic.ConfLevel > 0.5)
                        {
                            heuristic.ConfLevel = 0.5;
                        }
                    }
                }
                else
                {
                    heuristic.UpdateBeta = true;
                }



                if (plans.Count > 0)
                {
                    double avg = plans.Select(x => x.Count).Average();
                    double max = plans.Select(x => x.Count).Max();
                    double min = plans.Select(x => x.Count).Min();
                    Console.WriteLine("solved: " + plans.Count + " avg: " + avg + " max: " + max + " min: " + min);
                    Console.WriteLine("current conf level: " + heuristic.ConfLevel == null ? "NULL" : heuristic.ConfLevel.ToString());
                }

                long t = sw.ElapsedMilliseconds;

                length += lengthInc;

                csv.Add(t.ToString());

                csv.EndLine();

                csv.Write();

                csv.Clear();



                heuristic.Update(plans.ToArray());
            }

            heuristic.Dispose();
        }
Esempio n. 26
0
 private IEnumerable <RegistrationInfo> ScanRegistrations(IContainerInfo containerInfo, ISearchDomain searchDomain)
 {
     return(from pattern in containerInfo.RegistrationPatterns
            let matchResults = patternSearcher.Search(pattern, searchDomain)
                               from matchResult in matchResults.Where(result => result.Matched)
                               from registration in pattern.GetComponentRegistrations(matchResult.MatchedElement)
                               select new RegistrationInfo(registration, containerInfo.ContainerDisplayName));
 }
Esempio n. 27
0
        static int SolveTestData(IHeuristic heuristic, TestDomainData[] data, CSVWriter csvWriter, int?timeout)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            int countSolved = 0;

            for (int i = 0; i < data.Length; i++)
            {
                Console.WriteLine("iter: " + i.ToString());

                if (timeout != null && sw.ElapsedMilliseconds > timeout)
                {
                    break;
                }

                heuristic.ClearCache();

                GC.Collect();

                TestDomainData testDomainData = data[i];

                DomainContainer domainContainer = new DomainContainer(heuristic, testDomainData.Init);

                ISearchDomain domain = domainContainer.Domain;

                IDAStar <ISearchDomain> planner = new IDAStar <ISearchDomain>(domain);

                List <IState> plan = planner.Search(domain.Initial(), timeout);

                testDomainData.SolvedCost = plan.Count - 1;

                testDomainData.SolvedExpanded = planner.Expanded;

                testDomainData.SolvedGenerated = planner.Generated;


                if (testDomainData.SolvedCost > 0)
                {
                    csvWriter.Add(planner.Expanded.ToString());
                    csvWriter.Add(planner.Generated.ToString());
                    csvWriter.Add(testDomainData.OptimalCost.ToString());
                    csvWriter.Add(testDomainData.SolvedCost.ToString());
                    csvWriter.Add(planner.SwopWatch.ElapsedMilliseconds.ToString());
                    csvWriter.EndLine();
                    csvWriter.Write();
                    csvWriter.Clear();
                    countSolved++;
                }



                Console.WriteLine("cost: " + (plan.Count - 1).ToString());

                Console.WriteLine("generated: " + planner.Generated);

                Console.WriteLine("elapsed: " + planner.SwopWatch.ElapsedMilliseconds);
            }

            return(countSolved);
        }
Esempio n. 28
0
        private void DoSearch(IStructuralMatcher matcher, IFindResultConsumer <IStructuralMatchResult> consumer, ISearchDomain searchDomain)
        {
            // todo add support for VB (eventually)
            var searcher             = new StructuralSearcher(documentManager, CSharpLanguage.Instance, matcher);
            var searchDomainSearcher = new StructuralSearchDomainSearcher <IStructuralMatchResult>(
                searchDomain, searcher, consumer, NullProgressIndicator.Instance, true);

            //NarrowSearchDomain(matcher.Words, matcher.GetExtendedWords(solution), searchDomain, searchDomainFactory),
            //searcher, consumer, NullProgressIndicator.Instance, true);
            searchDomainSearcher.Run();
        }
Esempio n. 29
0
        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)));
        }
Esempio n. 30
0
 public WebSearch(ISearchDomain searchDomain, IKeywordExtractor keywordExtractor, SearchSettingsType settings) : this(searchDomain, keywordExtractor)
 {
     SearchSettings = settings;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="FindItemUsagesRequest" /> class.
 /// </summary>
 /// <param name="solution">The solution.</param>
 /// <param name="searchDomain">The search domain.</param>
 public FindItemUsagesRequest(ISolution solution, ISearchDomain searchDomain) : base(solution, searchDomain)
 {
 }
 protected override SearchDeclaredElementUsagesRequest CreateSearchRequest(IDataContext context, 
     ICollection<DeclaredElementInstance> elements,
     ICollection<DeclaredElementInstance> initialTargets, 
     ISearchDomain searchDomain) {
     return RequestUtil.CreateRequest(context, elements, initialTargets);
 }
 private IEnumerable<RegistrationInfo> ScanRegistrations(IContainerInfo containerInfo, ISearchDomain searchDomain)
 {
     return from pattern in containerInfo.RegistrationPatterns
            let matchResults = patternSearcher.Search(pattern, searchDomain)
            from matchResult in matchResults.Where(result => result.Matched)
            from registration in pattern.GetComponentRegistrations(matchResult.MatchedElement)
            select new RegistrationInfo(registration, containerInfo.ContainerDisplayName);
 }
Esempio n. 34
0
        public static string DetermineViewModelType(ITreeNode node, IType defaultType = null)
        {
            Func <IEnumerable <IType>, IType> typeChecker =
                types =>
                types.FirstOrDefault(
                    type => type != null && !type.IsUnknown && !type.IsObject() && !(type is IAnonymousType));

            // first, try determine type of explicitly specified model
            IType modelType = typeChecker(
                RetrieveArgumentExpressions(
                    (node.GetContainingNode <IArgument>(true) ?? node).GetContainingNode <IArgumentsOwner>(true),
                    MvcKind.ModelType)
                .Select(pair => pair.First).Select(_ => _.Type()));

            // second, try determine type of implicitly specified model
            if (modelType == null)
            {
                IPsiServices psiServices     = node.GetPsiServices();
                ISolution    solution        = psiServices.Solution;
                var          languageManager = solution.GetComponent <ILanguageManager>();
#if SDK80
                IMvcElementsCache mvcElementsCache = MvcElementsCache.GetInstance(node.GetPsiModule(), node.GetResolveContext());
#else
                IMvcElementsCache mvcElementsCache = MvcElementsCache.GetInstance(node.GetPsiModule());
#endif
                List <IDeclaredElement> setters =
                    new[]
                { mvcElementsCache.MvcViewDataDictionaryClass, mvcElementsCache.MvcTypedViewDataDictionaryClass }
                .WhereNotNull()
                .SelectMany(typeElement => typeElement.Properties)
                .Where(
                    property =>
                    String.Equals(property.ShortName, "Model",
                                  property.CaseSensistiveName
                                        ? StringComparison.Ordinal
                                        : StringComparison.OrdinalIgnoreCase))
                .Select <IProperty, IDeclaredElement>(property => property.Setter)
                .ToList();
                ISearchDomain searchDomain =
                    solution.GetComponent <SearchDomainFactory>()
                    .CreateSearchDomain(node.GetContainingNode <ITypeOwnerDeclaration>() ?? node);
                var references = new List <IReference>();
                psiServices.Finder.Find(setters, searchDomain, references.ConsumeReferences(),
                                        SearchPattern.FIND_USAGES | SearchPattern.FIND_RELATED_ELEMENTS,
                                        NullProgressIndicator.Instance);
                modelType = typeChecker(references
                                        .Select(reference => reference.GetTreeNode())
                                        .OfType <IExpression>()
                                        .Select(
                                            expression =>
                                            languageManager.GetService <IMvcLanguageHelper>(expression.Language)
                                            .GetAssigmentType(expression)))
                            ?? defaultType; // default type, fallback
            }

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

            return(modelType.GetLongPresentableName(node.Language));
        }
Esempio n. 35
0
        public IEnumerable <RegistrationInfo> Analyze()
        {
            ISearchDomain searchDomain = searchDomainFactory.CreateSearchDomain(solution, false);

            return(knownContainers.SelectMany(info => ScanRegistrations(info, searchDomain)));
        }
Esempio n. 36
0
 public PubSearchController(ISearchDomain searchDomain, ICacheManager Cache) : base(Cache)
 {
     SearchDomain = searchDomain;
 }
Esempio n. 37
0
        public IEnumerable <IStructuralMatchResult> Search(IStructuralPatternHolder pattern, ISearchDomain searchDomain)
        {
            var results  = new List <IStructuralMatchResult>();
            var consumer = new FindResultConsumer <IStructuralMatchResult>(result =>
            {
                var findResultStructural = result as FindResultStructural;
                if (findResultStructural != null && findResultStructural.DocumentRange.IsValid())
                {
                    return(findResultStructural.MatchResult);
                }

                return(null);
            }, match =>
            {
                if (match != null)
                {
                    results.Add(match);
                }
                return(FindExecution.Continue);
            });

            DoSearch(pattern.Matcher, consumer, searchDomain);

            return(results);
        }