/// <summary> /// 加载配置文件 /// </summary> /// <returns></returns> public static Dictionary <string, string> loadConfig() { try { Dictionary <string, string> configContent = new Dictionary <string, string>(); StreamReader configReader = new StreamReader(CONFIG_PATH, Encoding.UTF8); string line = ""; string item = ""; string value = ""; while ((line = configReader.ReadLine()) != null) { item = CodeAnalysis.getCommandString(line); value = CodeAnalysis.getValueString(line)[0]; if (!string.IsNullOrEmpty(item) && !configContent.ContainsKey(item)) { configContent.Add(item, value); } } configReader.Close(); return(configContent); } catch (Exception e) { BugReport.report(e); return(null); } }
/// <summary> /// Returns true if the given class declaration is a P# machine. /// </summary> /// <param name="compilation">Compilation</param> /// <param name="classDecl">Class declaration</param> /// <returns>Boolean</returns> internal static bool IsMachine(CodeAnalysis.Compilation compilation, ClassDeclarationSyntax classDecl) { var result = false; if (classDecl.BaseList == null) { return result; } var model = compilation.GetSemanticModel(classDecl.SyntaxTree); var symbol = model.GetDeclaredSymbol(classDecl); while (true) { if (symbol.ToString() == typeof(Machine).FullName) { result = true; break; } else if (symbol.BaseType != null) { symbol = symbol.BaseType; continue; } break; } return result; }
public void AugmentQuickInfoSession(IQuickInfoSession session, IList <object> qiContent, out ITrackingSpan applicableToSpan) { try { Debug.WriteLine("AugmentQuickInfoSession Starts"); var subjectTriggerPoint = session.GetTriggerPoint(m_subjectBuffer.CurrentSnapshot); if (!subjectTriggerPoint.HasValue) { applicableToSpan = null; return; } var navigator = m_provider.NavigatorService.GetTextStructureNavigator(m_subjectBuffer); var extent = navigator.GetExtentOfWord(subjectTriggerPoint.Value); var symbol = CodeAnalysis.GetCurrentSymbol(extent.Span); if (symbol != null) { Current.Symbol = symbol; var lnkBtn = new LinkButton { FormCaption = symbol.OriginalDefinition.ToDisplayString(Microsoft.CodeAnalysis.SymbolDisplayFormat.FullyQualifiedFormat) }; qiContent.Insert(0, lnkBtn); } } catch (Exception err) { Debug.WriteLine(err.ToString() + new StackTrace(err).ToString()); } finally { applicableToSpan = null; } }
/// <summary> /// Initializes a new instance of <see cref="PrecompilationTagHelperTypeResolver"/>. /// </summary> /// <param name="compilation">The <see cref="CodeAnalysis.Compilation"/>.</param> public PrecompilationTagHelperTypeResolver(CodeAnalysis.Compilation compilation) { if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } _compilation = compilation; }
public static IEnumerable<ITypeSymbol> GetDirectTypesInCompilation(CodeAnalysis.Compilation compilation) { if (compilation == null) { throw new ArgumentNullException(nameof(compilation)); } var types = new List<ITypeSymbol>(); CollectTypes(compilation.Assembly.GlobalNamespace, types); return types; }
/// <summary> /// 接收服务器的消息时的处理 /// </summary> /// <param name="iar"></param> void receiveCallBack(IAsyncResult iar) { try { int REnd = ctrlSocket.EndReceive(iar); string receive_content = Encoding.ASCII.GetString(receiveByte, 0, REnd); Reporter.BugReport.reportFTPLog(receive_content); richTextBoxConsole.Invoke(new MethodInvoker(delegate { richTextBoxConsole.AppendText(DateTime.Now.ToString() + "\n" + receive_content + "\n"); })); /* PASSIVE模式传输文件,获取传输端口号 */ if (receive_content.Contains("227 Entering Passive Mode")) { int startIndex = receive_content.IndexOf('(') + 1; string param_s = receive_content.Substring(receive_content.IndexOf('(') + 1, receive_content.Length - startIndex - 3); /* * richTextBoxConsole.Invoke(new MethodInvoker(delegate * { * richTextBoxConsole.AppendText(DateTime.Now.ToString() + "\n" + param_s + "\n"); * }));*/ int num1 = int.Parse(CodeAnalysis.getValueString("port_param " + param_s)[4]); int num2 = int.Parse(CodeAnalysis.getValueString("port_param " + param_s)[5]); int dataPort = num1 * 256 + num2; richTextBoxConsole.Invoke(new MethodInvoker(delegate { richTextBoxConsole.AppendText(DateTime.Now.ToString() + "\n" + "get data port : " + dataPort.ToString() + "\n"); })); lock (ServerIP) { /* 启动数据传输进程 */ if (IsUpload) { CMDMethod.CMDComand.executeDataTransferProcess(ServerIP, dataPort, FileName); } else { CMDMethod.CMDComand.executeDataDownloadProcess(ServerIP, dataPort, FileName, FileSize); } } } /* 获取文件尺寸 */ else if (receive_content.Contains("213 ")) { FileSize = int.Parse(CodeAnalysis.getValueString(receive_content)[0]); } ctrlSocket.BeginReceive(receiveByte, 0, receiveByte.Length, 0, asyncCallback, null); } catch (Exception e) { BugReport.report(e); } }
public static CompilationResult GetAssemblyFromCompilation( IAssemblyLoadContext loader, CodeAnalysis.Compilation compilation) { EmitResult result; using (var ms = new MemoryStream()) { using (var pdb = new MemoryStream()) { if (PlatformHelper.IsMono) { result = compilation.Emit(ms, pdbStream: null); } else { result = compilation.Emit(ms, pdbStream: pdb); } if (!result.Success) { var formatter = new DiagnosticFormatter(); var errorMessages = result.Diagnostics .Where(IsError) .Select(d => formatter.Format(d)); return CompilationResult.FromErrorMessages(errorMessages); } ms.Seek(0, SeekOrigin.Begin); Assembly assembly; if (PlatformHelper.IsMono) { assembly = loader.LoadStream(ms, assemblySymbols: null); } else { pdb.Seek(0, SeekOrigin.Begin); assembly = loader.LoadStream(ms, pdb); } return CompilationResult.FromAssembly(assembly); } } }
public void Given_Null_Commits_Expect_Empty_List() { //---------------Arrange------------------ var authors = new List <Author>(); var context = new AnalysisContext { ReportRange = new Domain.Reporting.ReportingPeriod { Start = DateTime.Today.AddDays(-7), End = DateTime.Now } }; var sut = new CodeAnalysis(authors, null, context); //---------------Act---------------------- var actual = sut.Build_Stats(); //---------------Assert------------------- actual.CommitStats.Should().BeEmpty(); }
public void Given_Valid_Reporting_Context_Expect_Range_To_Transfer_To_Code_Stats() { //---------------Arrange------------------ var authors = new List <Author>(); var commits = new List <Commit>(); var context = new AnalysisContext { ReportRange = new Domain.Reporting.ReportingPeriod { Start = DateTime.Today.AddDays(-7), End = DateTime.Now } }; var sut = new CodeAnalysis(authors, commits, context); //---------------Act---------------------- var actual = sut.Build_Stats(); //---------------Assert------------------- actual.ReportingPeriod.Should().Be(context.ReportRange); }
public void Given_Valid_Commits_Expect_Transformation_To_Commit_Stats() { //---------------Arrange------------------ var authors = new List <Author>(); var commits = new List <Commit> { new Commit { Author = new Author { Name = "T-rav", Emails = new List <string> { "*****@*****.**" } }, When = DateTime.Now, Patch = new List <Patch> { new Patch { ChangeType = ChangeType.Modified, LinesAdded = 2, LinesRemoved = 0, Contents = "@@ 2,0 2,0 @@ namespace Test.Namespace \na\nb" } } } }; var context = new AnalysisContext { ReportRange = new Domain.Reporting.ReportingPeriod { Start = DateTime.Today.AddDays(-7), End = DateTime.Now } }; var sut = new CodeAnalysis(authors, commits, context); //---------------Act---------------------- var actual = sut.Build_Stats(); //---------------Assert------------------- var expected = new List <CommitStat> { new CommitStat(commits.First()) }; actual.CommitStats.Should().BeEquivalentTo(expected); }
public bool FLAG_SUCESS; // 是否搜索成功 /// <summary> /// 构造函数 /// </summary> /// <param name="mapPath">静态网格地图的文件路径</param> public MeshSearch(string mapPath) { if (!File.Exists(mapPath)) { return; } try { StreamReader mapReader = new StreamReader(mapPath, Encoding.Default); string line; line = mapReader.ReadLine();// 读取第一行文件信息,比如宽和高 string[] fileInfo = CodeAnalysis.getValueInCSV(line); if (fileInfo.Length < 2) { return; } uint width = uint.Parse(fileInfo[0]); uint height = uint.Parse(fileInfo[1]); MeshMap = new MeshNode[height, width];// 实例化网格地图 // 读取地图节点信息 string[] pointInfo; int rowIndex = 0;// 行索引 while ((line = mapReader.ReadLine()) != null) { pointInfo = CodeAnalysis.getValueInCSV(line); for (int columnIndex = 0; columnIndex < width; columnIndex++) { MeshMap[rowIndex, columnIndex] = new MeshNode(pointInfo[columnIndex] == "1"); MeshMap[rowIndex, columnIndex].X = columnIndex; MeshMap[rowIndex, columnIndex].Y = rowIndex; } ++rowIndex; } mapReader.Close(); }catch (Exception e) { Console.WriteLine(e.ToString()); } }
/// <summary> /// 递归搜索 /// </summary> /// <param name="fileTree"></param> /// <param name="key"></param> /// <param name="listView"></param> void recursiveSearch(FileTree fileTree, string key) { /* 检索文件 */ foreach (FileTree.TreeFileInfo tfi in fileTree.CurrentDirectoryFileList.Values) { if (tfi.FileName.ToLower().Contains(key.ToLower())) { string fileName = tfi.FilePath; /* 大图标注意判断文件是否为图片 */ ListViewUtility.Invoke(new MethodInvoker(delegate { if (CodeAnalysis.IsImage(tfi.FilePath)) { Image image = Int32Dec64Convert.ConverToSquareBitmap(ImageListLargeUtility.ImageSize.Width, Image.FromFile(tfi.FilePath)); ImageListLargeUtility.Images.Add(MyConfig.getListKeyName(FileTree.FILE_IDENTIFY_NAME, fileName), image); } else if (LargeIconDict.ContainsKey(tfi.ExtendName)) { ImageListLargeUtility.Images.Add(MyConfig.getListKeyName(FileTree.FILE_IDENTIFY_NAME, fileName), Int32Dec64Convert.ConverToSquareBitmap(ImageListLargeUtility.ImageSize.Width, LargeIconDict[tfi.ExtendName])); } else { ImageListLargeUtility.Images.Add(MyConfig.getListKeyName(FileTree.FILE_IDENTIFY_NAME, fileName), Int32Dec64Convert.ConverToSquareBitmap(ImageListLargeUtility.ImageSize.Width, LargeDefaultFileIcon)); } if (SmallIconDict.ContainsKey(tfi.ExtendName)) { ImageListSmallUtility.Images.Add(MyConfig.getListKeyName(FileTree.FILE_IDENTIFY_NAME, fileName), Int32Dec64Convert.ConverToSquareBitmap(ImageListSmallUtility.ImageSize.Width, SmallIconDict[tfi.ExtendName])); } else { ImageListSmallUtility.Images.Add(MyConfig.getListKeyName(FileTree.FILE_IDENTIFY_NAME, fileName), Int32Dec64Convert.ConverToSquareBitmap(ImageListSmallUtility.ImageSize.Width, SmallDefaultFileIcon)); } ListViewUtility.Items.Add(MyConfig.getListKeyName(FileTree.FILE_IDENTIFY_NAME, fileName), tfi.FileName, MyConfig.getListKeyName(FileTree.FILE_IDENTIFY_NAME, fileName)); Application.DoEvents(); })); } } /* 检索文件夹 */ foreach (FileTree ft in fileTree.SubTree.Values) { if (ft.RootDirectory.Name.ToLower().Contains(key.ToLower())) { string directoryPath = ft.RootDirectory.FullName; ListViewUtility.Invoke(new MethodInvoker(delegate { ImageListLargeUtility.Images.Add(MyConfig.getListKeyName(FileTree.FOLDER_IDENTIFY_NAME, directoryPath), Int32Dec64Convert.ConverToSquareBitmap(ImageListLargeUtility.ImageSize.Width, LargeFolderIcon)); ImageListSmallUtility.Images.Add(MyConfig.getListKeyName(FileTree.FOLDER_IDENTIFY_NAME, directoryPath), Int32Dec64Convert.ConverToSquareBitmap(ImageListSmallUtility.ImageSize.Width, SmallFolderIcon)); ListViewUtility.Items.Add(MyConfig.getListKeyName(FileTree.FOLDER_IDENTIFY_NAME, directoryPath), ft.RootDirectory.Name, MyConfig.getListKeyName(FileTree.FOLDER_IDENTIFY_NAME, directoryPath)); Application.DoEvents(); })); } /* 递归 */ recursiveSearch(ft, key); } }
Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(CodeAnalysis.Emit.EmitContext context) { return this; }
/// <summary> /// Checks that at least one state is declared inside the machine. /// </summary> /// <param name="machine">Machine</param> /// <param name="compilation">Compilation</param> private void CheckForAtLeastOneState(ClassDeclarationSyntax machine, CodeAnalysis.Compilation compilation) { var states = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). ToList(); if (states.Count == 0) { base.WarningLog.Add(Tuple.Create(machine.Identifier, $"{this.GetTypeOfMachine().ToLower()} " + $"'{machine.Identifier.ValueText}' must declare at least one state (unless the machine " + "inherits at least one state from a base machine, or is partial, and one state has " + "been already declared in another part of the declaration).")); } }
/// <summary> /// Checks that a machine has an start state. /// </summary> /// <param name="machine">Machine</param> /// <param name="compilation">Compilation</param> private void CheckForStartState(ClassDeclarationSyntax machine, CodeAnalysis.Compilation compilation) { var model = compilation.GetSemanticModel(machine.SyntaxTree); var stateAttributes = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). SelectMany(val => val.AttributeLists). SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.Start")). ToList(); if (stateAttributes.Count == 0) { base.ErrorLog.Add(Tuple.Create(machine.Identifier, this.GetTypeOfMachine().ToLower() + " '" + machine.Identifier.ValueText + "' must declare a start state.")); } else if (stateAttributes.Count > 1) { base.ErrorLog.Add(Tuple.Create(machine.Identifier, this.GetTypeOfMachine().ToLower() + " '" + machine.Identifier.ValueText + "' must declare only one start state.")); } }
internal override string VisualizeRealIL(IModuleSymbol peModule, CodeAnalysis.CodeGen.CompilationTestData.MethodData methodData) { throw new NotImplementedException(); }
/// <summary> /// Compiles the given compilation and returns the assembly. /// </summary> /// <param name="compilation">Compilation</param> /// <param name="outputKind">OutputKind</param> /// <returns>Assembly</returns> private static Assembly ToAssembly(CodeAnalysis.Compilation compilation, OutputKind outputKind) { string assemblyFileName = null; if (outputKind == OutputKind.ConsoleApplication) { assemblyFileName = compilation.AssemblyName + ".exe"; } else if (outputKind == OutputKind.DynamicallyLinkedLibrary) { assemblyFileName = compilation.AssemblyName + ".dll"; } EmitResult emitResult = null; using (var ms = new MemoryStream()) { emitResult = compilation.Emit(ms); if (emitResult.Success) { var assembly = Assembly.Load(ms.GetBuffer()); return assembly; } } Output.Print("---"); Output.Print("Note: the errors below correspond to the intermediate C#-IR, " + "which can be printed using /debug."); Output.Print("---"); var message = string.Join("\r\n", emitResult.Diagnostics); throw new ApplicationException(message); }
/// <summary> /// Compiles the given compilation to a file. /// </summary> /// <param name="compilation">Compilation</param> /// <param name="outputKind">OutputKind</param> /// <param name="outputPath">OutputPath</param> /// <param name="printResults">Prints the compilation results</param> /// <param name="buildDebugFile">Builds the debug file</param> /// <returns>Output</returns> public string ToFile(CodeAnalysis.Compilation compilation, OutputKind outputKind, string outputPath, bool printResults, bool buildDebugFile) { string assemblyFileName = null; if (outputKind == OutputKind.ConsoleApplication) { assemblyFileName = compilation.AssemblyName + ".exe"; } else if (outputKind == OutputKind.DynamicallyLinkedLibrary) { assemblyFileName = compilation.AssemblyName + ".dll"; } string outputDirectory; if (!this.CompilationContext.Configuration.OutputFilePath.Equals("")) { outputDirectory = this.CompilationContext.Configuration.OutputFilePath; } else { outputDirectory = Path.GetDirectoryName(outputPath); } string fileName = outputDirectory + Path.DirectorySeparatorChar + assemblyFileName; string pdbFileName = outputDirectory + Path.DirectorySeparatorChar + compilation.AssemblyName + ".pdb"; this.OutputDirectoryMap?.Add(compilation.AssemblyName, outputDirectory); this.ProjectAssemblyPathMap?.Add(compilation.AssemblyName, fileName); EmitResult emitResult = null; using (FileStream outputFile = new FileStream(fileName, FileMode.Create, FileAccess.Write), outputPdbFile = new FileStream(pdbFileName, FileMode.Create, FileAccess.Write)) { if (buildDebugFile) { emitResult = compilation.Emit(outputFile, outputPdbFile); } else { emitResult = compilation.Emit(outputFile, null); } } if (emitResult.Success) { if (printResults) { IO.PrintLine("... Writing {0}", fileName); } return fileName; } IO.PrintLine("---"); IO.PrintLine("Note: the errors below correspond to the intermediate C#-IR, " + "which can be printed using /debug."); IO.PrintLine("---"); var message = string.Join("\r\n", emitResult.Diagnostics); throw new ApplicationException(message); }
/// <summary> /// Checks that at least one state or group is declared inside a group. /// </summary> /// <param name="machine">Machine</param> /// <param name="compilation">Compilation</param> private void CheckForAtLeastOneStateOrGroup(ClassDeclarationSyntax machine, CodeAnalysis.Compilation compilation) { var stateGroups = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => Querying.IsMachineStateGroup(compilation, val)). ToList(); foreach (var stateGroup in stateGroups) { var contents = stateGroup.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => Querying.IsMachineState(compilation, val) || Querying.IsMachineStateGroup(compilation, val)). ToList(); if (contents.Count == 0) { base.WarningLog.Add(Tuple.Create(stateGroup.Identifier, "State group " + $"'{stateGroup.Identifier.ValueText}' must declare at least one state or group.")); } } }
/// <summary> /// Checks that a state does not have a duplicate exit action. /// </summary> /// <param name="state">State</param> /// <param name="compilation">Compilation</param> private void CheckForDuplicateOnExit(ClassDeclarationSyntax state, CodeAnalysis.Compilation compilation) { var model = compilation.GetSemanticModel(state.SyntaxTree); var onExitAttribute = state.AttributeLists. SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.OnExit")). FirstOrDefault(); var onExitMethod = state.DescendantNodes().OfType<MethodDeclarationSyntax>(). Where(val => val.Modifiers.Any(SyntaxKind.OverrideKeyword)). Where(val => val.Identifier.ValueText.Equals("OnExit")). FirstOrDefault(); if (onExitAttribute != null && onExitMethod != null) { base.ErrorLog.Add(Tuple.Create(state.Identifier, "State '" + state.Identifier.ValueText + "' cannot have two exit actions.")); } }
/// <summary> /// Checks that a state does not have a liveness attribute. /// </summary> /// <param name="state">State</param> /// <param name="compilation">Compilation</param> private void CheckForLivenessAttribute(ClassDeclarationSyntax state, CodeAnalysis.Compilation compilation) { var model = compilation.GetSemanticModel(state.SyntaxTree); var hotAttributes = state.AttributeLists. SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.Hot")). ToList(); var coldAttributes = state.AttributeLists. SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.Cold")). ToList(); if (hotAttributes.Count > 0 || coldAttributes.Count > 0) { base.ErrorLog.Add(Tuple.Create(state.Identifier, "A machine state cannot declare " + "a liveness attribute.")); } }
/// <summary> /// Checks for special properties. /// </summary> /// <param name="state">State</param> /// <param name="compilation">Compilation</param> protected override void CheckForSpecialProperties(ClassDeclarationSyntax state, CodeAnalysis.Compilation compilation) { this.CheckForLivenessAttribute(state, compilation); }
/// <summary> /// Checks for special properties. /// </summary> /// <param name="state">State</param> /// <param name="compilation">Compilation</param> protected abstract void CheckForSpecialProperties(ClassDeclarationSyntax state, CodeAnalysis.Compilation compilation);
/// <summary> /// Checks for multiple handlers for the same event. /// </summary> /// <param name="state">State</param> /// <param name="compilation">Compilation</param> private void CheckForMultipleSameEventHandlers(ClassDeclarationSyntax state, CodeAnalysis.Compilation compilation) { var model = compilation.GetSemanticModel(state.SyntaxTree); var eventTypes = state.AttributeLists. SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.OnEventGotoState") || model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.OnEventPushState") || model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.OnEventDoAction") || model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.IgnoreEvents") || model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.DeferEvents")). Where(val => val.ArgumentList != null). Where(val => val.ArgumentList.Arguments.Count > 0). Where(val => val.ArgumentList.Arguments[0].Expression is TypeOfExpressionSyntax). Select(val => val.ArgumentList.Arguments[0].Expression as TypeOfExpressionSyntax); var eventHandlers = eventTypes. Where(val => val.Type is IdentifierNameSyntax). Select(val => val.Type as IdentifierNameSyntax). Select(val => val.ToFullString()). ToList(); eventHandlers.AddRange(eventTypes. Where(val => val.Type is QualifiedNameSyntax). Select(val => val.Type as QualifiedNameSyntax). Select(val => val.ToFullString()). ToList()); var eventOccurrences = eventHandlers.GroupBy(val => val); foreach (var e in eventOccurrences.Where(val => val.Count() > 1)) { base.ErrorLog.Add(Tuple.Create(state.Identifier, "State '" + state.Identifier.ValueText + "' cannot declare more than one handler for event '" + e.Key + "'.")); } }
public void Given_Reporting_Range_Of_Two_Days_With_MultipleDeveloper_Expect_Two_Days_Of_Stats() { //---------------Arrange------------------ var author1 = new Author { Name = "T-rav", Emails = new List <string> { "*****@*****.**" } }; var author2 = new Author { Name = "Zen", Emails = new List <string> { "*****@*****.**" } }; var authors = new List <Author> { author1, author2 }; var commits = new List <Commit> { new Commit { Author = author1, When = DateTime.Now, Patch = new List <Patch> { new Patch { ChangeType = ChangeType.Modified, LinesAdded = 2, LinesRemoved = 0, Contents = "@@ 2,0 2,0 @@ namespace Test.Namespace \na\nb" } } }, new Commit { Author = author2, When = DateTime.Now, Patch = new List <Patch> { new Patch { ChangeType = ChangeType.Added, LinesAdded = 3, LinesRemoved = 0, Contents = "@@ 3,0 3,0 @@ namespace Test2.Namespace \n1\n2\n3" } } } }; var context = new AnalysisContext { ReportRange = new Domain.Reporting.ReportingPeriod { Start = DateTime.Today.AddDays(-1), End = DateTime.Now } }; var sut = new CodeAnalysis(authors, commits, context); //---------------Act---------------------- var actual = sut.Build_Stats(); //---------------Assert------------------- var expected = new List <TeamStatsForDay> { new TeamStatsForDay { ActiveDevelopers = 0, Commits = 0, Impact = 0, Churn = 0, RiskFactor = 0, Ptt100 = 0, When = DateTime.Now.Date.AddDays(-1) }, new TeamStatsForDay { ActiveDevelopers = 2, Commits = 2, Impact = 0.006, Churn = 0.0, RiskFactor = 2.5, Ptt100 = 331.58, When = DateTime.Now.Date } }; actual.TeamStatsPerDay.Should().BeEquivalentTo(expected); }
Cci.IDefinition Cci.IReference.AsDefinition(CodeAnalysis.Emit.EmitContext context) { return null; }
/// <summary> /// Returns true if the given class declaration is a stategroup. /// </summary> /// <param name="compilation">Compilation</param> /// <param name="classDecl">Class declaration</param> /// <returns>Boolean</returns> protected override bool IsStateGroup(CodeAnalysis.Compilation compilation, ClassDeclarationSyntax classDecl) { return Querying.IsMachineStateGroup(compilation, classDecl); }
/// <summary> /// Checks that a machine has an start state. /// </summary> /// <param name="machine">Machine</param> /// <param name="compilation">Compilation</param> private void CheckForStartState(ClassDeclarationSyntax machine, CodeAnalysis.Compilation compilation) { var model = compilation.GetSemanticModel(machine.SyntaxTree); var stateAttributes = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). SelectMany(val => val.AttributeLists). SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.Start")). ToList(); if (stateAttributes.Count == 0) { base.WarningLog.Add(Tuple.Create(machine.Identifier, $"{this.GetTypeOfMachine().ToLower()} " + $"'{machine.Identifier.ValueText}' must declare a start state (unless the machine " + "inherits a start state from a base machine, or is partial, and one state has been " + "already declared in another part of the declaration).")); } else if (stateAttributes.Count > 1) { base.ErrorLog.Add(Tuple.Create(machine.Identifier, $"{this.GetTypeOfMachine().ToLower()} " + $"'{machine.Identifier.ValueText}' must declare only one start state.")); } }
public void Respond(CodeAnalysis output) { _stats = output; }
public void Respond(CodeAnalysis output) { _output = output; }
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(CodeAnalysis.Emit.EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); }
/// <summary> /// Returns true if the given class declaration is a state. /// </summary> /// <param name="compilation">Compilation</param> /// <param name="classDecl">Class declaration</param> /// <returns>Boolean</returns> protected abstract bool IsState(CodeAnalysis.Compilation compilation, ClassDeclarationSyntax classDecl);
/// <summary> /// Returns true if the given class declaration is a state. /// </summary> /// <param name="compilation">Compilation</param> /// <param name="classDecl">Class declaration</param> /// <returns>Boolean</returns> protected override bool IsState(CodeAnalysis.Compilation compilation, ClassDeclarationSyntax classDecl) { return Querying.IsMonitorState(compilation, classDecl); }
/// <summary> /// Discovers the available actions of the given machine. /// </summary> /// <param name="machine">Machine</param> /// <param name="compilation">Compilation</param> private void DiscoverMachineActions(ClassDeclarationSyntax machine, CodeAnalysis.Compilation compilation) { var model = compilation.GetSemanticModel(machine.SyntaxTree); var onEntryActionNames = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). SelectMany(val => val.AttributeLists). SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.OnEntry")). Where(val => val.ArgumentList != null). Where(val => val.ArgumentList.Arguments.Count == 1). Where(val => val.ArgumentList.Arguments[0].Expression is LiteralExpressionSyntax). Select(val => val.ArgumentList.Arguments[0].Expression as LiteralExpressionSyntax). Select(val => val.Token.ValueText). ToList(); var onEntryNameOfActionNames = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). SelectMany(val => val.AttributeLists). SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.OnEntry")). Where(val => val.ArgumentList != null). Where(val => val.ArgumentList.Arguments.Count == 1). Where(val => val.ArgumentList.Arguments[0].Expression is InvocationExpressionSyntax). Select(val => val.ArgumentList.Arguments[0].Expression as InvocationExpressionSyntax). Where(val => val.Expression is IdentifierNameSyntax). Where(val => (val.Expression as IdentifierNameSyntax).Identifier.ValueText.Equals("nameof")). Where(val => val.ArgumentList != null). Where(val => val.ArgumentList.Arguments.Count == 1). Where(val => val.ArgumentList.Arguments[0].Expression is IdentifierNameSyntax). Select(val => val.ArgumentList.Arguments[0].Expression as IdentifierNameSyntax). Select(val => val.Identifier.ValueText). ToList(); var onExitActionNames = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). SelectMany(val => val.AttributeLists). SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.OnExit")). Where(val => val.ArgumentList != null). Where(val => val.ArgumentList.Arguments.Count == 1). Where(val => val.ArgumentList.Arguments[0].Expression is LiteralExpressionSyntax). Select(val => val.ArgumentList.Arguments[0].Expression as LiteralExpressionSyntax). Select(val => val.Token.ValueText). ToList(); var onExitNameOfActionNames = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). SelectMany(val => val.AttributeLists). SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.OnExit")). Where(val => val.ArgumentList != null). Where(val => val.ArgumentList.Arguments.Count == 1). Where(val => val.ArgumentList.Arguments[0].Expression is InvocationExpressionSyntax). Select(val => val.ArgumentList.Arguments[0].Expression as InvocationExpressionSyntax). Where(val => val.Expression is IdentifierNameSyntax). Where(val => (val.Expression as IdentifierNameSyntax).Identifier.ValueText.Equals("nameof")). Where(val => val.ArgumentList != null). Where(val => val.ArgumentList.Arguments.Count == 1). Where(val => val.ArgumentList.Arguments[0].Expression is IdentifierNameSyntax). Select(val => val.ArgumentList.Arguments[0].Expression as IdentifierNameSyntax). Select(val => val.Identifier.ValueText). ToList(); var onEventDoActionNames = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). SelectMany(val => val.AttributeLists). SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.OnEventDoAction")). Where(val => val.ArgumentList != null). Where(val => val.ArgumentList.Arguments.Count == 2). Where(val => val.ArgumentList.Arguments[1].Expression is LiteralExpressionSyntax). Select(val => val.ArgumentList.Arguments[1].Expression as LiteralExpressionSyntax). Select(val => val.Token.ValueText). ToList(); var onEventDoNameOfActionNames = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). SelectMany(val => val.AttributeLists). SelectMany(val => val.Attributes). Where(val => model.GetTypeInfo(val).Type.ToDisplayString().Equals("Microsoft.PSharp.OnEventDoAction")). Where(val => val.ArgumentList != null). Where(val => val.ArgumentList.Arguments.Count == 2). Where(val => val.ArgumentList.Arguments[1].Expression is InvocationExpressionSyntax). Select(val => val.ArgumentList.Arguments[1].Expression as InvocationExpressionSyntax). Where(val => val.Expression is IdentifierNameSyntax). Where(val => (val.Expression as IdentifierNameSyntax).Identifier.ValueText.Equals("nameof")). Where(val => val.ArgumentList != null). Where(val => val.ArgumentList.Arguments.Count == 1). Where(val => val.ArgumentList.Arguments[0].Expression is IdentifierNameSyntax). Select(val => val.ArgumentList.Arguments[0].Expression as IdentifierNameSyntax). Select(val => val.Identifier.ValueText). ToList(); var actionNames = new HashSet<string>(); actionNames.UnionWith(onEntryActionNames); actionNames.UnionWith(onEntryNameOfActionNames); actionNames.UnionWith(onExitActionNames); actionNames.UnionWith(onExitNameOfActionNames); actionNames.UnionWith(onEventDoActionNames); actionNames.UnionWith(onEventDoNameOfActionNames); this.Actions.Add(machine, new List<MethodDeclarationSyntax>()); foreach (var actionName in actionNames) { var action = machine.DescendantNodes().OfType<MethodDeclarationSyntax>(). Where(val => val.ParameterList != null). Where(val => val.ParameterList.Parameters.Count == 0). Where(val => val.Identifier.ValueText.Equals(actionName)). FirstOrDefault(); if (action != null) { this.Actions[machine].Add(action); } } var states = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). ToList(); var stateMethods = states.SelectMany(val => val.DescendantNodes().OfType<MethodDeclarationSyntax>()). Where(val => val.Modifiers.Any(SyntaxKind.OverrideKeyword)). ToList(); foreach (var method in stateMethods) { this.Actions[machine].Add(method); } }
internal override string VisualizeRealIL(IModuleSymbol peModule, CodeAnalysis.CodeGen.CompilationTestData.MethodData methodData, IReadOnlyDictionary<int, string> markers) { throw new NotImplementedException(); }
/// <summary> /// Discovers the actions of the given machine that pop. /// </summary> /// <param name="machine">Machine</param> /// <param name="compilation">Compilation</param> private void DiscoverMachineActionsThatPop(ClassDeclarationSyntax machine, CodeAnalysis.Compilation compilation) { this.ActionsThaPop.Add(machine, new List<MethodDeclarationSyntax>()); var actions = this.Actions[machine]; foreach (var action in actions) { var hasPop = action.DescendantNodes().OfType<InvocationExpressionSyntax>(). Where(val => val.Expression is IdentifierNameSyntax). Select(val => val.Expression as IdentifierNameSyntax). Any(val => val.Identifier.ValueText.Equals("Pop")); if (!hasPop) { hasPop = action.DescendantNodes().OfType<InvocationExpressionSyntax>(). Where(val => val.Expression is MemberAccessExpressionSyntax). Select(val => val.Expression as MemberAccessExpressionSyntax). Any(val => val.Name.Identifier.ValueText.Equals("Pop")); } if (hasPop) { this.ActionsThaPop[machine].Add(action); } } }
/// <summary> /// Links the external references to the given P# compilation. /// </summary> /// <param name="compilation">Compilation</param> private static void LinkExternalAssembliesToProject(CodeAnalysis.Compilation compilation) { //foreach (var reference in compilation.ExternalReferences) //{ // if (!(reference is PortableExecutableReference)) // { // continue; // } //} }
/// <summary> /// Checks that at least one state is declared inside the machine. /// </summary> /// <param name="machine">Machine</param> /// <param name="compilation">Compilation</param> private void CheckForAtLeastOneState(ClassDeclarationSyntax machine, CodeAnalysis.Compilation compilation) { var states = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => this.IsState(compilation, val)). ToList(); if (states.Count == 0) { base.ErrorLog.Add(Tuple.Create(machine.Identifier, this.GetTypeOfMachine().ToLower() + " '" + machine.Identifier.ValueText + "' must declare at least one state.")); } }
/// <summary> /// Compiles the given compilation to a file. /// </summary> /// <param name="compilation">Compilation</param> /// <param name="outputKind">OutputKind</param> /// <param name="outputPath">OutputPath</param> /// <returns>Output</returns> private static string ToFile(CodeAnalysis.Compilation compilation, OutputKind outputKind, string outputPath) { string assemblyFileName = null; if (outputKind == OutputKind.ConsoleApplication) { assemblyFileName = compilation.AssemblyName + ".exe"; } else if (outputKind == OutputKind.DynamicallyLinkedLibrary) { assemblyFileName = compilation.AssemblyName + ".dll"; } string fileName = null; if (!Configuration.OutputFilePath.Equals("")) { fileName = Configuration.OutputFilePath + Path.DirectorySeparatorChar + assemblyFileName; CompilationEngine.OutputDirectoryMap.Add(compilation.AssemblyName, Configuration.OutputFilePath); } else { fileName = Path.GetDirectoryName(outputPath) + Path.DirectorySeparatorChar + assemblyFileName; CompilationEngine.OutputDirectoryMap.Add(compilation.AssemblyName, Path.GetDirectoryName(outputPath)); } CompilationEngine.ProjectAssemblyPathMap.Add(compilation.AssemblyName, fileName); // Link external references. CompilationEngine.LinkExternalAssembliesToProject(compilation); EmitResult emitResult = null; using (var outputFile = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { emitResult = compilation.Emit(outputFile); if (emitResult.Success) { Output.Print("... Writing " + fileName); return fileName; } } Output.Print("---"); Output.Print("Note: the errors below correspond to the intermediate C#-IR, " + "which can be printed using /debug."); Output.Print("---"); var message = string.Join("\r\n", emitResult.Diagnostics); throw new ApplicationException(message); }
/// <summary> /// Checks that no non-state or non-event classes are declared inside the machine. /// </summary> /// <param name="machine">Machine</param> /// <param name="compilation">Compilation</param> private void CheckForNonStateNonEventClasses(ClassDeclarationSyntax machine, CodeAnalysis.Compilation compilation) { var classIdentifiers = machine.DescendantNodes().OfType<ClassDeclarationSyntax>(). Where(val => !this.IsState(compilation, val) && !Querying.IsEventDeclaration(compilation, val)). Select(val => val.Identifier). ToList(); foreach (var identifier in classIdentifiers) { base.ErrorLog.Add(Tuple.Create(identifier, "Not allowed to declare non-state class '" + identifier.ValueText + "' inside " + this.GetTypeOfMachine().ToLower() + " '" + machine.Identifier.ValueText + "'.")); } }