Esempio n. 1
1
        internal async Task RemoveAllRenameAnnotationsAsync(IEnumerable<DocumentId> documentWithRenameAnnotations, AnnotationTable<RenameAnnotation> annotationSet, CancellationToken cancellationToken)
        {
            foreach (var documentId in documentWithRenameAnnotations)
            {
                if (_renamedSpansTracker.IsDocumentChanged(documentId))
                {
                    var document = _newSolution.GetDocument(documentId);
                    var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                    // For the computeReplacementToken and computeReplacementNode functions, use 
                    // the "updated" node to maintain any annotation removals from descendants.
                    var newRoot = root.ReplaceSyntax(
                        nodes: annotationSet.GetAnnotatedNodes(root),
                        computeReplacementNode: (original, updated) => annotationSet.WithoutAnnotations(updated, annotationSet.GetAnnotations(updated).ToArray()),
                        tokens: annotationSet.GetAnnotatedTokens(root),
                        computeReplacementToken: (original, updated) => annotationSet.WithoutAnnotations(updated, annotationSet.GetAnnotations(updated).ToArray()),
                        trivia: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(),
                        computeReplacementTrivia: null);

                    _intermediateSolutionContainingOnlyModifiedDocuments = _intermediateSolutionContainingOnlyModifiedDocuments.WithDocumentSyntaxRoot(documentId, newRoot, PreservationMode.PreserveIdentity);
                }
            }

            _newSolution = _intermediateSolutionContainingOnlyModifiedDocuments;
        }
Esempio n. 2
0
        internal static IEnumerable<Document> GetDocumentsAffectedByRename(ISymbol symbol, Solution solution, IEnumerable<RenameLocation> renameLocations)
        {
            if (IsSymbolDefinedInsideMethod(symbol))
            {
                // if the symbol was declared inside of a method, don't check for conflicts in non-renamed documents.
                return renameLocations.Select(l => solution.GetDocument(l.DocumentId));
            }
            else
            {
                var documentsOfRenameSymbolDeclaration = symbol.Locations.Where(l => l.IsInSource).Select(l => solution.GetDocument(l.SourceTree));
                var projectIdsOfRenameSymbolDeclaration =
                    documentsOfRenameSymbolDeclaration.SelectMany(d => d.GetLinkedDocumentIds())
                    .Concat(documentsOfRenameSymbolDeclaration.First().Id)
                    .Select(d => d.ProjectId).Distinct();

                if (ShouldRenameOnlyAffectDeclaringProject(symbol))
                {
                    var isSubset = renameLocations.Select(l => l.DocumentId.ProjectId).Distinct().Except(projectIdsOfRenameSymbolDeclaration).IsEmpty();
                    Contract.ThrowIfFalse(isSubset);
                    return projectIdsOfRenameSymbolDeclaration.SelectMany(p => solution.GetProject(p).Documents);
                }
                else
                {
                    // We are trying to figure out the projects that directly depend on the project that contains the declaration for 
                    // the rename symbol.  Other projects should not be affected by the rename.
                    var relevantProjects = projectIdsOfRenameSymbolDeclaration.Concat(projectIdsOfRenameSymbolDeclaration.SelectMany(p =>
                       solution.GetProjectDependencyGraph().GetProjectsThatDirectlyDependOnThisProject(p))).Distinct();
                    return relevantProjects.SelectMany(p => solution.GetProject(p).Documents);
                }
            }
        }
Esempio n. 3
0
 private static void AddSolution(SolutionSizeTracker.IncrementalAnalyzer analyzer, Solution solution)
 {
     foreach (var document in solution.Projects.SelectMany(p => p.Documents))
     {
         analyzer.AnalyzeSyntaxAsync(document, CancellationToken.None).Wait();
     }
 }
        /// <summary>
        /// this gives you SymbolTreeInfo for a metadata
        /// </summary>
        public static async Task<SymbolTreeInfo> GetInfoForMetadataReferenceAsync(
            Solution solution,
            PortableExecutableReference reference,
            bool loadOnly,
            CancellationToken cancellationToken)
        {
            var metadata = reference.GetMetadata();
            if (metadata == null)
            {
                return null;
            }

            // Find the lock associated with this piece of metadata.  This way only one thread is
            // computing a symbol tree info for a particular piece of metadata at a time.
            var gate = s_metadataIdToGate.GetValue(metadata.Id, s_metadataIdToGateCallback);
            using (await gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
            {
                cancellationToken.ThrowIfCancellationRequested();

                SymbolTreeInfo info;
                if (s_metadataIdToInfo.TryGetValue(metadata.Id, out info))
                {
                    return info;
                }

                info = await LoadOrCreateMetadataSymbolTreeInfoAsync(
                    solution, reference, loadOnly, cancellationToken: cancellationToken).ConfigureAwait(false);
                if (info == null && loadOnly)
                {
                    return null;
                }

                return s_metadataIdToInfo.GetValue(metadata.Id, _ => info);
            }
        }
        public PluginList()
        {
            InitializeComponent();

            _logger = new Logger();

            _dte = Package.GetGlobalService(typeof(DTE)) as DTE;
            if (_dte == null)
                return;

            _solution = _dte.Solution;
            if (_solution == null)
                return;

            _events = _dte.Events;
            var windowEvents = _events.WindowEvents;
            windowEvents.WindowActivated += WindowEventsOnWindowActivated;
            _solutionEvents = _events.SolutionEvents;
            _solutionEvents.BeforeClosing += BeforeSolutionClosing;
            _solutionEvents.BeforeClosing += SolutionBeforeClosing;
            _solutionEvents.ProjectAdded += SolutionProjectAdded;
            _solutionEvents.ProjectRemoved += SolutionProjectRemoved;
            _solutionEvents.ProjectRenamed += SolutionProjectRenamed;

            SelectedAssemblyItem.PropertyChanged += SelectedAssemblyItem_PropertyChanged;
        }
		public MemberMetricsCalculator(SemanticModel semanticModel, Solution solution, IAsyncFactory<ISymbol, IMemberDocumentation> documentationFactory)
			: base(semanticModel)
		{
			_solution = solution;
			_documentationFactory = documentationFactory;
			_nameResolver = new MemberNameResolver(Model);
		}
            public override Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
            {
                // check whether we are good to report total symbol numbers
                if (_symbolCountByProjectMap == null || _symbolCountByProjectMap.Count < solution.ProjectIds.Count || string.IsNullOrEmpty(solution.FilePath))
                {
                    return SpecializedTasks.EmptyTask;
                }

                if (_solutionId != null && _solutionId != solution.Id)
                {
                    ReportCount();
                    return SpecializedTasks.EmptyTask;
                }

                _solutionId = solution.Id;
                foreach (var projectId in solution.ProjectIds)
                {
                    if (!_symbolCountByProjectMap.ContainsKey(projectId))
                    {
                        return SpecializedTasks.EmptyTask;
                    }
                }

                ReportCount();
                return SpecializedTasks.EmptyTask;
            }
 public Population(Problem problem)
 {
     _problem = problem;
     InitializePopulation();
     _bestSolution = new Solution();
     _generationsSoFar = 0;
 }
            public SymbolLocationNavigableItem(
                Solution solution,
                ISymbol symbol,
                Location location)
            {
                _solution = solution;
                _symbol = symbol;
                _location = location;

                _lazyDisplayName = new Lazy<string>(() =>
                {
                    var symbolDisplayService = this.Document.Project.LanguageServices.GetService<ISymbolDisplayService>();

                    switch (symbol.Kind)
                    {
                        case SymbolKind.NamedType:
                            return symbolDisplayService.ToDisplayString(_symbol, s_shortFormatWithModifiers);

                        case SymbolKind.Method:
                            return _symbol.IsStaticConstructor()
                                ? symbolDisplayService.ToDisplayString(_symbol, s_shortFormatWithModifiers)
                                : symbolDisplayService.ToDisplayString(_symbol, s_shortFormat);

                        default:
                            return symbolDisplayService.ToDisplayString(_symbol, s_shortFormat);
                    }
                });
            }
 protected override BinPacking2D CreatePacking(
   Solution partialSolution,
   ref IList<int> remainingIDs, IList<PackingItem> items) {
   var bp = new BinPacking2D(partialSolution.BinShape);
   bp.ExtremePointBasedPacking(ref remainingIDs, items, stackingConstraints: false);
   return bp;
 }
Esempio n. 11
0
        private static async Task FindReferencesInServiceProcessAsync(
            SymbolAndProjectId symbolAndProjectId,
            Solution solution,
            IStreamingFindReferencesProgress progress,
            IImmutableSet<Document> documents,
            CancellationToken cancellationToken)
        {
            var client = await solution.Workspace.GetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false);
            if (client == null)
            {
                await FindReferencesInCurrentProcessAsync(
                    symbolAndProjectId, solution, progress, documents, cancellationToken).ConfigureAwait(false);
                return;
            }

            // Create a callback that we can pass to the server process to hear about the 
            // results as it finds them.  When we hear about results we'll forward them to
            // the 'progress' parameter which will then upate the UI.
            var serverCallback = new ServerCallback(solution, progress, cancellationToken);

            using (var session = await client.CreateCodeAnalysisServiceSessionAsync(
                solution, serverCallback, cancellationToken).ConfigureAwait(false))
            {
                await session.InvokeAsync(
                    nameof(IRemoteSymbolFinder.FindReferencesAsync),
                    SerializableSymbolAndProjectId.Dehydrate(symbolAndProjectId),
                    documents?.Select(SerializableDocumentId.Dehydrate).ToArray()).ConfigureAwait(false);
            }
        }
 /// <summary>
 /// Finds all references to a symbol throughout a solution
 /// </summary>
 /// <param name="symbol">The symbol to find references to.</param>
 /// <param name="solution">The solution to find references within.</param>
 /// <param name="cancellationToken">A cancellation token.</param>
 public static Task<IEnumerable<ReferencedSymbol>> FindReferencesAsync(
     ISymbol symbol,
     Solution solution,
     CancellationToken cancellationToken = default(CancellationToken))
 {
     return FindReferencesAsync(symbol, solution, progress: null, documents: null, cancellationToken: cancellationToken);
 }
