public ExpressionCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) : base(insertionPoint, selectionResult, analyzerResult) { }
public SingleStatementCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) : base(insertionPoint, selectionResult, analyzerResult) { }
public static StockRepositoryTestFixture Create() { var mockDbContext = new Mock <AnalyzerDbContext>(); var processor = new StockProcessorTestFixture(mockDbContext, new StockLoaderTestFixture()) { LoadCompactAsyncResult = AnalyzerResult.Sucess(), LoadFullAsyncResult = AnalyzerResult.Sucess() }; return(new StockRepositoryTestFixture(mockDbContext, processor)); }
protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) : base(insertionPoint, selectionResult, analyzerResult) { Contract.ThrowIfFalse(this.SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(this.MethodNameAnnotation); }
/// <summary> /// Checks <see cref="AnalyzerResult.FileOutput"/> for certain strings. /// Only the file output of the execution analyzer executable is checked. /// Use <see cref="AssertPipMiss(AnalyzerResult, Pip, PipCacheMissType, string[])"/> to additionally /// test runtime cache miss analysis output. /// </summary> /// <note> /// This is highly inefficient since it does a full pass over the /// output file for every assertion. /// </note> public static AnalyzerResult AssertAnalyzerOutput( this AnalyzerResult result, params string[] messages) { foreach (var message in messages) { XAssert.IsTrue(result.FileOutput.Contains(message), "Expected message: \"{0}\" to appear in analyzer output: \"{1}\"", message, result.FileOutput); } return(result); }
/// <summary> /// Gets a Roslyn workspace for the analyzed results. /// </summary> /// <param name="analyzerResult">The results from building a Buildalyzer project analyzer.</param> /// <param name="addProjectReferences"> /// <c>true</c> to add projects to the workspace for project references that exist in the same <see cref="AnalyzerManager"/>. /// If <c>true</c> this will trigger (re)building all referenced projects. Directly add <see cref="AnalyzerResult"/> instances instead if you already have them available. /// </param> /// <returns>A Roslyn workspace.</returns> public static AdhocWorkspace GetWorkspace(this AnalyzerResult analyzerResult, bool addProjectReferences = false) { if (analyzerResult == null) { throw new ArgumentNullException(nameof(analyzerResult)); } AdhocWorkspace workspace = new AdhocWorkspace(); analyzerResult.AddToWorkspace(workspace, addProjectReferences); return(workspace); }
protected async Task <AnalyzerResult> LoadAsync(string ticker, string outputSize) { ticker = ticker.ToUpperInvariant(); var stock = await _dbContext.Stocks.FirstOrDefaultAsync(s => s.Id == ticker); var initialStockLoad = false; if (stock == null) { stock = _dbContext.Stocks.Add(new Stock() { Id = ticker, MinDate = DateTime.MaxValue, MaxDate = DateTime.MinValue }); initialStockLoad = true; } if (stock.MaxDate == DateTime.Today.AddDays(-1) && !IsMarketClosed) { return(AnalyzerResult.Sucess()); } var test = 0; try { var quotes = await _loader.LoadAsync(ticker, outputSize); foreach (var quote in quotes.OrderBy(s => s.Date).Where(q => initialStockLoad || q.Date <stock.MinDate || q.Date.Date> stock.MaxDate.Date)) { if (quote.Date == DateTime.Today && !IsMarketClosed) { continue; } _dbContext.StockQuotes.Add(quote); test++; stock.MinDate = stock.MinDate > quote.Date ? quote.Date : stock.MinDate; stock.MaxDate = stock.MaxDate < quote.Date ? quote.Date : stock.MaxDate; } } catch (Exception e) { return(AnalyzerResult.Fail(e.Message)); } stock.LastLoadDate = DateTime.UtcNow; await _dbContext.SaveChangesAsync(); return(AnalyzerResult.Sucess()); }
public static Task <GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, bool localFunction, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult, localFunction); return(codeGenerator.GenerateAsync(cancellationToken)); }
/// <summary> /// Checks <see cref="AnalyzerResult.FileOutput"/> for correct analysis on a pip cache miss. /// Only the file output of the execution analyzer executable is checked. /// Use <see cref="AssertPipMiss(AnalyzerResult, Pip, PipCacheMissType, string[])"/> to additionally /// test runtime cache miss analysis output. /// </summary> /// <param name="pip">The expected pip that had a miss.</param> /// <param name="missType">The expected <see cref="PipCacheMissType"/>.</param> /// <param name="messages">Expected messages to be printed.</param> /// <note> /// This is highly inefficient since it does a full pass over the /// output file for every assertion. /// </note> public static AnalyzerResult AssertAnalyzerPipMiss( this AnalyzerResult result, Pip pip, PipCacheMissType missType, params string[] messages) { result.AssertSuccess(); AssertAnalyzerOutput(result, pip.FormattedSemiStableHash, missType.ToString()); return(AssertAnalyzerOutput(result, messages)); }
/// <summary> /// Determines if a project is a CoreWCF Compatible Config based Service based on the following :- /// If it has a web.config or App.config based configuaration, and has a service tag /// in the nested configuration/system.serviceModel tag. /// The service should also have atleast one binding and transport mode compatible with CoreWCF. /// </summary> /// <param name="analyzerResult"></param> /// <returns>Whether a project is a CoreWCF Compatible Config based Service or not</returns> public override bool IsPresent(AnalyzerResult analyzerResult) { if (!IsWCFConfigService(analyzerResult)) { return(false); } Dictionary <string, BindingConfiguration> bindingsTransportMap = WCFBindingAndTransportUtil.GetBindingAndTransport(analyzerResult); return(CoreWCFParityCheck.HasCoreWCFParity(bindingsTransportMap)); }
public ProjectAnalyzer(string inputProjectPath, AnalyzerResult analyzerResult, ProjectConfiguration projectConfiguration, ProjectResult projectResult) { _inputProjectPath = inputProjectPath; AnalyzerResult = analyzerResult; ProjectConfiguration = projectConfiguration; ProjectResult = projectResult; ProjectReferences = analyzerResult?.ProjectBuildResult?.ExternalReferences?.ProjectReferences.Select(p => p.AssemblyLocation).ToList(); MetaReferences = analyzerResult?.ProjectBuildResult?.Project?.MetadataReferences?.Select(m => m.Display).ToList(); }
/// <summary> /// Checks <see cref="AnalyzerResult.FileOutput"/> for certain strings. /// Only the file output of the execution analyzer executable is checked. /// Use <see cref="AssertPipMiss(AnalyzerResult, Pip, PipCacheMissType, string[])"/> to additionally /// test runtime cache miss analysis output. /// </summary> /// <note> /// This is highly inefficient since it does a full pass over the /// output file for every assertion. /// </note> public static AnalyzerResult AssertAnalyzerOutput( this AnalyzerResult result, params string[] messages) { foreach (var message in messages) { XAssert.IsTrue(result.FileOutput.ToUpperInvariant().Contains(ObservedInputConstants.ToExpandedString(message).ToUpperInvariant()), "Expected message: \"{0}\" to appear in analyzer output: \"{1}\"", ObservedInputConstants.ToExpandedString(message), result.FileOutput); } return(result); }
public override bool IsConditionMet(AnalyzerResult analyzerResult) { var directoryToSearch = SearchPath ?? analyzerResult?.ProjectResult.ProjectRootPath ?? string.Empty; var xmlFiles = FindFileNamePatternInDirectory(directoryToSearch); var filesWithAttributes = xmlFiles .Where(xmlFile => GetElementsInPath(XmlElementPath, xmlFile.Value) .Any(element => ContainsAllAttributes(element, XmlElementAttributes))) .Select(xmlFile => xmlFile.Key); return(filesWithAttributes.Any() == MatchType); }
private void ProjectFinished(object sender, ProjectFinishedEventArgs e) { // Make sure this is the same project, nested MSBuild tasks may have spawned additional builds of other projects if (AnalyzerManager.NormalizePath(e.ProjectFile) == _projectFilePath) { AnalyzerResult result = _currentResult.Pop(); if (result != null) { result.Succeeded = e.Succeeded; } } }
private bool DidPerformCoreCompile(AnalyzerResult result) { if (result == null) { return(false); } var sourceCount = result.SourceFiles?.Length ?? 0; var compilerInputs = result.GetCompileInputs()?.Length ?? 0; return(compilerInputs > 0 && sourceCount > 0); }
public ProjectResult RunProject(AnalyzerResult analyzerResult, PortCoreConfiguration portCoreConfiguration) { var projectPort = new ProjectPort(analyzerResult, portCoreConfiguration, this); portCoreConfiguration.AdditionalReferences.Add(Constants.ProjectRecommendationFile); var projectAnalysisResult = projectPort.AnalysisRun(); var projectResult = projectPort.Run(); _portSolutionResult.References.UnionWith(projectPort.ProjectReferences); AppendProjectResult(projectAnalysisResult, projectResult, analyzerResult, projectPort.ProjectTypeFeatureResults); return(projectResult); }
private void MessageRaised(object sender, BuildMessageEventArgs e) { // Process the command line arguments for the Csc task AnalyzerResult result = _currentResult.Count == 0 ? null : _currentResult.Peek(); if (result != null && e is TaskCommandLineEventArgs cmd && string.Equals(cmd.TaskName, "Csc", StringComparison.OrdinalIgnoreCase)) { result.ProcessCscCommandLine(cmd.CommandLine, _targetStack.Any(x => x.TargetName == "CoreCompile")); } }
protected internal static AnalyzerResult CompileProjectAndTrace(ProjectAnalyzer analyzer, StringWriter log) { log.GetStringBuilder().Clear(); AnalyzerResult result = analyzer.Build(); if (result.OverallSuccess == false) { Trace.Error($"Could not compile project at {analyzer.ProjectFile.Path}"); Trace.Warning(log.ToString()); return(null); } return(result); }
public ProjectRewriter GetInstance(AnalyzerResult analyzerResult, ProjectConfiguration projectConfiguration) { var projectType = projectConfiguration.ProjectType; var projectRewriter = projectType switch { ProjectType.WCFCodeBasedService => new WCFProjectRewriter(analyzerResult, projectConfiguration), ProjectType.WCFConfigBasedService => new WCFProjectRewriter(analyzerResult, projectConfiguration), ProjectType.WebForms => new WebFormsProjectRewriter(analyzerResult, projectConfiguration), _ => new ProjectRewriter(analyzerResult, projectConfiguration) }; return(projectRewriter); }
public CodeReplacer(List <SourceFileBuildResult> sourceFileBuildResults, ProjectConfiguration projectConfiguration, List <string> metadataReferences, AnalyzerResult analyzerResult, List <string> updatedFiles = null, ProjectResult projectResult = null) { _sourceFileBuildResults = sourceFileBuildResults; if (updatedFiles != null) { _sourceFileBuildResults = _sourceFileBuildResults.Where(s => updatedFiles.Contains(s.SourceFileFullPath)); } _analyzerResult = analyzerResult; _projectConfiguration = projectConfiguration; _metadataReferences = metadataReferences; _projectResult = projectResult ?? new ProjectResult(); }
public static Task <GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, CSharpCodeGenerationOptions options, NamingStylePreferencesProvider namingPreferences, bool localFunction, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult, options, namingPreferences, localFunction); return(codeGenerator.GenerateAsync(cancellationToken)); }
private AnalyzerResult GetWinner(Ranking rankBreakfast, Ranking rankLunch, Ranking rankDinner, Ranking rankDessert) { var meals = new Ranking[] { rankBreakfast, rankLunch, rankDinner, rankDessert }; var sorted = meals.OrderByDescending(m => m.Score).ToArray(); var firstPlace = sorted[0]; var difference = sorted[1].Score / sorted[0].Score; var secondPlace = difference > SecondPlaceDifferenceTolerance ? sorted[1] : null; var result = new AnalyzerResult(firstPlace.Type, secondPlace != null ? secondPlace.Type : Category.None); return(result); }
public void ParsesCscCommandLineSourceFiles(string commandLine, string[] sourceFiles) { // Given commandLine = Path.Combine("/", "Fizz", "Buzz", "csc.exe") + " " + "/noconfig /unsafe- /checked- /nowarn:1701,1702,1701,1702,1701,1702 /nostdlib+ /errorreport:prompt /warn:4 /define:TRACE;DEBUG;NETCOREAPP;NETCOREAPP2_1 " + commandLine; // When List <(string, string)> result = AnalyzerResult.ProcessCscCommandLine(commandLine); // Then result.Where(x => x.Item1 == null).Select(x => x.Item2).Skip(1).ShouldBe(sourceFiles); }
public void FilterSkippedPipNoFingerprint() { FileArtifact src = CreateSourceFile(); var pipBuilderA = this.CreatePipBuilder(new Operation[] { Operation.ReadFile(src), Operation.WriteFile(CreateOutputFileArtifact()) }); pipBuilderA.AddTags(Context.StringTable, "pipA"); Process pipA = SchedulePipBuilder(pipBuilderA).Process; // Create independent pipB var pipBuilderB = this.CreatePipBuilder(new Operation[] { Operation.ReadFile(src), Operation.WriteFile(CreateOutputFileArtifact()) }); pipBuilderB.AddTags(Context.StringTable, "pipB"); Process pipB = SchedulePipBuilder(pipBuilderB).Process; RunScheduler().AssertCacheMiss(pipA.PipId, pipB.PipId); Configuration.Filter = "tag='pipB'"; // filter graph to just pipB var buildA = RunScheduler().AssertCacheHit(pipB.PipId); Configuration.Filter = ""; // reset filter to default // Cause a miss on pipA and pipB File.WriteAllText(ArtifactToPrint(src), "asdf"); var buildB = RunScheduler().AssertCacheMiss(pipA.PipId, pipB.PipId); var messages = new string[] { ArtifactToPrint(src) }; AnalyzerResult result = RunAnalyzer(buildA, buildB); // Missing fingerprint for pipA because it was filtered out in last build result.AssertPipMiss( pipA, PipCacheMissType.MissForDescriptorsDueToWeakFingerprints, messages); // Normal analysis for pipB result.AssertPipMiss( pipB, PipCacheMissType.MissForDescriptorsDueToWeakFingerprints, messages); }
private async Task <AnalyzerResult> BuildProjectAsync(AnalyzerResult result) { if (result != null) { return(result); } using (await DirectoryAccessor.TryLockAsync()) { using (var operation = Log.OnEnterAndConfirmOnExit()) { try { operation.Info("Building package {name}", Name); await DotnetBuild(); operation.Info("Workspace built"); operation.Succeed(); } catch (Exception exception) { operation.Error("Exception building workspace", exception); throw; } var binLog = this.FindLatestBinLog(); if (binLog == null) { throw new InvalidOperationException("Failed to build"); } var results = await TryLoadAnalyzerResultsAsync(binLog); if (results?.Count == 0) { throw new InvalidOperationException("The build log seems to contain no solutions or projects"); } result = results?.FirstOrDefault(p => p.ProjectFilePath == _projectFile.FullName); if (result?.Succeeded == true) { return(result); } throw new InvalidOperationException("Failed to build"); } } }
public ProjectPort(AnalyzerResult analyzerResult, PortCoreConfiguration projectConfiguration, SolutionPort solutionPort, ILogger logger = null) { if (logger != null) { LogHelper.Logger = logger; } _solutionPort = solutionPort; ProjectReferences = new HashSet <string>() { Constants.ProjectRecommendationFile }; InitProjectRewriter(analyzerResult, projectConfiguration); }
public async Task StockRepository_GetStockWithChartVm_ByTake_Failed_FailedLoader() { var dataFixture = new StockDataFixture(); var processor = new StockProcessorTestFixture(); var repository = StockRepositoryFactory.Create(processor); repository.MockDbContext.Setup(s => s.StockQuotes).Returns(dataFixture.QuoteDataFixture.MockDataSet.Object); repository.MockDbContext.Setup(s => s.Stocks).Returns(dataFixture.MockDataSet.Object); processor.LoadCompactAsyncResult = AnalyzerResult.Fail("Failed to load."); var result = await repository.GetChartAsync("ticker", 30); Assert.IsNull(result); }
public void CommandLineChangeCacheMiss() { var outFile = CreateOutputFileArtifact(); var outOp = Operation.WriteFile(outFile, "hello.txt"); var pip = CreateAndSchedulePipBuilder(new Operation[] { outOp }).Process; RunScheduler().AssertCacheMiss(pip.PipId); // Reset the graph and re-schedule the same pip to verify // the generating pip Ids is stable across graphs and gets a cache hit ResetPipGraphBuilder(); var repeatPip = CreateAndSchedulePipBuilder(new Operation[] { outOp }).Process; XAssert.AreEqual(pip.PipId, repeatPip.PipId); var buildA = RunScheduler().AssertCacheHit(repeatPip.PipId); // Reset the graph and re-schedule the same pip but with an added command line arg ResetPipGraphBuilder(); var mismatchingPipBuilder = CreatePipBuilder(new Operation[] { outOp }); // Adds an argument to the test process' command line that won't crash the test process // and won't cause disallowed file access var nonExistentDir = CreateOutputDirectoryArtifact(); mismatchingPipBuilder.ArgumentsBuilder.Add(Operation.EnumerateDir(nonExistentDir).ToCommandLine(Context.PathTable)); var mismatchingPip = SchedulePipBuilder(mismatchingPipBuilder).Process; // Make sure the new argument didn't churn the pip id XAssert.AreEqual(pip.PipId, mismatchingPip.PipId); var buildB = RunScheduler().AssertCacheMiss(mismatchingPip.PipId); var messages = new string[] { "Arguments" }; AnalyzerResult result = RunAnalyzer(buildA, buildB).AssertPipMiss( mismatchingPip, PipCacheMissType.MissForDescriptorsDueToWeakFingerprints, messages); }
private IEnumerable <StatementSyntax> SplitOrMoveDeclarationIntoMethodDefinition( IEnumerable <StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = CreateDeclarationStatements(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return(declStatements.Concat(statements)); }
private Task <Workspace> BuildWorkspaceAsync(AnalyzerResult result) { if (result.TryGetWorkspace(out var ws)) { var projectId = ws.CurrentSolution.ProjectIds.FirstOrDefault(); var references = result.References; var metadataReferences = references.GetMetadataReferences(); var solution = ws.CurrentSolution; solution = solution.WithProjectMetadataReferences(projectId, metadataReferences); ws.TryApplyChanges(solution); return(Task.FromResult(ws)); } throw new InvalidOperationException("Failed creating workspace"); }
/// <summary> /// Determines that a project is an ASP.NET Core MVC project if: /// 1) Any class derived from the Controller abstract class also calls any method returning a view-related object /// AND /// 2) The project contains a non-empty Views directory /// </summary> /// <param name="analyzerResult"></param> /// <returns>Whether a project is an ASP.NET Core MVC project or not</returns> public override bool IsPresent(AnalyzerResult analyzerResult) { var project = analyzerResult.ProjectResult; var controllerClassDeclarations = project.GetClassDeclarationsByBaseType(Constants.NetCoreMvcControllerOriginalDefinition); var returnStatementsFromPublicMethods = controllerClassDeclarations.SelectMany(c => c.GetPublicMethodDeclarations()) .SelectMany(m => m.AllReturnStatements()); var viewObjectReturnTypes = returnStatementsFromPublicMethods .Where(r => Constants.NetCoreViewResultTypes.Contains(r.SemanticReturnType)); var isPresent = viewObjectReturnTypes.Any(); return(isPresent); }
protected CodeGenerator(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) { //Contract.ThrowIfFalse(insertionPoint.SemanticDocument == analyzerResult.SemanticDocument); this.InsertionPoint = insertionPoint; this.SemanticDocument = insertionPoint.SemanticDocument; this.SelectionResult = selectionResult; this.AnalyzerResult = analyzerResult; this.MethodNameAnnotation = new SyntaxAnnotation(); this.CallSiteAnnotation = new SyntaxAnnotation(); this.MethodDefinitionAnnotation = new SyntaxAnnotation(); }
protected abstract Task<GeneratedCode> GenerateCodeAsync(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzeResult, CancellationToken cancellationToken);
private async Task<OperationStatus> CheckVariableTypesAsync( OperationStatus status, AnalyzerResult analyzeResult, CancellationToken cancellationToken) { var document = analyzeResult.SemanticDocument; // sync selection result to same semantic data as analyzeResult var firstToken = this.OriginalSelectionResult.With(document).GetFirstTokenInSelection(); var context = firstToken.Parent; var result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), status, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.MethodParameters, result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToMoveOutToCallSite(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { return result.Item2; } } } } } status = result.Item2; var checkedStatus = await CheckTypeAsync(document.Document, context, context.GetLocation(), analyzeResult.ReturnType, cancellationToken).ConfigureAwait(false); return checkedStatus.With(status); }
protected override Task<MethodExtractor.GeneratedCode> GenerateCodeAsync(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzeResult, CancellationToken cancellationToken) { return CSharpCodeGenerator.GenerateAsync(insertionPoint, selectionResult, analyzeResult, cancellationToken); }