private static void ReadBinaryFile(CoverageInfo covInfo, Stream fs)
        {
            while (true)
            {
                var id = (fs.ReadByte() << 24) + (fs.ReadByte() << 16) +
                         (fs.ReadByte() << 8) + (fs.ReadByte() << 0);
                var value = fs.ReadByte();
                if (value == -1)
                {
                    return;
                }
                switch ((ElementType)(value >> 2))
                {
                case ElementType.TestCase:
                    break;

                default:
                    if (0 <= id && id < covInfo.Targets.Count)
                    {
                        var element = covInfo.Targets[id];
                        var state   = (CoverageState)(value & ((1 << 2) - 1));
                        element.UpdateState(state);
                    }
                    break;
                }
            }
        }
		public static string InsertInstrumentationCode(LanguageSupport mode, string fileName) {
			var info = new CoverageInfo(
					Fixture.GetCoverageInputPath(), mode.Name, SharingMethod.SharedMemory);
			var inPath = Path.Combine(Fixture.GetCoverageInputPath(), fileName);
			var code = OccfCodeGenerator.GetCoveragedCode(new FileInfo(inPath), info, mode);
			File.WriteAllText(Fixture.GetOutputPath(fileName), code);
			return code;
		}
 public static void ReadFile(CoverageInfo covInfo, FileInfo fileInfo) {
     using (var fs = new FileStream(fileInfo.FullName, FileMode.Open)) {
         if (IsTextFile(fs)) {
             ReadTextFile(covInfo, fs);
         } else {
             ReadBinaryFile(covInfo, fs);
         }
     }
 }
        public static void TransofrmStatement(
                CoverageInfo info, XElement root, LanguageSupport support, string relativePath) {
            // ステートメントを挿入できるようにブロックを補う
            support.AstTransformer.SupplementBlock(root);

            InsertIntoStatement(info, root, support, relativePath);
            InsertIntoVariableInitializer(info, root, support, relativePath);

            // Add import for loggin executed items
            support.AstTransformer.InsertImport(root);
        }
 private static void ReadTextFile(CoverageInfo covInfo, FileStream fs) {
     using (var reader = new StreamReader(fs)) {
         string line;
         while (!string.IsNullOrEmpty((line = reader.ReadLine()))) {
             var items = line.Split(' ');
             var element = covInfo.Targets[int.Parse(items[0])];
             var state = (CoverageState)(int.Parse(items[2]));
             element.UpdateState(state);
         }
     }
 }
        public static void TransformPredicate(
                CoverageInfo info, XElement root, LanguageSupport support, string relativePath) {
            // switch文を正しく測定できるようにdefault節を追加する
            support.AstTransformer.SupplementDefaultCase(root);

            InsertIntoBranchAndCondition(info, root, support, relativePath);
            InsertIntoSwitchCase(info, root, support, relativePath);
            InsertIntoForeach(info, root, support, relativePath);

            // Add import for loggin executed items
            support.AstTransformer.InsertImport(root);
        }
		public static string GetCoveragedCode(
				FileInfo codeFile, CoverageInfo info, LanguageSupport support, out string relativePath) {
			relativePath = ParaibaPath.GetRelativePath(codeFile.FullName, info.BasePath);
			var ast = support.CodeToXml.GenerateFromFile(codeFile.FullName);

			// 測定用コードの埋め込み
			var path = relativePath;
			CodeTransformer.InstrumentStatementAndPredicate(info, ast, support, path);

			// コード生成
			return support.XmlToCode.Generate(ast);
		}
 public static void ReadFile(CoverageInfo covInfo, FileInfo fileInfo)
 {
     using (var fs = new FileStream(fileInfo.FullName, FileMode.Open)) {
         if (IsTextFile(fs))
         {
             ReadTextFile(covInfo, fs);
         }
         else
         {
             ReadBinaryFile(covInfo, fs);
         }
     }
 }
 private static void ReadTextFile(CoverageInfo covInfo, FileStream fs)
 {
     using (var reader = new StreamReader(fs)) {
         string line;
         while (!string.IsNullOrEmpty((line = reader.ReadLine())))
         {
             var items   = line.Split(' ');
             var element = covInfo.Targets[int.Parse(items[0])];
             var state   = (CoverageState)(int.Parse(items[2]));
             element.UpdateState(state);
         }
     }
 }
		public void InsertInstrumentationCode(string fileName) {
			var profile = LanguageSupports.GetCoverageModeByClassName("Java");
			CodeInsertTest.InsertInstrumentationCode(profile, fileName);

			var info = new CoverageInfo(
					Fixture.GetCoverageInputPath(), profile.Name, SharingMethod.SharedMemory);
			var inPath = Path.Combine(Fixture.GetCoverageInputPath(), fileName);
			var codeFile = new FileInfo(inPath);

			var relativePath = ParaibaPath.GetRelativePath(codeFile.FullName, info.BasePath);
			var ast = profile.CodeToXml.GenerateFromFile(codeFile.FullName);

			File.WriteAllText(Fixture.GetOutputPath(fileName) + ".xml", ast.ToString());

			// 測定用コードの埋め込み
			var path = relativePath;
			CodeTransformer.InstrumentStatementAndPredicate(info, ast, profile, path);

			File.WriteAllText(Fixture.GetOutputPath(fileName) + ".modified.xml", ast.ToString());
		}
 private static void ReadBinaryFile(CoverageInfo covInfo, Stream fs) {
     while (true) {
         var id = (fs.ReadByte() << 24) + (fs.ReadByte() << 16) +
                 (fs.ReadByte() << 8) + (fs.ReadByte() << 0);
         var value = fs.ReadByte();
         if (value == -1) {
             return;
         }
         switch ((ElementType)(value >> 2)) {
         case ElementType.TestCase:
             break;
         default:
             if (0 <= id && id < covInfo.Targets.Count) {
                 var element = covInfo.Targets[id];
                 var state = (CoverageState)(value & ((1 << 2) - 1));
                 element.UpdateState(state);
             }
             break;
         }
     }
 }
        public static void InstrumentStatementAndPredicate(
                CoverageInfo info, XElement root, LanguageSupport support, string relativePath) {
            // ステートメントを挿入できるようにブロックを補う
            support.AstTransformer.SupplementBlock(root);

            // switch文を正しく測定できるようにdefault節を追加する
            support.AstTransformer.SupplementDefaultCase(root);

            InsertIntoStatement(info, root, support, relativePath);
            //InsertIntoBranchAndCondition(info, root, support, relativePath);

            // Add the measurement code as a statement into switch and foreach
            // after inserting the measurement code into statements
            //InsertIntoSwitchCase(info, root, support, relativePath);
            //InsertIntoForeach(info, root, support, relativePath);

            // Add the measurement code as a prediction into variable initializers
            // after inserting the measurement code into predictions
            //InsertIntoVariableInitializer(info, root, support, relativePath);

            // Add import for logging executed items
            support.AstTransformer.InsertImport(root);
        }
		public void Start(int port, CoverageInfo info) {
			var address = IPAddress.Parse("127.0.0.1");
			var server = new TcpListener(address, port);
			server.Start();

			while (true) {
				var client = server.AcceptTcpClient();
				Action action = () => {
					using (var stream = client.GetStream()) {
						while (true) {
							var index = (stream.ReadByte() << 24) + (stream.ReadByte() << 16) +
									(stream.ReadByte() << 8) + (stream.ReadByte() << 0);
							var value = stream.ReadByte();
							if (value == -1) {
								break;
							}
							info.Targets[index].UpdateState((CoverageState)value);
						}
					}
				};
				action.BeginInvoke(action.EndInvoke, null);
			}
		}
		private void BtnStartClick(object sender, EventArgs e) {
			var files = clbFiles.CheckedItems.Cast<string>();
			var basePath = txtBase.Text.AddIfNotEndsWith('\\');
			var outDirPath = txtOutput.Text.AddIfNotEndsWith('\\');

			var filePathList = files.ToList();
			var langName = cmbLanguage.Text;

			Action action = () => {
				var profile = LanguageSupports.GetCoverageModeByClassName(langName);
				var info = new CoverageInfo(basePath, profile.Name, SharingMethod.File);
				var outDir = new DirectoryInfo(outDirPath);
				foreach (var filePath in filePathList) {
					OccfCodeGenerator.WriteCoveragedCode(
							profile, info, new FileInfo(filePath), outDir);
				}
				info.Write(new DirectoryInfo(outDirPath));
			};
			ProgressForm.Start(this, filePathList.Count, action);
		}
 private static void InsertIntoStatement(
         CoverageInfo info, XElement root, LanguageSupport support, string relativePath) {
     var statemetIndex = info.Targets.Count;
     var nodes = support.AstAnalyzer.FindStatements(root);
     foreach (var node in nodes.ToList()) {
         // ステートメントに測定用コードを埋め込む
         var posNode = support.AstAnalyzer.GetBaseElementForStatement(node);
         support.AstTransformer.InsertStatementBefore(
                 posNode, info.Targets.Count, Done, ElementType.Statement);
         // カバレッジ情報を生成
         var covElem = new CoverageElement(relativePath, node, support.Tagger);
         info.Targets.Add(covElem);
     }
     info.StatementRanges.Add(Tuple.Create(statemetIndex, info.Targets.Count));
 }
 private static void InsertIntoForeach(
         CoverageInfo info, XElement node, LanguageSupport support, string relativePath) {
     var startBranchIndex = info.Targets.Count;
     var startBranchConditionIndex = info.TargetGroups.Count;
     var analyzer = support.AstAnalyzer;
     var transformer = support.AstTransformer;
     var foreachNodes = analyzer.FindForeach(node);
     foreach (var foreachNode in foreachNodes.ToList()) {
         // ステートメントに測定用コードを埋め込む
         var head = analyzer.FindForeachHead(foreachNode).First();
         var tail = analyzer.FindForeachTail(foreachNode).First();
         // 同じid( = count)を共有
         var id = info.Targets.Count;
         // Record(TrueOnly)    _lastState = TrueOnly
         // foreach() {
         //   Record(FalseOnly) ループ判定成立 (State |= FalseOnly)
         //   statement;
         //   Record(TrueOnly)  _lastState = TrueOnly
         // }
         // Record(TrueOnly)    ループ判定不成立 (State |= TrueOnly if _lastState == TrueOnly)
         transformer.InsertStatementBefore(
                 foreachNode, id, TrueOnly, ElementType.DecisionAndCondition);
         transformer.InsertStatementAfter(
                 head, id, FalseOnly, ElementType.DecisionAndCondition);
         transformer.InsertStatementBefore(
                 tail, id, TrueOnly, ElementType.DecisionAndCondition);
         transformer.InsertStatementAfter(
                 tail, id, TrueOnly, ElementType.DecisionAndCondition);
         // カバレッジ情報を生成
         var covElem = new ForeachCoverageElement(relativePath, foreachNode, support.Tagger);
         info.Targets.Add(covElem);
         var elementGroup = new CoverageElementGroup(covElem);
         info.TargetGroups.Add(elementGroup);
     }
     info.BranchRanges.Add(Tuple.Create(startBranchIndex, info.Targets.Count));
     info.BranchConditionRanges.Add(Tuple.Create(startBranchConditionIndex,
             info.TargetGroups.Count));
 }
		private static void WriteInfoFiles(DirectoryInfo rootDir, CoverageInfo covInfo, TestInfo testInfo) {
			var formatter = new BinaryFormatter();
			covInfo.Write(rootDir, formatter);
			if (testInfo == null) {
				return;
			}
			testInfo.Write(rootDir, formatter);
		}
		private static void WriteProductionCodeFiles(
				DirectoryInfo rootDir, IEnumerable<FileInfo> fileInfos, LanguageSupport mode,
				CoverageInfo info) {
			foreach (var path in fileInfos) {
				// 対象ファイルに対してKlee_backやLine_backがあるときは作成しない
				// Avoid ge
				if (!(File.Exists(path.FullName + OccfNames.LineBackUpSuffix))
				    && !(File.Exists(path.FullName + OccfNames.KleeBackUpSuffix))) {
					var backPath = Path.Combine(rootDir.FullName,
							path.FullName + OccfNames.BackupSuffix);
					path.CopyTo(backPath, true);
				}

				var outPath = OccfCodeGenerator.WriteCoveragedCode(mode, info, path, rootDir);
				Console.WriteLine("wrote:" + outPath);
			}
		}
		public static void InsertMeasurementCode(
				DirectoryInfo rootDir, ICollection<FileInfo> fileInfos, DirectoryInfo testDir,
				DirectoryInfo libDir, LanguageSupport mode, RecordingMode recordingMode) {
			Contract.Requires<ArgumentException>(rootDir.Exists);
			Contract.Requires<ArgumentException>(testDir == null || testDir.Exists);
			Contract.Requires<ArgumentException>(libDir.Exists);
			Contract.Requires<ArgumentNullException>(mode != null);

			//root
			var covInfo = new CoverageInfo(rootDir.FullName, mode.Name, SharingMethod.File);
			//(o)root or src?
			var testInfo = testDir != null
					? new TestInfo(rootDir.FullName)
					: null;
			//root
			RemoveExistingCoverageDataFiles(rootDir, libDir);

			mode.RemoveLibraries(libDir);
			//+src
			WriteProductionCodeFiles(rootDir, fileInfos, mode, covInfo);
			if (testInfo != null) {
				//(o)root or src
				WriteTestCodeFiles(rootDir, testDir, mode, testInfo);
			} else {
				// Initialize test information with empty contents
				testInfo = new TestInfo(rootDir.FullName);
				testInfo.TestCases.Add(new TestCase("nothing", "nothing", new CodeRange()));
			}
			//root
			WriteInfoFiles(rootDir, covInfo, testInfo);

			mode.CopyLibraries(libDir, recordingMode);
		}
 private static void InsertIntoSwitchCase(
         CoverageInfo info, XElement node, LanguageSupport support, string relativePath) {
     var analyzer = support.AstAnalyzer;
     var startSwitchIndex = info.TargetGroups.Count;
     var switchNodes = analyzer.FindSwitches(node);
     foreach (var switchNode in switchNodes.ToList()) {
         var caseElements = new List<CoverageElement>();
         var caseNodes = analyzer.FindCaseLabelTails(switchNode);
         foreach (var caseNode in caseNodes.ToList()) {
             // ステートメントに測定用コードを埋め込む
             support.AstTransformer.InsertStatementAfter(
                     caseNode, info.Targets.Count, Done, ElementType.SwitchCase);
             // カバレッジ情報を生成
             var covElem = new CoverageElement(relativePath, caseNode, support.Tagger);
             info.Targets.Add(covElem);
             caseElements.Add(covElem);
         }
         // switchのカバレッジ情報を生成
         var element = new CoverageElement(relativePath, switchNode, support.Tagger);
         // 条件分岐と論理項のカバレッジ情報をまとめる
         var elementGroup = new CoverageElementGroup(element, caseElements);
         info.TargetGroups.Add(elementGroup);
     }
     info.SwitchRanges.Add(Tuple.Create(startSwitchIndex, info.TargetGroups.Count));
 }
		public static string GetCoveragedCode(
				FileInfo codeFile, CoverageInfo info, LanguageSupport support) {
			string relativePath;
			return GetCoveragedCode(codeFile, info, support, out relativePath);
		}
        private static void InsertIntoBnrachAndComparison(
                CoverageInfo info, XElement root, LanguageSupport support, string relativePath) {
            var analyzer = support.AstAnalyzer;
            var branchNodes = analyzer.FindBranches(root);
            var startBranchIndex = info.Targets.Count;
            var startBranchConditionIndex = info.TargetGroups.Count;
            foreach (var branchNode in branchNodes.ToList()) {
                // 全ての論理項を列挙
                var condNodeList = analyzer.FindConditions(branchNode).ToList();
                // 論理項に測定用コードを埋め込み,カバレッジ情報を生成
                var condElements = InsertIntoConditionCoverage(info, condNodeList, support,
                        relativePath);

                // 条件分岐のカバレッジ情報を生成
                var element = new CoverageElement(relativePath, branchNode, support.Tagger);
                // 条件分岐と論理項のカバレッジ情報をまとめる
                var elementGroup = new CoverageElementGroup(element, condElements);
                info.TargetGroups.Add(elementGroup);

                // 論理項を含む条件式か否かを判断
                support.AstTransformer.InsertPredicate(
                        branchNode, info.Targets.Count,
                        elementGroup.Targets.Count > 0
                                ? ElementType.Decision
                                : ElementType.DecisionAndCondition);
                info.Targets.Add(element);
            }
            info.BranchConditionRanges.Add(Tuple.Create(startBranchConditionIndex,
                    info.TargetGroups.Count));
            info.BranchRanges.Add(Tuple.Create(startBranchIndex, info.Targets.Count));
        }
		private static SortedSet<string> ReconstructTags(CoverageInfo info) {
			// タグを構成要素に分解して再構成する
			var tagSet = info.Targets.Select(t => t.Tag).ToHashSet();
			var newTagSet = new SortedSet<string>();

			foreach (var tag in tagSet) {
				var tagElements = tag.Split(
						new[] { '>' },
						StringSplitOptions.RemoveEmptyEntries);
				var newTag = string.Empty;
				foreach (var tagEelment in tagElements) {
					newTag += tagEelment + '>';
					newTagSet.Add(newTag);
				}
			}
			return newTagSet;
		}
        private static void InsertIntoBranch(
                CoverageInfo info, XElement node, LanguageSupport support, string relativePath) {
            var branchNodes = support.AstAnalyzer.FindBranches(node);
            var startBranchIndex = info.Targets.Count;
            foreach (var branchNode in branchNodes.ToList()) {
                support.AstTransformer.InsertPredicate(branchNode, info.Targets.Count,
                        ElementType.Decision);

                // 条件分岐のカバレッジ情報を生成
                var element = new CoverageElement(relativePath, branchNode, support.Tagger);
                info.Targets.Add(element);
            }
            info.BranchRanges.Add(Tuple.Create(startBranchIndex, info.Targets.Count));
        }
        private static List<CoverageElement> InsertIntoConditionCoverage(
                CoverageInfo info, ICollection<XElement> condNodeList, LanguageSupport support,
                string relativePath) {
            return condNodeList.SelectToList(
                    node => {
                        support.AstTransformer.InsertPredicate(node, info.Targets.Count,
                                ElementType.Condition);

                        var covElem = new CoverageElement(relativePath, node, support.Tagger);
                        info.Targets.Add(covElem);
                        return covElem;
                    });
        }
        private static List<CoverageElement> InsertIntoConditionAndComparison(
                CoverageInfo info, ICollection<XElement> condNodeList, LanguageSupport support,
                string relativePath) {
            return condNodeList.SelectToList(
                    node => {
                        var elemsAndType = support.AstAnalyzer.GetComparedElements(node);
                        if (elemsAndType != null) {
                            var leftElement = elemsAndType.Item1;
                            var rightElement = elemsAndType.Item2;
                            var type = elemsAndType.Item3;
                            switch (type) {
                            case ComparatorType.Equal:
                                support.AstTransformer.InsertEqual(node, leftElement, rightElement,
                                        info.Targets.Count, ElementType.Condition);
                                break;
                            case ComparatorType.NotEqual:
                                support.AstTransformer.InsertNotEqual(node, leftElement,
                                        rightElement, info.Targets.Count, ElementType.Condition);
                                break;
                            case ComparatorType.LessThan:
                                support.AstTransformer.InsertLessThan(node, leftElement,
                                        rightElement, info.Targets.Count, ElementType.Condition);
                                break;
                            case ComparatorType.GraterThan:
                                support.AstTransformer.InsertGraterThan(node, leftElement,
                                        rightElement, info.Targets.Count, ElementType.Condition);
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                            }
                        } else {
                            support.AstTransformer.InsertPredicate(node, info.Targets.Count,
                                    ElementType.Condition);
                        }

                        var covElem = new CoverageElement(relativePath, node, support.Tagger);
                        info.Targets.Add(covElem);
                        return covElem;
                    });
        }
 private static void InsertIntoVariableInitializer(
         CoverageInfo info, XElement root, LanguageSupport support, string relativePath) {
     var statemetIndex = info.Targets.Count;
     var nodes = support.AstAnalyzer.FindVariableInitializers(root);
     foreach (var node in nodes.ToList()) {
         // ステートメントに測定用コードを埋め込む
         support.AstTransformer.InsertInitializer(node, info.Targets.Count,
                 ElementType.Statement);
         // カバレッジ情報を生成
         var covElem = new CoverageElement(relativePath, node, support.Tagger);
         info.Targets.Add(covElem);
     }
     info.StatementRanges.Add(Tuple.Create(statemetIndex, info.Targets.Count));
 }
		public static string WriteCoveragedCode(
				LanguageSupport support, CoverageInfo info, FileInfo codeFile, DirectoryInfo outDir) {
			string relativePath;
			var code = GetCoveragedCode(codeFile, info, support, out relativePath);
			return WriteCode(relativePath, outDir, code);
		}
		private void LoadCoverageInfomation(string filePath) {
			_txtCovInfoPath.Text = filePath;

			// カバレッジ情報(母数)の取得
			_info = CoverageInfo.ReadCoverageInfo(new FileInfo(filePath));

			// タグを構成要素に分解して再構成する
			var tagSet = _info.Targets.Select(t => t.Tag).ToHashSet();
			var newTagSet = new SortedSet<string>();

			foreach (var tag in tagSet) {
				var tagElements = tag.Split(
						new[] { '>' },
						StringSplitOptions.RemoveEmptyEntries);
				var newTag = string.Empty;
				foreach (var tagEelment in tagElements) {
					newTag += tagEelment + '>';
					newTagSet.Add(newTag);
				}
			}

			_lbTag.Items.Clear();
			foreach (var tag in newTagSet) {
				_lbTag.Items.Add(tag);
			}

			switch (_info.SharingMethod) {
			case SharingMethod.SharedMemory:
				SharedMemoryReporter.Initialize(_info.Targets.Count);
				break;
			case SharingMethod.TcpIp:
				break;
			case SharingMethod.File:
				break;
			default:
				throw new ArgumentOutOfRangeException();
			}
		}
        public static IEnumerable<LocalizedElement> LocalizeStatements(
                CoverageInfo covInfo, TestInfo testInfo, string metricsFilePath) {

            var calcMetricFunc = LoadMetricFunc(metricsFilePath);
            var maxStatementCount = covInfo.StatementIndexAndTargets.Count();
            var currentStatementCount = 1;
            foreach (var stmt in covInfo.StatementIndexAndTargets) {
                var id = stmt.Item1;
                var element = stmt.Item2;

                var passedTestCases = testInfo.TestCases.Where(t => t.Passed);
                var executedAndPassedTestCases =
                        passedTestCases.Where(t => t.Statements.Contains(id));
                var failedTestCases = testInfo.TestCases.Where(t => !t.Passed);
                var executedAndFailedTestCases =
                        failedTestCases.Where(t => t.Statements.Contains(id));

                var localized = new LocalizedElement {
                        ExecutedAndPassed = executedAndPassedTestCases.Count(),
                        Passed = passedTestCases.Count(),
                        ExecutedAndFailed = executedAndFailedTestCases.Count(),
                        Failed = failedTestCases.Count(),
                        Element = element,
                };
                var metrics = calcMetricFunc(
                        localized.ExecutedAndPassed,
                        localized.Passed,
                        localized.ExecutedAndFailed,
                        localized.Failed).Cast<double>().ToList();
                localized.Values = metrics.ToList();
                yield return localized;

                Console.Write("Calculating: " + currentStatementCount + " / " + maxStatementCount + "\r");
                currentStatementCount++;
            }
        }