Esempio n. 13
0
 public void TestMethod(string ratingsString, string candyString)
 {
     var ratings = JsonConvert.DeserializeObject<int[]>(ratingsString);
     var expectedResult = JsonConvert.DeserializeObject<int[]>(candyString).Sum();
     var result = new Solution().Candy(ratings);
     Assert.AreEqual(expectedResult, result);
 }
 public LinqGenerator(Solution.Solution solution, SchemaFactory dbInfo)
     : base(solution, dbInfo)
 {
     LinqDirectory = Path.Combine(Solution.BaseDirectory, "LINQ");
     if (!Directory.Exists(LinqDirectory))
         Directory.CreateDirectory(LinqDirectory);
 }
		public SolutionPackageRepository2 (Solution solution)
			: this (
				solution,
				new SharpDevelopPackageRepositoryFactory (),
				PackageManagementServices.Options)
		{
		}
Esempio n. 16
0
        public static async Task<Solution> RenameSymbolAsync(Solution solution, ISymbol symbol, string newName, OptionSet optionSet, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (solution == null)
            {
                throw new ArgumentNullException(nameof(solution));
            }

            if (symbol == null)
            {
                throw new ArgumentNullException(nameof(symbol));
            }

            if (string.IsNullOrEmpty(newName))
            {
                throw new ArgumentException("newName");
            }

            cancellationToken.ThrowIfCancellationRequested();

            optionSet = optionSet ?? solution.Workspace.Options;
            var renameLocationSet = await RenameLocationSet.FindAsync(symbol, solution, optionSet, cancellationToken).ConfigureAwait(false);
            var conflictResolution = await ConflictEngine.ConflictResolver.ResolveConflictsAsync(renameLocationSet, symbol.Name, newName, optionSet, cancellationToken).ConfigureAwait(false);

            return conflictResolution.NewSolution;
        }
        private void ProcessReferencedSymbol(
            Solution solution,
            ReferencedSymbol referencedSymbol,
            ArrayBuilder<DefinitionItem> definitions,
            ArrayBuilder<SourceReferenceItem> references,
            bool includeHiddenLocations,
            HashSet<DocumentSpan> uniqueSpans)
        {
            // See if this is a symbol we even want to present to the user.  If not,
            // ignore it entirely (including all its reference locations).
            if (!referencedSymbol.ShouldShow())
            {
                return;
            }

            var definitionItem = referencedSymbol.Definition.ToDefinitionItem(
                solution, includeHiddenLocations, uniqueSpans);
            definitions.Add(definitionItem);

            // Now, create the SourceReferenceItems for all the reference locations
            // for this definition.
            CreateReferences(
                referencedSymbol, references, definitionItem,
                includeHiddenLocations, uniqueSpans);

            // Finally, see if there are any third parties that want to add their
            // own result to our collection.
            var thirdPartyItem = GetThirdPartyDefinitionItem(solution, referencedSymbol.Definition);
            if (thirdPartyItem != null)
            {
                definitions.Add(thirdPartyItem);
            }
        }
Esempio n. 18
0
 internal RenameLocations(ISet<RenameLocation> locations, ISymbol symbol, Solution solution, IEnumerable<ISymbol> referencedSymbols, IEnumerable<ReferenceLocation> implicitLocations, OptionSet options)
 {
     _symbol = symbol;
     _solution = solution;
     _mergedResult = new SearchResult(locations, implicitLocations, referencedSymbols);
     Options = options;
 }
        public static Document GetSingleAddedDocument(Solution oldSolution, Solution newSolution)
        {
            var projectDifferences = GetSingleChangedProjectChanges(oldSolution, newSolution);
            var documentId = projectDifferences.GetAddedDocuments().Single();

            return newSolution.GetDocument(documentId);
        }
 public void TestMethod(string s, string expectedResultString)
 {
     expectedResultString = JsonConvert.SerializeObject(JsonConvert.DeserializeObject<string[]>(expectedResultString).OrderBy(ip => ip));
     var answer = new Solution().RestoreIpAddresses(s);
     var answerString = JsonConvert.SerializeObject(answer.OrderBy(ip => ip));
     Assert.AreEqual(expectedResultString, answerString);
 }
Esempio n. 21
0
        public void SolutionLoaded(Solution solution)
        {
            var converter = new NuGetConverter();
            var report = converter.Convert(solution);

            // Print out the report
        }
        public static IList<Project> Projects(Solution solution)
        {
            Projects projects = solution.Projects;
            List<Project> list = new List<Project>();
            var item = projects.GetEnumerator();
            while (item.MoveNext())
            {
                var project = item.Current as Project;
                if (project == null)
                {
                    continue;
                }

                if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder)
                {
                    list.AddRange(GetSolutionFolderProjects(project));
                }
                else
                {
                    list.Add(project);
                }
            }

            return list;
        }
Esempio n. 23
0
 public void TestMethod(string s, string wordDictString, string expectedResultsString)
 {
     var wordDict = new HashSet<string>(wordDictString.Split());
     var expectedResults = expectedResultsString.Split('|').OrderBy(str => str).ToArray();
     var results = new Solution().WordBreak(s, wordDict).OrderBy(str => str).ToArray();
     Assert.AreEqual(string.Join("|", expectedResults), string.Join("|", results));
 }
        public IList<Dependency> MergeAndResolveDependencies(Solution soln, Project proj)
        {
            try {
                var wishes = new List<Wish>();
                wishes.AddRange(soln.GetAllWishes());
                wishes.AddRange(proj.GetAllWishes());

                if (Log.IsTraceEnabled()) {
                    Log.Trace("merged wishes=\n" + String.Join("\n",wishes));
                }
                ValidateAll(wishes);

                //now the fun begins. Resolve transitive deps, find closest versions
                //TODO:resolve for all but pick only what the current project needs
                //TODO:keep the calculated cache for how long? how to decide when to recalc all?
                var resolver = new WishDependencyResolver(DepsCache);
                var deps = resolver.Resolve(wishes);

                var projWishes = proj.GetAllWishes();
                //TODO:now line up with deps? to get copy to and additional info added?

                return deps;
            } catch (Exception e) {
                throw new ResolverException("Error trying to resolve dependencies for project " + proj + " and solution " + soln, e);
            }
        }
Esempio n. 25
0
        public void DoMutation(double probability, Solution solution)
        {
            XReal x = new XReal(solution);

            for (int var = 0; var < solution.DecisionVariables.Length; var++)
            {
                if (PseudoRandom.Instance().NextDouble() < probability)
                {
                    double rand = PseudoRandom.Instance().NextDouble();
                    double tmp = (rand - 0.5)*_perturbation;

                    tmp += x.GetValue(var);

                    if (tmp < x.GetLowerBound(var))
                    {
                        tmp = x.GetLowerBound(var);
                    }
                    else if (tmp > x.GetUpperBound(var))
                    {
                        tmp = x.GetUpperBound(var);
                    }

                    x.SetValue(var, tmp);
                }
            }
        }
		public RestoreAndCheckForUpdatesAction (Solution solution)
		{
			this.solution = solution;
			packageManagementEvents = PackageManagementServices.PackageManagementEvents;

			solutionManager = PackageManagementServices.Workspace.GetSolutionManager (solution);
			nugetProjects = solutionManager.GetNuGetProjects ().ToList ();

			if (AnyProjectsUsingPackagesConfig ()) {
				restoreManager = new PackageRestoreManager (
					solutionManager.CreateSourceRepositoryProvider (),
					solutionManager.Settings,
					solutionManager
				);
			}

			if (AnyProjectsUsingProjectJson ()) {
				buildIntegratedRestorer = new MonoDevelopBuildIntegratedRestorer (
					solutionManager.CreateSourceRepositoryProvider (),
					solutionManager.Settings);
			}

			if (AnyNuGetAwareProjects ()) {
				nugetAwareRestorer = new NuGetAwareProjectPackageRestoreManager (solutionManager);
			}
		}
 public void TestMethod(string input, string expectedResultString)
 {
     var expectedResult = JsonConvert.DeserializeObject<List<int>>(expectedResultString);
     expectedResult.Sort();
     var result = new Solution().DiffWaysToCompute(input).OrderBy(x => x);
     Assert.AreEqual(JsonConvert.SerializeObject(expectedResult), JsonConvert.SerializeObject(result));
 }
Esempio n. 28
0
    static void Main(string[] args)
    {
        Solution s = new Solution();

        int[] TestCase = new int[6] {1,3,6,4,1,2};
        Console.WriteLine(s.solution(TestCase));
    }
Esempio n. 29
0
        public TemporaryWorkspace(Solution solution)
            : base(RoslynServices.HostServices, workspaceKind: TemporaryWorkspace.WorkspaceKind_TemporaryWorkspace)
        {
            Options = Options.WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0);

            this.SetCurrentSolution(solution);
        }
Esempio n. 30
0
        static void Main()
        {
            var s = new Solution();
            Console.WriteLine(s.solution(
                new[] { 5, 1, 3, 1, 1 },
                new[] { 1, 1, 0, 0, 0 }));
            Console.WriteLine(s.solution(
                new[] { 1, 2, 1, 1, 1 },
                new[] { 0, 1, 0, 0, 0 }));
            Console.WriteLine(s.solution(
                new[] { 1, 2, 4, 3, 5 },
                new[] { 0, 1, 0, 1, 0 }));
            Console.WriteLine(s.solution(
                new[] { 1, 2, 1, 3, 1 },
                new[] { 0, 1, 0, 1, 0 }));
            Console.WriteLine(s.solution(
                new[] { 1, 4, 2, 3, 5 },
                new[] { 0, 1, 0, 1, 0 }));
            Console.WriteLine(s.solution(
                new[] { 1, 1, 3, 1, 1 },
                new[] { 0, 1, 0, 0, 0 }));

            Console.WriteLine(s.solution(new[] { 1 }, new[] { 0 }));
            Console.WriteLine(s.solution(new[] { 1 }, new[] { 1 }));

            var A = new int[100000];
            for (int i = 0; i < 100000; i++)
            {
                A[i] = 1000000000 - i;
            }
            var B = new int[100000];
            B[0] = 1;
            Console.WriteLine(s.solution(A, B));
        }
Esempio n. 31
0
        private static Solution UpdateSolution(Solution solution, string projectName, string documentName, string csAddition, string vbAddition)
        {
            var(project, document) = GetProjectAndDocument(solution, projectName, documentName);

            return(document.WithText(GetNewText(document, csAddition, vbAddition)).Project.Solution);
        }
Esempio n. 32
0
 private static Solution WithChangedOptionsFromRemoteWorkspace(Solution solution)
 => solution.WithChangedOptionsFrom(RemoteWorkspace.Options);
Esempio n. 33
0
 public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
 {
     return SpecializedTasks.EmptyTask;
 }
Esempio n. 34
0
        public static async Task <bool> IsUnusedSymbolAsync(
            ISymbol symbol,
            Solution solution,
            CancellationToken cancellationToken = default)
        {
            ImmutableArray <SyntaxReference> syntaxReferences = symbol.DeclaringSyntaxReferences;

            Debug.Assert(syntaxReferences.Any(), $"No syntax references for {symbol.ToDisplayString()}");

            if (!syntaxReferences.Any())
            {
                return(false);
            }

            if (IsReferencedInDebuggerDisplayAttribute(symbol))
            {
                return(false);
            }

            IEnumerable <ReferencedSymbol> referencedSymbols = await SymbolFinder.FindReferencesAsync(symbol, solution, cancellationToken).ConfigureAwait(false);

            foreach (ReferencedSymbol referencedSymbol in referencedSymbols)
            {
                foreach (ReferenceLocation referenceLocation in referencedSymbol.Locations)
                {
                    if (referenceLocation.IsImplicit)
                    {
                        continue;
                    }

                    if (referenceLocation.IsCandidateLocation)
                    {
                        return(false);
                    }

                    Location location = referenceLocation.Location;

                    if (!location.IsInSource)
                    {
                        continue;
                    }

                    foreach (SyntaxReference syntaxReference in syntaxReferences)
                    {
                        if (syntaxReference.SyntaxTree != location.SourceTree ||
                            !syntaxReference.Span.Contains(location.SourceSpan))
                        {
                            return(false);
                        }
                    }
                }
            }

            if (symbol.Kind == SymbolKind.Field)
            {
                INamedTypeSymbol containingType = symbol.ContainingType;

                if (containingType.TypeKind == TypeKind.Enum &&
                    containingType.HasAttribute(MetadataNames.System_FlagsAttribute))
                {
                    var fieldSymbol = (IFieldSymbol)symbol;

                    if (fieldSymbol.HasConstantValue)
                    {
                        ulong value = SymbolUtility.GetEnumValueAsUInt64(fieldSymbol.ConstantValue, containingType);

                        if (value == 0)
                        {
                            return(false);
                        }
                    }
                }
            }

            if (symbol.Kind == SymbolKind.NamedType)
            {
                var namedType = (INamedTypeSymbol)symbol;

                if (namedType.TypeKind.Is(TypeKind.Class, TypeKind.Struct))
                {
                    foreach (ISymbol member in namedType.GetMembers())
                    {
                        if (member.Kind == SymbolKind.Method)
                        {
                            var methodSymbol = (IMethodSymbol)member;

                            if (SymbolUtility.CanBeEntryPoint(methodSymbol))
                            {
                                return(false);
                            }
                        }
                    }
                }
            }

            return(true);
        }
Esempio n. 35
0
        /// <summary>
        /// Create a project using the input strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <returns>A Project created out of the Documents created from the source strings</returns>
        private static Project CreateProject(string[] sources)
        {
            Solution sol = null;

            return(CreateProject(TestProjectName, ref sol, sources));
        }
Esempio n. 36
0
        /// <summary>
        /// Returns true if the solution is using the old style package restore.
        /// </summary>
        /// <param name="solution">The solution to check.</param>
        /// <returns>True if the solution is using the old style package restore.</returns>
        private static bool UsingOldPackageRestore(Solution solution)
        {
            var nugetSolutionFolder = VsUtility.GetNuGetSolutionFolder(solution);

            return(File.Exists(Path.Combine(nugetSolutionFolder, "nuget.targets")));
        }
        public SolutionViewModel(ISolution model) : base(model)
        {
            shell = IoC.Get<IShell>();

            Projects = new ObservableCollection<ProjectViewModel>();
            IsExpanded = true;

            Projects.BindCollections(model.Projects, p => { return ProjectViewModel.Create(this, p); },
                (pvm, p) => pvm.Model == p);

            NewProjectCommand = ReactiveCommand.Create(() =>
            {
                shell.ModalDialog = new NewProjectDialogViewModel(model);
                shell.ModalDialog.ShowDialog();
            });

            AddExistingProjectCommand = ReactiveCommand.Create(async () =>
            {
                var dlg = new OpenFileDialog();
                dlg.Title = "Open Project";

                var extensions = new List<string>();

                foreach (var projectType in shell.ProjectTypes)
                {
                    extensions.AddRange(projectType.Extensions);
                }

                dlg.Filters.Add(new FileDialogFilter { Name = "AvalonStudio Project", Extensions = extensions });

                if (Platform.PlatformIdentifier == Platforms.PlatformID.Win32NT)
                {
                    dlg.InitialDirectory = Model.CurrentDirectory;
                }
                else
                {
                    dlg.InitialFileName = Model.CurrentDirectory;
                }

                dlg.AllowMultiple = false;

                var result = await dlg.ShowAsync();

                if (result != null && !string.IsNullOrEmpty(result.FirstOrDefault()))
                {
                    var proj = Solution.LoadProjectFile(model, result[0]);

                    if (proj != null)
                    {
                        model.AddProject(proj);
                        model.Save();
                    }
                }
            });

            OpenInExplorerCommand = ReactiveCommand.Create(() => { Platform.OpenFolderInExplorer(model.CurrentDirectory); });

            ConfigurationCommand = ReactiveCommand.Create(() =>
            {
                //Workspace.Instance.ModalDialog = new SolutionConfigurationDialogViewModel(Workspace.Instance.SolutionExplorer.Model);
                //Workspace.Instance.ModalDialog.ShowDialog();
            });

            BuildSolutionCommand = ReactiveCommand.Create(() => BuildSolution());

            CleanSolutionCommand = ReactiveCommand.Create(() => CleanSolution());

            RebuildSolutionCommand = ReactiveCommand.Create(() =>
            {
                CleanSolution();

                BuildSolution();
            });

            RunAllTestsCommand = ReactiveCommand.Create(() => RunTests());
        }
Esempio n. 38
0
        private async Task <Solution> VerifyIncrementalUpdatesAsync(InProcRemoteHostClient client, Solution solution, string csAddition, string vbAddition)
        {
            var remoteSolution = RemoteWorkspace.CurrentSolution;
            var projectIds     = solution.ProjectIds;

            for (var i = 0; i < projectIds.Count; i++)
            {
                var projectName = $"Project{i}";
                var project     = solution.GetProject(projectIds[i]);

                var documentIds = project.DocumentIds;
                for (var j = 0; j < documentIds.Count; j++)
                {
                    var documentName = $"Document{j}";

                    var currentSolution = UpdateSolution(solution, projectName, documentName, csAddition, vbAddition);
                    await UpdatePrimaryWorkspace(client, currentSolution);

                    var currentRemoteSolution = RemoteWorkspace.CurrentSolution;
                    VerifyStates(remoteSolution, currentRemoteSolution, projectName, documentName);

                    solution       = currentSolution;
                    remoteSolution = currentRemoteSolution;

                    Assert.Equal(
                        await solution.State.GetChecksumAsync(CancellationToken.None),
                        await remoteSolution.State.GetChecksumAsync(CancellationToken.None));
                }
            }

            return(solution);
        }
Esempio n. 39
0
        public IPersistentStorage GetStorage(Solution solution)
        {
            if (solution.FilePath == null)
            {
                return(NoOpPersistentStorageInstance);
            }

            // can't use cached information
            if (!string.Equals(solution.FilePath, _lastSolutionPath, StringComparison.OrdinalIgnoreCase))
            {
                // check whether the solution actually exist on disk
                if (!File.Exists(solution.FilePath))
                {
                    return(NoOpPersistentStorageInstance);
                }
            }

            // cache current result.
            _lastSolutionPath = solution.FilePath;

            // get working folder path
            var workingFolderPath = GetWorkingFolderPath(solution);

            if (workingFolderPath == null)
            {
                // we don't have place to save esent file. don't use esent
                return(NoOpPersistentStorageInstance);
            }

            lock (_lookupAccessLock)
            {
                // see whether we have something we can use
                AbstractPersistentStorage storage;
                if (_lookup.TryGetValue(solution.FilePath, out storage))
                {
                    // previous attempt to create esent storage failed, don't try again within same VS session
                    // just don't use esent within this same vs session
                    if (storage == null)
                    {
                        return(NoOpPersistentStorageInstance);
                    }

                    // everything seems right, use what we have
                    if (storage.WorkingFolderPath == workingFolderPath)
                    {
                        storage.AddRefUnsafe();
                        return(storage);
                    }
                }

                // either this is the first time, or working folder path has changed.
                // remove existing one
                _lookup.Remove(solution.FilePath);

                // try create new one
                storage = TryCreateEsentStorage(workingFolderPath, solution.FilePath);
                _lookup.Add(solution.FilePath, storage);

                if (storage != null)
                {
                    RegisterPrimarySolutionStorageIfNeeded(solution, storage);

                    storage.AddRefUnsafe();
                    return(storage);
                }

                return(NoOpPersistentStorageInstance);
            }
        }
Esempio n. 40
0
        private static async Task VerifyAssetStorageAsync(InProcRemoteHostClient client, Solution solution)
        {
            var map = await solution.GetAssetMapAsync(CancellationToken.None);

            var storage = client.AssetStorage;

            TestUtils.VerifyAssetStorage(map, storage);
        }
Esempio n. 41
0
            internal static async Task <IEnumerable <RenameLocation> > GetRenamableReferenceLocationsAsync(ISymbol referencedSymbol, ISymbol originalSymbol, ReferenceLocation location, Solution solution, CancellationToken cancellationToken)
            {
                // We won't try to update references in source generated files; we'll assume the generator will rerun
                // and produce an updated document with the new name.
                if (location.Document is SourceGeneratedDocument)
                {
                    return(SpecializedCollections.EmptyEnumerable <RenameLocation>());
                }

                var shouldIncludeSymbol = await ShouldIncludeSymbolAsync(referencedSymbol, originalSymbol, solution, true, cancellationToken).ConfigureAwait(false);

                if (!shouldIncludeSymbol)
                {
                    return(SpecializedCollections.EmptyEnumerable <RenameLocation>());
                }

                // Implicit references are things like a foreach referencing GetEnumerator. We don't
                // want to consider those as part of the set
                if (location.IsImplicit)
                {
                    return(SpecializedCollections.EmptyEnumerable <RenameLocation>());
                }

                var results = new List <RenameLocation>();

                // If we were originally naming an alias, then we'll only use the location if was
                // also bound through the alias
                if (originalSymbol.Kind == SymbolKind.Alias)
                {
                    if (originalSymbol.Equals(location.Alias))
                    {
                        results.Add(new RenameLocation(location, location.Document.Id));

                        // We also need to add the location of the alias
                        // itself
                        var aliasLocation = location.Alias.Locations.Single();
                        Contract.ThrowIfNull(aliasLocation.SourceTree);
                        results.Add(new RenameLocation(aliasLocation, solution.GetRequiredDocument(aliasLocation.SourceTree).Id));
                    }
                }
                else
                {
                    // If we bound through an alias, we'll only rename if the alias's name matches
                    // the name of symbol it points to. We do this because it's common to see things
                    // like "using Goo = System.Goo" where people want to import a single type
                    // rather than a whole namespace of stuff.
                    if (location.Alias != null)
                    {
                        if (location.Alias.Name == referencedSymbol.Name)
                        {
                            results.Add(new RenameLocation(location.Location, location.Document.Id,
                                                           candidateReason: location.CandidateReason, isRenamableAliasUsage: true, isWrittenTo: location.IsWrittenTo));

                            // We also need to add the location of the alias itself
                            var aliasLocation = location.Alias.Locations.Single();
                            Contract.ThrowIfNull(aliasLocation.SourceTree);
                            results.Add(new RenameLocation(aliasLocation, solution.GetRequiredDocument(aliasLocation.SourceTree).Id));
                        }
                    }
                    else if (location.ContainingStringLocation != Location.None)
                    {
                        // Location within a string
                        results.Add(new RenameLocation(
                                        location.Location,
                                        location.Document.Id,
                                        containingLocationForStringOrComment: location.ContainingStringLocation.SourceSpan));
                    }
                    else
                    {
                        // The simple case, so just the single location and we're done
                        results.Add(new RenameLocation(
                                        location.Location,
                                        location.Document.Id,
                                        isWrittenTo: location.IsWrittenTo,
                                        candidateReason: location.CandidateReason,
                                        isRenamableAccessor: await IsPropertyAccessorOrAnOverrideAsync(referencedSymbol, solution, cancellationToken).ConfigureAwait(false)));
                    }
                }

                return(results);
            }
Esempio n. 42
0
 private static async Task <LSP.InitializeResult> RunInitializeAsync(Solution solution, LSP.InitializeParams request)
 => await GetLanguageServer(solution).ExecuteRequestAsync <LSP.InitializeParams, LSP.InitializeResult>(LSP.Methods.InitializeName,
                                                                                                       solution, request, new LSP.ClientCapabilities(), null, CancellationToken.None);
Esempio n. 43
0
            private static async Task <bool> ShouldIncludeSymbolAsync(
                ISymbol referencedSymbol, ISymbol originalSymbol, Solution solution, bool considerSymbolReferences, CancellationToken cancellationToken)
            {
                if (referencedSymbol.IsPropertyAccessor())
                {
                    return(considerSymbolReferences);
                }

                if (referencedSymbol.Equals(originalSymbol))
                {
                    return(true);
                }

                // Parameters of properties and methods can cascade to each other in
                // indexer scenarios.
                if (originalSymbol.Kind == SymbolKind.Parameter && referencedSymbol.Kind == SymbolKind.Parameter)
                {
                    return(true);
                }

                // If the original symbol is a property, cascade to the backing field
                if (referencedSymbol.Kind == SymbolKind.Field && originalSymbol.Equals(((IFieldSymbol)referencedSymbol).AssociatedSymbol))
                {
                    return(true);
                }

                // If the symbol doesn't actually exist in source, we never want to rename it
                if (referencedSymbol.IsImplicitlyDeclared)
                {
                    return(considerSymbolReferences);
                }

                // We can cascade from members to other members only if the names match. The example
                // where the names might be different is explicit interface implementations in
                // Visual Basic and VB's identifiers are case insensitive.
                // Do not cascade to symbols that are defined only in metadata.
                if (referencedSymbol.Kind == originalSymbol.Kind &&
                    string.Compare(TrimNameToAfterLastDot(referencedSymbol.Name), TrimNameToAfterLastDot(originalSymbol.Name), StringComparison.OrdinalIgnoreCase) == 0 &&
                    referencedSymbol.Locations.Any(loc => loc.IsInSource))
                {
                    return(true);
                }

                // If the original symbol is an alias, then the referenced symbol will be where we
                // actually see references.
                if (originalSymbol.Kind == SymbolKind.Alias)
                {
                    var target = ((IAliasSymbol)originalSymbol).Target;

                    switch (target)
                    {
                    case INamedTypeSymbol nt:
                        return(nt.ConstructedFrom.Equals(referencedSymbol) ||
                               IsConstructorForType(possibleConstructor: referencedSymbol, possibleType: nt));

                    case INamespaceOrTypeSymbol s:
                        return(s.Equals(referencedSymbol));

                    default: return(false);
                    }
                }

                // cascade from property accessor to property (someone in C# renames base.get_X, or the accessor override)
                if (await IsPropertyAccessorOrAnOverrideAsync(referencedSymbol, solution, cancellationToken).ConfigureAwait(false) ||
                    await IsPropertyAccessorOrAnOverrideAsync(originalSymbol, solution, cancellationToken).ConfigureAwait(false))
                {
                    return(true);
                }

                // cascade from constructor to named type
                if (IsConstructorForType(possibleConstructor: referencedSymbol, possibleType: originalSymbol))
                {
                    return(true);
                }

                if (referencedSymbol.ContainingSymbol != null &&
                    referencedSymbol.ContainingSymbol.Kind == SymbolKind.NamedType &&
                    ((INamedTypeSymbol)referencedSymbol.ContainingSymbol).TypeKind == TypeKind.Interface &&
                    !originalSymbol.ExplicitInterfaceImplementations().Any(s => s.Equals(referencedSymbol)))
                {
                    return(true);
                }

                return(false);
Esempio n. 44
0
            /// <summary>
            /// Given a symbol, finds the symbol that actually defines the name that we're using.
            /// </summary>
            public static async Task <ISymbol> FindDefinitionSymbolAsync(
                ISymbol symbol, Solution solution, CancellationToken cancellationToken)
            {
                Contract.ThrowIfNull(symbol);
                Contract.ThrowIfNull(solution);

                // Make sure we're on the original source definition if we can be
                var foundSymbol = await SymbolFinder.FindSourceDefinitionAsync(
                    symbol, solution, cancellationToken).ConfigureAwait(false);

                var bestSymbol = foundSymbol ?? symbol;

                symbol = bestSymbol;

                // If we're renaming a property, it might be a synthesized property for a method
                // backing field.
                if (symbol.Kind == SymbolKind.Parameter)
                {
                    if (symbol.ContainingSymbol.Kind == SymbolKind.Method)
                    {
                        var containingMethod = (IMethodSymbol)symbol.ContainingSymbol;
                        if (containingMethod.AssociatedSymbol is IPropertySymbol)
                        {
                            var associatedPropertyOrEvent = (IPropertySymbol)containingMethod.AssociatedSymbol;
                            var ordinal = containingMethod.Parameters.IndexOf((IParameterSymbol)symbol);
                            if (ordinal < associatedPropertyOrEvent.Parameters.Length)
                            {
                                return(associatedPropertyOrEvent.Parameters[ordinal]);
                            }
                        }
                    }
                }

                // if we are renaming a compiler generated delegate for an event, cascade to the event
                if (symbol.Kind == SymbolKind.NamedType)
                {
                    var typeSymbol = (INamedTypeSymbol)symbol;
                    if (typeSymbol.IsImplicitlyDeclared && typeSymbol.IsDelegateType() && typeSymbol.AssociatedSymbol != null)
                    {
                        return(typeSymbol.AssociatedSymbol);
                    }
                }

                // If we are renaming a constructor or destructor, we wish to rename the whole type
                if (symbol.Kind == SymbolKind.Method)
                {
                    var methodSymbol = (IMethodSymbol)symbol;
                    if (methodSymbol.MethodKind is MethodKind.Constructor or
                        MethodKind.StaticConstructor or
                        MethodKind.Destructor)
                    {
                        return(methodSymbol.ContainingType);
                    }
                }

                // If we are renaming a backing field for a property, cascade to the property
                if (symbol.Kind == SymbolKind.Field)
                {
                    var fieldSymbol = (IFieldSymbol)symbol;
                    if (fieldSymbol.IsImplicitlyDeclared &&
                        fieldSymbol.AssociatedSymbol.IsKind(SymbolKind.Property))
                    {
                        return(fieldSymbol.AssociatedSymbol);
                    }
                }

                // in case this is e.g. an overridden property accessor, we'll treat the property itself as the definition symbol
                var property = await TryGetPropertyFromAccessorOrAnOverrideAsync(bestSymbol, solution, cancellationToken).ConfigureAwait(false);

                return(property ?? bestSymbol);
            }
Esempio n. 45
0
 public Task <IEnumerable <BreakpointResolutionResult> > ResolveBreakpointsAsync(
     Solution solution,
     string name,
     CancellationToken cancellationToken
     ) => new BreakpointResolver(solution, name).DoAsync(cancellationToken);
Esempio n. 46
0
            /// <summary>
            /// Given a ISymbol, returns the renameable locations for a given symbol.
            /// </summary>
            public static async Task <ImmutableArray <RenameLocation> > GetRenamableDefinitionLocationsAsync(
                ISymbol referencedSymbol, ISymbol originalSymbol, Solution solution, CancellationToken cancellationToken)
            {
                var shouldIncludeSymbol = await ShouldIncludeSymbolAsync(referencedSymbol, originalSymbol, solution, false, cancellationToken).ConfigureAwait(false);

                if (!shouldIncludeSymbol)
                {
                    return(ImmutableArray <RenameLocation> .Empty);
                }

                // Namespaces are definitions and references all in one. Since every definition
                // location is also a reference, we'll ignore it's definitions.
                if (referencedSymbol.Kind == SymbolKind.Namespace)
                {
                    return(ImmutableArray <RenameLocation> .Empty);
                }

                var results = ArrayBuilder <RenameLocation> .GetInstance();

                // If the original symbol was an alias, then the definitions will just be the
                // location of the alias, always
                if (originalSymbol.Kind == SymbolKind.Alias)
                {
                    var location = originalSymbol.Locations.Single();
                    AddRenameLocationIfNotGenerated(location);
                    return(results.ToImmutableAndFree());
                }

                var isRenamableAccessor = await IsPropertyAccessorOrAnOverrideAsync(referencedSymbol, solution, cancellationToken).ConfigureAwait(false);

                foreach (var location in referencedSymbol.Locations)
                {
                    if (location.IsInSource)
                    {
                        AddRenameLocationIfNotGenerated(location, isRenamableAccessor);
                    }
                }

                // If we're renaming a named type, we'll also have to find constructors and
                // destructors declarations that match the name
                if (referencedSymbol.Kind == SymbolKind.NamedType && referencedSymbol.Locations.All(l => l.IsInSource))
                {
                    var firstLocation = referencedSymbol.Locations[0];
                    var syntaxFacts   = solution.GetRequiredDocument(firstLocation.SourceTree !)
                                        .GetRequiredLanguageService <ISyntaxFactsService>();

                    var namedType = (INamedTypeSymbol)referencedSymbol;
                    foreach (var method in namedType.GetMembers().OfType <IMethodSymbol>())
                    {
                        if (!method.IsImplicitlyDeclared && (method.MethodKind == MethodKind.Constructor ||
                                                             method.MethodKind == MethodKind.StaticConstructor ||
                                                             method.MethodKind == MethodKind.Destructor))
                        {
                            foreach (var location in method.Locations)
                            {
                                if (location.IsInSource)
                                {
                                    var token = location.FindToken(cancellationToken);
                                    if (!syntaxFacts.IsReservedOrContextualKeyword(token) &&
                                        token.ValueText == referencedSymbol.Name)
                                    {
                                        AddRenameLocationIfNotGenerated(location);
                                    }
                                }
                            }
                        }
                    }
                }

                return(results.ToImmutableAndFree());

                void AddRenameLocationIfNotGenerated(Location location, bool isRenamableAccessor = false)
                {
                    RoslynDebug.Assert(location.IsInSource);
                    var document = solution.GetRequiredDocument(location.SourceTree);

                    // If the location is in a source generated file, we won't rename it. Our assumption in this case is we
                    // have cascaded to this symbol from our original source symbol, and the generator will update this file
                    // based on the renamed symbol.
                    if (document is not SourceGeneratedDocument)
                    {
                        results.Add(new RenameLocation(location, document.Id, isRenamableAccessor: isRenamableAccessor));
                    }
                }
            }
        public override void ActivateMultipleItems()
        {
            Solution sol = CurrentNode.DataItem as Solution;

            IdeApp.ProjectOperations.ShowOptions(sol);
        }
Esempio n. 48
0
 public string NugetFolder(Solution solution)
 {
     return(ExplodedDirectory(solution.PackagesDirectory()));
 }
        public override bool HasChildNodes(ITreeBuilder builder, object dataObject)
        {
            Solution sol = (Solution)dataObject;

            return(sol.RootFolder.Items.Count > 0 || sol.RootFolder.Files.Count > 0);
        }
Esempio n. 50
0
 IPersistentStorage IPersistentStorageService.GetStorage(Solution solution)
 {
     return(_instance);
 }
        private void TryNavigateToLocationOrStartRenameSession(Workspace workspace, Solution oldSolution, Solution newSolution, CancellationToken cancellationToken)
        {
            var changedDocuments = newSolution.GetChangedDocuments(oldSolution);
            foreach (var documentId in changedDocuments)
            {
                var document = newSolution.GetDocument(documentId);
                if (!document.SupportsSyntaxTree)
                {
                    continue;
                }

                var root = document.GetSyntaxRootSynchronously(cancellationToken);

                var navigationTokenOpt = root.GetAnnotatedTokens(NavigationAnnotation.Kind)
                                             .FirstOrNullable();
                if (navigationTokenOpt.HasValue)
                {
                    var navigationService = workspace.Services.GetService<IDocumentNavigationService>();
                    navigationService.TryNavigateToPosition(workspace, documentId, navigationTokenOpt.Value.SpanStart);
                    return;
                }

                var renameTokenOpt = root.GetAnnotatedTokens(RenameAnnotation.Kind)
                                         .FirstOrNullable();

                if (renameTokenOpt.HasValue)
                {
                    // It's possible that the workspace's current solution is not the same as
                    // newSolution. This can happen if the workspace host performs other edits
                    // during ApplyChanges, such as in the Venus scenario where indentation and
                    // formatting can happen. To work around this, we create a SyntaxPath to the
                    // rename token in the newSolution and resolve it to the current solution.

                    var pathToRenameToken = new SyntaxPath(renameTokenOpt.Value);
                    var latestDocument = workspace.CurrentSolution.GetDocument(documentId);
                    var latestRoot = latestDocument.GetSyntaxRootSynchronously(cancellationToken);
                    if (pathToRenameToken.TryResolve(latestRoot, out var resolvedRenameToken) &&
                        resolvedRenameToken.IsToken)
                    {
                        var editorWorkspace = workspace;
                        var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
                        if (navigationService.TryNavigateToSpan(editorWorkspace, documentId, resolvedRenameToken.Span))
                        {
                            var openDocument = workspace.CurrentSolution.GetDocument(documentId);
                            var openRoot = openDocument.GetSyntaxRootSynchronously(cancellationToken);

                            // NOTE: We need to resolve the syntax path again in case VB line commit kicked in
                            // due to the navigation.

                            // TODO(DustinCa): We still have a potential problem here with VB line commit,
                            // because it can insert tokens and all sorts of other business, which could
                            // wind up with us not being able to resolve the token.
                            if (pathToRenameToken.TryResolve(openRoot, out resolvedRenameToken) &&
                                resolvedRenameToken.IsToken)
                            {
                                var snapshot = openDocument.GetTextSynchronously(cancellationToken).FindCorrespondingEditorTextSnapshot();
                                if (snapshot != null)
                                {
                                    _renameService.StartInlineSession(openDocument, resolvedRenameToken.AsToken().Span, cancellationToken);
                                }
                            }
                        }
                    }

                    return;
                }
            }
        }
        public override void RenameItem(string newName)
        {
            Solution sol = (Solution)CurrentNode.DataItem;

            IdeApp.ProjectOperations.RenameItem(sol, newName);
        }
Esempio n. 53
0
    public void Solve(ReadOnlySpan <byte> input, Solution solution)
    {
        int width  = input.IndexOf((byte)'\n');
        int height = input.Length / (width + 1);

        //int ulongsPerRow = (width + 63) / 64;
        const int    ulongsPerRow     = 3;
        int          countInLastUlong = width % 64;
        ulong        lastUlongMask    = (1UL << countInLastUlong) - 1;
        Span <ulong> easts            = stackalloc ulong[ulongsPerRow * height];
        Span <ulong> souths           = stackalloc ulong[ulongsPerRow * height];

        for (int row = 0; row < height; row++)
        {
            ReadOnlySpan <byte> rowInput  = input.Slice(row * (width + 1), width);
            Span <ulong>        eastData  = easts.Slice(row * ulongsPerRow, ulongsPerRow);
            Span <ulong>        southData = souths.Slice(row * ulongsPerRow, ulongsPerRow);
            for (int col = 0; col < width; col++)
            {
                byte c = rowInput[col];
                if (c == '>')
                {
                    eastData[col / 64] |= 1UL << (col % 64);
                }
                else if (c == 'v')
                {
                    southData[col / 64] |= 1UL << (col % 64);
                }
            }
        }

        int steps = 0;

        while (true)
        {
            bool containsMove = false;

            // move all east-facing cucumbers
            for (int row = 0; row < height; row++)
            {
                Span <ulong> eastData  = easts.Slice(row * ulongsPerRow, ulongsPerRow);
                Span <ulong> southData = souths.Slice(row * ulongsPerRow, ulongsPerRow);

                ulong e1 = eastData[0];
                ulong e2 = eastData[1];
                ulong e3 = eastData[2];

                ulong combined1 = e1 | southData[0];
                ulong combined2 = e2 | southData[1];
                ulong combined3 = e3 | southData[2];

                ulong lastE3 = e3 >> (countInLastUlong - 1);
                e3 = (e3 << 1 | e2 >> 63) & lastUlongMask;
                e2 = e2 << 1 | e1 >> 63;
                e1 = e1 << 1 | lastE3;

                ulong overlap1 = e1 & combined1;
                ulong overlap2 = e2 & combined2;
                ulong overlap3 = e3 & combined3;

                if (overlap1 != e1 || overlap2 != e2 || overlap3 != e3)
                {
                    containsMove = true;
                }

                eastData[0] = (e1 ^ overlap1) | (overlap1 >> 1) | (overlap2 << 63);
                eastData[1] = (e2 ^ overlap2) | (overlap2 >> 1) | (overlap3 << 63);
                eastData[2] = (e3 ^ overlap3) | (overlap3 >> 1) | ((overlap1 & 1) << (countInLastUlong - 1));
            }

            // Cache the last row data so it can be used again for the end
            Span <ulong> lastRowSouthData = souths.Slice((height - 1) * ulongsPerRow, ulongsPerRow);
            ulong        lastRowS1        = lastRowSouthData[0];
            ulong        lastRowS2        = lastRowSouthData[1];
            ulong        lastRowS3        = lastRowSouthData[2];
            lastRowSouthData.Clear();

            // move all south-facing cucumbers
            Span <ulong> nextRowSouthData = lastRowSouthData;
            ulong        nextRowS1        = lastRowS1;
            ulong        nextRowS2        = lastRowS2;
            ulong        nextRowS3        = lastRowS3;
            for (int row = height - 2; row >= 0; row--)
            {
                Span <ulong> nextRowEastData = easts.Slice((row + 1) * ulongsPerRow, ulongsPerRow);
                Span <ulong> southData       = souths.Slice(row * ulongsPerRow, ulongsPerRow);

                ulong s1 = southData[0];
                ulong s2 = southData[1];
                ulong s3 = southData[2];

                ulong overlap1 = s1 & (nextRowEastData[0] | nextRowS1);
                ulong overlap2 = s2 & (nextRowEastData[1] | nextRowS2);
                ulong overlap3 = s3 & (nextRowEastData[2] | nextRowS3);

                if (overlap1 != s1 || overlap2 != s2 || overlap3 != s3)
                {
                    containsMove = true;
                }

                nextRowSouthData[0] |= s1 ^ overlap1;
                nextRowSouthData[1] |= s2 ^ overlap2;
                nextRowSouthData[2] |= s3 ^ overlap3;

                southData[0] = overlap1;
                southData[1] = overlap2;
                southData[2] = overlap3;

                nextRowS1        = s1;
                nextRowS2        = s2;
                nextRowS3        = s3;
                nextRowSouthData = southData;
            }

            // Fix the last row
            {
                ulong overlap1 = lastRowS1 & (easts[0] | nextRowS1);
                ulong overlap2 = lastRowS2 & (easts[1] | nextRowS2);
                ulong overlap3 = lastRowS3 & (easts[2] | nextRowS3);

                if (overlap1 != lastRowS1 || overlap2 != lastRowS2 || overlap3 != lastRowS3)
                {
                    containsMove = true;
                }

                nextRowSouthData[0] |= lastRowS1 ^ overlap1;
                nextRowSouthData[1] |= lastRowS2 ^ overlap2;
                nextRowSouthData[2] |= lastRowS3 ^ overlap3;

                lastRowSouthData[0] |= overlap1;
                lastRowSouthData[1] |= overlap2;
                lastRowSouthData[2] |= overlap3;
            }

            steps++;

            if (!containsMove)
            {
                break;
            }
        }

        solution.SubmitPart1(steps);
        solution.SubmitPart2(string.Empty);
    }
Esempio n. 54
0
        private static async Task <List <INamedTypeSymbol> > GetDeclaredTypeSymbolsAsync(Solution solution, ProjectId projectId, DocumentId documentId)
        {
            var document   = solution.GetDocument(documentId);
            var syntaxTree = await document.GetSyntaxTreeAsync();

            var typeDeclarationSyntaxNodes = (await syntaxTree.GetRootAsync()).DescendantNodes().OfType <TypeDeclarationSyntax>();

            var project     = solution.GetProject(projectId);
            var compilation = await project.GetCompilationAsync();

            var semanticModel = compilation.GetSemanticModel(syntaxTree);

            return(typeDeclarationSyntaxNodes.Select(i => semanticModel.GetDeclaredSymbol(i)).OfType <INamedTypeSymbol>().ToList());
        }
Esempio n. 55
0
 /// <summary>
 /// Create <see cref="RemoteHostClient.Session"/> for the <paramref name="serviceName"/> if possible.
 /// otherwise, return null.
 ///
 /// Creating session could fail if remote host is not available. one of example will be user killing
 /// remote host.
 /// </summary>
 public Task <Session> TryCreateServiceSessionAsync(string serviceName, Solution solution, CancellationToken cancellationToken)
 {
     return(TryCreateServiceSessionAsync(serviceName, solution, callbackTarget: null, cancellationToken: cancellationToken));
 }
        private TextDocument TryGetSingleChangedText(
            Solution oldSolution, ImmutableArray<CodeActionOperation> operationsList)
        {
            Debug.Assert(operationsList.Length > 0);
            if (operationsList.Length > 1)
            {
                return null;
            }

            var applyOperation = operationsList.Single() as ApplyChangesOperation;
            if (applyOperation == null)
            {
                return null;
            }

            var newSolution = applyOperation.ChangedSolution;
            var changes = newSolution.GetChanges(oldSolution);

            if (changes.GetAddedProjects().Any() ||
                changes.GetRemovedProjects().Any())
            {
                return null;
            }

            var projectChanges = changes.GetProjectChanges().ToImmutableArray();
            if (projectChanges.Length != 1)
            {
                return null;
            }

            var projectChange = projectChanges.Single();
            if (projectChange.GetAddedAdditionalDocuments().Any() ||
                projectChange.GetAddedAnalyzerReferences().Any() ||
                projectChange.GetAddedDocuments().Any() ||
                projectChange.GetAddedMetadataReferences().Any() ||
                projectChange.GetAddedProjectReferences().Any() ||
                projectChange.GetRemovedAdditionalDocuments().Any() ||
                projectChange.GetRemovedAnalyzerReferences().Any() ||
                projectChange.GetRemovedDocuments().Any() ||
                projectChange.GetRemovedMetadataReferences().Any() ||
                projectChange.GetRemovedProjectReferences().Any())
            {
                return null;
            }

            var changedAdditionalDocuments = projectChange.GetChangedAdditionalDocuments().ToImmutableArray();
            var changedDocuments = projectChange.GetChangedDocuments().ToImmutableArray();

            if (changedAdditionalDocuments.Length + changedDocuments.Length != 1)
            {
                return null;
            }

            if (changedDocuments.Any(id => newSolution.GetDocument(id).HasInfoChanged(oldSolution.GetDocument(id))) ||
                changedAdditionalDocuments.Any(id => newSolution.GetDocument(id).HasInfoChanged(oldSolution.GetDocument(id))))
            {
                return null;
            }

            return changedDocuments.Length == 1
                ? oldSolution.GetDocument(changedDocuments[0])
                : oldSolution.GetAdditionalDocument(changedAdditionalDocuments[0]);
        }
Esempio n. 57
0
        private static async Task <TypeDeclarationSyntax> GetRootTypeDeclarationAsync(Solution currentSnapshot)
        {
            var tree = await currentSnapshot.Projects.First().Documents.First().GetSyntaxTreeAsync();

            var root = (CompilationUnitSyntax)tree.GetRoot();
            var type = (TypeDeclarationSyntax)root.Members[0];

            return(type);
        }
Esempio n. 58
0
        // recursively search our dictionary for a given 'currentWord', with a given 'starting distance' (depth, or cost if you like),
        // building up a solution in 'currentSolution'. When a successful solution is found, it's added to the list in scenario.
        private void WordDepthSolver(
//            Puzzle scenario,
            string currentWord,
            int currentDepth,
            List <string> currentSolution
            )
        {
            Console.WriteLine($"looking at {currentWord}, {currentDepth}");

            CheckedWords.Add(currentWord);
            currentSolution.Add(currentWord);


            // found the word?
            if (currentWord == EndWord)
            {
                // add the current working solution to the overall list of solutions
                Solution <string> thisList = new Solution <string>();
                thisList.AddRange(currentSolution);
                Solutions.Add(thisList);
            }
            // are we still in range
            else if (currentDepth > 0 && DepthDict[currentWord] < currentDepth)
            {
                char[] letters = currentWord.ToCharArray();

                // create and choose a fake word as before.. so, for each letter-place in the word
                for (int i = 0; i < WordLength; i++)
                {
                    // we're going to swap a letter out as before, but we need to put it back later
                    char replacedLetter = letters[i];
                    // for each possible letter this could become
                    for (int nextLetter = 'a'; nextLetter <= 'z'; nextLetter++)
                    {
                        // obviously not the letter it already is
                        if (letters[i] != nextLetter)
                        {
                            // swap in the new letter, make the fake word
                            letters[i] = (char)nextLetter;
                            string fakeWord = new string(letters);

                            // if we've just made a valid word, and we haven't visited it yet
                            // setup and run the process from this word
                            if (WordList.Contains(fakeWord) && !CheckedWords.Contains(fakeWord))
                            {
                                WordDepthSolver(
                                    //scenario,
                                    fakeWord,         // new word to solve for
                                    currentDepth - 1, // because we will be 1 word further from the currentword
                                    currentSolution);
                            }
                        }
                    }

                    letters[i] = replacedLetter; // restore the overwritten char
                }
            }

            // remove this (last word) from our current solution
            currentSolution.RemoveAt(currentSolution.Count - 1);

            // don't forget to take this back off our visited list, ready for next use
            CheckedWords.Remove(currentWord);
        }
Esempio n. 59
0
        static void Main(string[] args)
        {
            //long beginningTime = System.nanoTime();
            Cube myRubik = new Cube();

            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.LEFT, Direction.CW);
            myRubik.rotateFace(Face.FRONT, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.LEFT, Direction.CW);
            myRubik.rotateFace(Face.FRONT, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.LEFT, Direction.CW);
            myRubik.rotateFace(Face.FRONT, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.LEFT, Direction.CW);
            myRubik.rotateFace(Face.FRONT, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.LEFT, Direction.CW);
            myRubik.rotateFace(Face.FRONT, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.LEFT, Direction.CW);
            myRubik.rotateFace(Face.FRONT, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.LEFT, Direction.CW);
            myRubik.rotateFace(Face.FRONT, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            myRubik.rotateFace(Face.BACK, Direction.CW);
            myRubik.rotateFace(Face.LEFT, Direction.CW);
            myRubik.rotateFace(Face.FRONT, Direction.CW);
            myRubik.rotateFace(Face.RIGHT, Direction.CW);
            Solver mySolver = new Solver();


            RubikFileReader readFirstFloor  = new RubikFileReader("..\\..\\..\\Resources\\FirstFloor.txt");
            RubikFileReader readSecondFloor = new RubikFileReader("..\\..\\..\\Resources\\SecondFloor.txt");
            RubikFileReader readThirdFloor  = new RubikFileReader("..\\..\\..\\Resources\\ThirdFloor.txt");


            RotationTree firstFloorTree  = RotationTree.getRotationTreeFromFile(readFirstFloor);
            RotationTree secondFloorTree = RotationTree.getRotationTreeFromFile(readSecondFloor);
            RotationTree thirdFloorTree  = RotationTree.getRotationTreeFromFile(readThirdFloor);

            Solution mySolution = mySolver.solve(myRubik, firstFloorTree, secondFloorTree, thirdFloorTree);

            mySolution.applyToRubik(myRubik);
            mySolution.print();

            if (myRubik.equals(new Cube()))
            {
                Console.WriteLine("Solved!");
            }
            else
            {
                Console.WriteLine("Not Solved :-(");
            }
            Console.ReadLine();
        }
Esempio n. 60
0
            private IVsDebugName CreateDebugName(BreakpointResolutionResult breakpoint, Solution solution, CancellationToken cancellationToken)
            {
                var document = breakpoint.Document;
                var filePath = _languageService.Workspace.GetFilePath(document.Id);
                var text     = document.GetTextSynchronously(cancellationToken);
                var span     = text.GetVsTextSpanForSpan(breakpoint.TextSpan);

                // If we're inside an Venus code nugget, we need to map the span to the surface buffer.
                // Otherwise, we'll just use the original span.
                if (!span.TryMapSpanFromSecondaryBufferToPrimaryBuffer(solution.Workspace, document.Id, out var mappedSpan))
                {
                    mappedSpan = span;
                }

                return(new VsDebugName(breakpoint.LocationNameOpt, filePath, mappedSpan));
            }