public ReverseForeignRelationshipMapping(PropertyInfo property, Type type, Type parentType, Formatter<PropertyInfo> keyFormatter) : base(property) { this.type = type; this.parentType = parentType; this.ColumnName = keyFormatter.Format(property); }
public void Format_should_accept_TextWriter() { var sut = new Formatter(); var writer = new StringWriter(); writer.NewLine = "\n"; sut.Format(_testGame, writer); Assert.AreEqual(TestGameString, writer.ToString()); }
public void It_Should_Not_Be_null() { _objectsToFormat = new List<DummyObject>(); for (int i = 0; i < _numberOfObjects; i++) { _objectsToFormat.Add(new DummyObject()); } _formatter = new Formatter<DummyObject>(); try { _formatter.Format(_objectsToFormat); Assert.Fail("Expected NoFormatSpecificationException to be thrown"); } catch (NoFormatSpecificationException) { // Expect NoFormatSpecificationException to be thrown. } }
public void Then_Fixed_Length_Should_Be_Applied_To_The_Fields() { var dummyObjects = new List<DummyObject>(); for (int i = 0; i < 10; i++) { dummyObjects.Add(new DummyObject() { SomeInt = i, SomeString = "Str" + i}); } var formatter = new Formatter<DummyObject>() .With(y => y.SomeInt, 0, 5, y => y.ToString().PadLeft(5, '0')) .With(y => y.SomeString, 5, 5, y => y.PadRight(5, ' ')); var result = formatter.Format(dummyObjects); for (int i = 0; i < dummyObjects.Count; i++) { string expected = i.ToString().PadLeft(5, '0') + ("Str" + i).PadRight(5, ' '); string actual = result.ElementAt(i); Assert.AreEqual(expected, actual); } }
private void SaveLogEntry(LogEntry logEntry) { ServiceContainer.Resolve <ILogService>().CreateLog(new Log { EventID = logEntry.EventId, Priority = logEntry.Priority, Severity = logEntry.LoggedSeverity, Title = string.IsNullOrWhiteSpace(logEntry.Title) ? null : logEntry.Title.Trim(), Timestamp = logEntry.TimeStamp.ToLocalTime(), MachineName = logEntry.MachineName, Categories = string.Join(",", logEntry.CategoriesStrings), AppDomainName = logEntry.AppDomainName, ProcessID = logEntry.ProcessId, ProcessName = logEntry.ProcessName, ThreadName = logEntry.ManagedThreadName, ThreadId = logEntry.Win32ThreadId, Message = logEntry.Message, FormattedMessage = Formatter?.Format(logEntry) }); }
/// <summary> /// General verifier for codefixes. /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes. /// Then gets the string after the codefix is applied and compares it with the expected result. /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true. /// </summary> /// <param name="language">The language the source code is in</param> /// <param name="analyzer">The analyzer to be applied to the source code</param> /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param> /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="newSource">A class in the form of a string after the CodeFix was applied to it</param> /// <param name="codeFixIndex">Index determining which codefix to apply if there are multiple</param> /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param> private static void InvokeAndVerifyFix( string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldSource, string newSource, int?codeFixIndex, bool allowNewCompilerDiagnostics) { var document = DocumentFactory.CreateDocument(oldSource, language); var analyzerDiagnostics = analyzer.GetSortedDiagnosticsFromDocuments(new[] { document }); var compilerDiagnostics = document.GetCompilerDiagnostics(); var attempts = analyzerDiagnostics.Length; for (var i = 0; i < attempts; ++i) { var actions = new List <CodeAction>(); var context = new CodeFixContext( document, analyzerDiagnostics[0], registerCodeFix: (a, d) => actions.Add(a), cancellationToken: CancellationToken.None); codeFixProvider.RegisterCodeFixesAsync(context).Wait(); if (!actions.Any()) { break; } if (codeFixIndex != null) { document = document.ApplyFix(actions.ElementAt((int)codeFixIndex)); break; } document = document.ApplyFix(actions.ElementAt(0)); analyzerDiagnostics = analyzer.GetSortedDiagnosticsFromDocuments(new[] { document }); var newCompilerDiagnostics = DiagnosticComparer.GetNewDiagnostics( compilerDiagnostics, document.GetCompilerDiagnostics()); //check if applying the code fix introduced any new compiler diagnostics if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = DiagnosticComparer.GetNewDiagnostics(compilerDiagnostics, document.GetCompilerDiagnostics()); Assert.True(false, string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n", string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())), document.GetSyntaxRootAsync().Result.ToFullString())); } //check if there are analyzer diagnostics left after the code fix if (!analyzerDiagnostics.Any()) { break; } } //after applying all of the code fixes, compare the resulting string to the inputted one var expectedSource = newSource.Replace("\r\n", "\n"); var actualSource = document.ToSourceCode().Replace("\r\n", "\n"); Assert.Equal(expectedSource, actualSource); }
public void NullObjectPropertiesShouldEvaluateInEmptyString() { const string TEMPLATE = "abcd${Text}efgh${Text}"; const string FORMATTED = "abcdefgh"; var model = new TestModel(); model.Text = null; var formatter = new Formatter(TEMPLATE).Parse(); string formatted = formatter.Format(model); Assert.That(formatted, Is.EqualTo(FORMATTED)); Assert.That(formatter.ParsedTemplate.Count, Is.EqualTo(4)); }
public void Then_The_Header_Should_Be_The_First_Row() { string header = "This is the header"; var formatter = new Formatter<DummyObject>() .With(y => y.SomeInt, 0, 5, y => y.ToString("00000")) .With(y => y.SomeString, 5, 6, y => y.ToString().PadLeft(6, '_')) .WithHeader(header); var result = formatter.Format(_objectsToFormat); Assert.AreEqual(header, result.First()); }
public void HandNestedInclude() { var some = new Hashtable {{"a", "##"}}; var table = new Hashtable {{"some", some}}; var formatter = new Formatter("<sharp:include file='SharpTags/d.htm'/>").Parse(); Assert.That( formatter.Format(new TagModel(table)), Is.EqualTo("|bb##bb|bb##bb|bb##bb|") ); }
public void TestParseOfRandomDollarSignsAndParanthesesWithQuotes() { var formatter = new Formatter("A$('A')").Parse(); Assert.That(formatter.Format(new TagModel(this)), Is.EqualTo("A$('A')")); }
public void HandOverVariableScopeNested() { var some = new Hashtable(); some.Add("a", "##"); var table = new Hashtable(); table.Add("some", some); var formatter = new Formatter("<sharp:include file='SharpTags/b.htm'/>").Parse(); Assert.That(formatter.Format(new TagModel(table)), Is.EqualTo("bb##bb")); }
public void Disassemble(Formatter formatter, TextWriter output, DisasmInfo method) { formatterOutput.writer = output; targets.Clear(); sortedTargets.Clear(); bool upperCaseHex = formatter.Options.UpperCaseHex; output.Write(commentPrefix); output.WriteLine("================================================================================"); output.Write(commentPrefix); output.WriteLine(method.MethodFullName); uint codeSize = 0; foreach (var info in method.Code) { codeSize += (uint)info.Code.Length; } var codeSizeHexText = codeSize.ToString(upperCaseHex ? "X" : "x"); output.WriteLine($"{commentPrefix}{codeSize} (0x{codeSizeHexText}) bytes"); var instrCount = method.Instructions.Count; var instrCountHexText = instrCount.ToString(upperCaseHex ? "X" : "x"); output.WriteLine($"{commentPrefix}{instrCount} (0x{instrCountHexText}) instructions"); void Add(ulong address, TargetKind kind) { if (!targets.TryGetValue(address, out var addrInfo)) { targets[address] = new AddressInfo(kind); } else if (addrInfo.Kind < kind) { addrInfo.Kind = kind; } } if (method.Instructions.Count > 0) { Add(method.Instructions[0].IP, TargetKind.Unknown); } foreach (ref var instr in method.Instructions) { switch (instr.FlowControl) { case FlowControl.Next: case FlowControl.Interrupt: break; case FlowControl.UnconditionalBranch: Add(instr.NextIP, TargetKind.Unknown); if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64) { Add(instr.NearBranchTarget, TargetKind.Branch); } break; case FlowControl.ConditionalBranch: case FlowControl.XbeginXabortXend: if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64) { Add(instr.NearBranchTarget, TargetKind.Branch); } break; case FlowControl.Call: if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64) { Add(instr.NearBranchTarget, TargetKind.Call); } break; case FlowControl.IndirectBranch: Add(instr.NextIP, TargetKind.Unknown); // Unknown target break; case FlowControl.IndirectCall: // Unknown target break; case FlowControl.Return: case FlowControl.Exception: Add(instr.NextIP, TargetKind.Unknown); break; default: Debug.Fail($"Unknown flow control: {instr.FlowControl}"); break; } var baseReg = instr.MemoryBase; if (baseReg == Register.RIP || baseReg == Register.EIP) { int opCount = instr.OpCount; for (int i = 0; i < opCount; i++) { if (instr.GetOpKind(i) == OpKind.Memory) { if (method.Contains(instr.IPRelativeMemoryAddress)) { Add(instr.IPRelativeMemoryAddress, TargetKind.Branch); } break; } } } else if (instr.MemoryDisplSize >= 2) { ulong displ; switch (instr.MemoryDisplSize) { case 2: case 4: displ = instr.MemoryDisplacement; break; case 8: displ = (ulong)(int)instr.MemoryDisplacement; break; default: Debug.Fail($"Unknown mem displ size: {instr.MemoryDisplSize}"); goto case 8; } if (method.Contains(displ)) { Add(displ, TargetKind.Branch); } } } foreach (var map in method.ILMap) { if (targets.TryGetValue(map.nativeStartAddress, out var info)) { if (info.Kind < TargetKind.BlockStart && info.Kind != TargetKind.Unknown) { info.Kind = TargetKind.BlockStart; } } else { targets.Add(map.nativeStartAddress, info = new AddressInfo(TargetKind.Unknown)); } if (info.ILOffset < 0) { info.ILOffset = map.ilOffset; } } int labelIndex = 0, methodIndex = 0; string GetLabel(int index) => LABEL_PREFIX + index.ToString(); string GetFunc(int index) => FUNC_PREFIX + index.ToString(); foreach (var kv in targets) { if (method.Contains(kv.Key)) { sortedTargets.Add(kv); } } sortedTargets.Sort((a, b) => a.Key.CompareTo(b.Key)); foreach (var kv in sortedTargets) { var address = kv.Key; var info = kv.Value; switch (info.Kind) { case TargetKind.Unknown: info.Name = null; break; case TargetKind.Data: info.Name = GetLabel(labelIndex++); break; case TargetKind.BlockStart: case TargetKind.Branch: info.Name = GetLabel(labelIndex++); break; case TargetKind.Call: info.Name = GetFunc(methodIndex++); break; default: throw new InvalidOperationException(); } } foreach (ref var instr in method.Instructions) { ulong ip = instr.IP; if (targets.TryGetValue(ip, out var lblInfo)) { output.WriteLine(); if (!(lblInfo.Name is null)) { output.Write(lblInfo.Name); output.Write(':'); output.WriteLine(); } if (lblInfo.ILOffset >= 0) { if (ShowSourceCode) { foreach (var info in sourceCodeProvider.GetStatementLines(method, lblInfo.ILOffset)) { output.Write(commentPrefix); var line = info.Line; int column = commentPrefix.Length; WriteWithTabs(output, line, 0, line.Length, '\0', ref column); output.WriteLine(); if (info.Partial) { output.Write(commentPrefix); column = commentPrefix.Length; WriteWithTabs(output, line, 0, info.Span.Start, ' ', ref column); output.WriteLine(new string('^', info.Span.Length)); } } } } } if (ShowAddresses) { var address = FormatAddress(bitness, ip, upperCaseHex); output.Write(address); output.Write(" "); } else { output.Write(formatter.Options.TabSize > 0 ? "\t\t" : " "); } if (ShowHexBytes) { if (!method.TryGetCode(ip, out var nativeCode)) { throw new InvalidOperationException(); } var codeBytes = nativeCode.Code; int index = (int)(ip - nativeCode.IP); int instrLen = instr.ByteLength; for (int i = 0; i < instrLen; i++) { byte b = codeBytes[index + i]; output.Write(b.ToString(upperCaseHex ? "X2" : "x2")); } int missingBytes = HEXBYTES_COLUMN_BYTE_LENGTH - instrLen; for (int i = 0; i < missingBytes; i++) { output.Write(" "); } output.Write(" "); } formatter.Format(instr, formatterOutput); output.WriteLine(); } }
public void CommentedCodeShouldBeFilteredOut() { const string TEMPLATE = "abcd'<%--<mdc:test />--%>\\$\\{Text\\}'efgh${Text}"; const string FORMATTED = "abcd'${Text}'efgh12345"; var model = new TestModel(); model.Text = "12345"; var formatter = new Formatter(TEMPLATE).Parse(); string formatted = formatter.Format(model); Assert.That(formatted, Is.EqualTo(FORMATTED)); }
/// <summary> /// General verifier for codefixes. /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes. /// Then gets the string after the codefix is applied and compares it with the expected result. /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true. /// </summary> /// <param name="language">The language the source code is in</param> /// <param name="analyzer">The analyzer to be applied to the source code</param> /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param> /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="newSource">A class in the form of a string after the CodeFix was applied to it</param> /// <param name="codeFixIndex">Index determining which codefix to apply if there are multiple</param> /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param> private async Task VerifyFix(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldSource, string newSource, int?codeFixIndex, bool allowNewCompilerDiagnostics) { var document = CreateDocument(oldSource, language); var analyzerDiagnostics = await GetSortedDiagnosticsFromDocuments(analyzer, new[] { document }, false); var compilerDiagnostics = await GetCompilerDiagnostics(document); var attempts = analyzerDiagnostics.Length; for (int i = 0; i < attempts; ++i) { var actions = new List <CodeAction>(); var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); await codeFixProvider.RegisterCodeFixesAsync(context); if (!actions.Any()) { break; } if (codeFixIndex != null) { document = await ApplyFix(document, actions.ElementAt((int)codeFixIndex)); break; } document = await ApplyFix(document, actions.ElementAt(0)); analyzerDiagnostics = await GetSortedDiagnosticsFromDocuments(analyzer, new[] { document }, false); var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnostics(document)); // check if applying the code fix introduced any new compiler diagnostics if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = document.WithSyntaxRoot(Formatter.Format(await document.GetSyntaxRootAsync(), Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, await GetCompilerDiagnostics(document)); var diagnosticsString = string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())); var newDocumentString = (await document.GetSyntaxRootAsync()).ToFullString(); string message = $"Fix introduced new compiler diagnostics:\r\n{diagnosticsString}\r\n\r\nNew document:\r\n{newDocumentString}\r\n"; message.Should().BeEmpty(); } // check if there are analyzer diagnostics left after the code fix if (analyzerDiagnostics.Any()) { var diagnosticsString = string.Join("\r\n", analyzerDiagnostics.Select(d => d.ToString())); var newDocumentString = (await document.GetSyntaxRootAsync()).ToFullString(); string message = $"Fix didn't fix compiler diagnostics:\r\n{diagnosticsString}\r\n\r\nNew document:\r\n{newDocumentString}\r\n"; message.Should().BeEmpty(); } } // after applying all of the code fixes, compare the resulting string to the inputted one var actual = await GetStringFromDocument(document); actual.Should().Be(newSource); }
public override void Mutate(GroboIL il, ILInstructionParameter parameter, ref EvaluationStack stack) { var field = ((FieldILInstructionParameter)parameter).Field; if (!field.IsStatic) { var declaringType = field.DeclaringType; CheckNotEmpty(il, stack, () => $"In order to load the field '{Formatter.Format(field)}' an instance must be put onto the evaluation stack"); var instance = stack.Pop().ToType(); if (instance != null) { if (instance.IsValueType) { ThrowError(il, $"In order to load the field '{Formatter.Format(field)}' of a value type '{Formatter.Format(instance)}' load an instance by ref"); } else if (!instance.IsByRef) { CheckCanBeAssigned(il, declaringType, instance); } else { var elementType = instance.GetElementType(); if (elementType.IsValueType) { if (declaringType != elementType) { ThrowError(il, $"Cannot load the field '{Formatter.Format(field)}' of an instance of type '{Formatter.Format(elementType)}'"); } } else { ThrowError(il, $"Cannot load the field '{Formatter.Format(field)}' of an instance of type '{Formatter.Format(instance)}'"); } } } } stack.Push(field.FieldType); }
/// <summary> /// General verifier for codefixes. /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes. /// Then gets the string after the codefix is applied and compares it with the expected result. /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true. /// </summary> /// <param name="language">The language the source code is in</param> /// <param name="analyzers">The analyzers to be applied to the source code</param> /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param> /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param> /// <param name="newSource">A class in the form of a string after the CodeFix was applied to it</param> /// <param name="codeFixIndex">Index determining which codefix to apply if there are multiple</param> /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param> private void VerifyFix(string language, List <DiagnosticAnalyzer> analyzers, CodeFixProvider codeFixProvider, string oldSource, string newSource, int?codeFixIndex, bool allowNewCompilerDiagnostics) { var document = CreateDocument(oldSource, language, GetAdditionnalReferences()); var analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzers, new[] { document }); var compilerDiagnostics = GetCompilerDiagnostics(document); foreach (Diagnostic diag in compilerDiagnostics) { Console.WriteLine("/!\\: " + diag.ToString()); } //Some compiler diagnostic are simply warnings, we can not fail once a warning is present.. //Assert.AreEqual(compilerDiagnostics.Count(),0); var attempts = analyzerDiagnostics.Length; for (int i = 0; i < attempts; ++i) { var actions = new List <CodeAction>(); var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); codeFixProvider.RegisterCodeFixesAsync(context).Wait(); if (!actions.Any()) { break; } if (codeFixIndex != null) { document = ApplyFix(document, actions.ElementAt((int)codeFixIndex)); break; } document = ApplyFix(document, actions.ElementAt(0)); analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzers, new[] { document }); var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document)); //check if applying the code fix introduced any new compiler diagnostics if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document)); Assert.IsTrue(false, string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n", string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())), document.GetSyntaxRootAsync().Result.ToFullString())); } //check if there are analyzer diagnostics left after the code fix if (!analyzerDiagnostics.Any()) { break; } } //after applying all of the code fixes, compare the resulting string to the inputted one var actual = GetStringFromDocument(document); Assert.AreEqual(newSource, actual); }
/// <summary> /// Gets the string representation of the Syntax and it's trivia /// The result is not indented. /// </summary> /// <param name="node">The node.</param> /// <returns></returns> internal static string ToFormattedCode(this SyntaxNode node) => Formatter.Format(node, Config.EMPTY_WORKSPACE).ToFullString();
public static CreateSorter Compile(string name, string sorterCode) { var originalName = name; name = GetCSharpSafeName(name) + "." + Guid.NewGuid() + ".sorter"; var compilationUnit = SyntaxFactory.ParseCompilationUnit(sorterCode); SyntaxNode formattedCompilationUnit; using (var workspace = new AdhocWorkspace()) { formattedCompilationUnit = Formatter.Format(compilationUnit, workspace); } string sourceFile = null; if (IndexCompiler.EnableDebugging) { sourceFile = Path.Combine(Path.GetTempPath(), name + ".cs"); File.WriteAllText(sourceFile, formattedCompilationUnit.ToFullString(), Encoding.UTF8); } var syntaxTree = IndexCompiler.EnableDebugging ? SyntaxFactory.ParseSyntaxTree(File.ReadAllText(sourceFile), path: sourceFile, encoding: Encoding.UTF8) : SyntaxFactory.ParseSyntaxTree(formattedCompilationUnit.ToFullString()); var compilation = CSharpCompilation.Create( assemblyName: name + ".dll", syntaxTrees: new[] { syntaxTree }, references: IndexCompiler.References, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) .WithOptimizationLevel(IndexCompiler.EnableDebugging ? OptimizationLevel.Debug : OptimizationLevel.Release) ); var code = formattedCompilationUnit.SyntaxTree.ToString(); var asm = new MemoryStream(); var pdb = IndexCompiler.EnableDebugging ? new MemoryStream() : null; var result = compilation.Emit(asm, pdb, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); if (result.Success == false) { IEnumerable <Diagnostic> failures = result.Diagnostics .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error); var sb = new StringBuilder(); sb.AppendLine($"Failed to compile sorter '{originalName}'"); sb.AppendLine(); sb.AppendLine(code); sb.AppendLine(); foreach (var diagnostic in failures) { sb.AppendLine(diagnostic.ToString()); } throw new SorterCompilationException(sb.ToString()); } asm.Position = 0; Assembly assembly; if (IndexCompiler.EnableDebugging) { pdb.Position = 0; assembly = AssemblyLoadContext.Default.LoadFromStream(asm, pdb); } else { assembly = AssemblyLoadContext.Default.LoadFromStream(asm); } var type = assembly.GetType(originalName); if (type == null) { foreach (var exportedType in assembly.GetExportedTypes()) { if (exportedType.Name != originalName) { continue; } type = exportedType; break; } } if (type == null) { throw new SorterCompilationException($"Could not find type '{originalName}' in given assembly."); } return((fieldName, numHits, sortPos, reversed, diagnostics) => { var instance = Activator.CreateInstance(type, fieldName, numHits, sortPos, reversed, diagnostics) as FieldComparator; if (instance == null) { throw new InvalidOperationException($"Created sorter does not inherit from '{nameof(FieldComparator)}' class."); } return instance; }); }
public void ParseOfNonCommandTagsShouldNotDistrubtFormatting() { const string TEMPLATE = "<a/>bcd${Text}slk"; const string FORMATTED = "<a/>bcd12345slk"; var model = new TestModel(); model.Text = "12345"; var formatter = new Formatter(TEMPLATE).Parse(); string formatted = formatter.Format(model); Assert.That(formatted, Is.EqualTo(FORMATTED)); Assert.That(formatter.ParsedTemplate.Count, Is.EqualTo(3)); }
public void Format_should_format_correctly() { var sut = new Formatter(); Assert.Equal(TestGameString, sut.Format(_testGame)); }
public void Setting_Empty_String_Should_Be_Parsed_Correctly() { const string TEMPLATE = "<c:set value='' var='Text' scope='Model'/>"; var model = new TestModel(); model.Text = "aaa"; var formatter = new Formatter(TEMPLATE).Parse(); formatter.Format(model); Console.WriteLine($"[{model.Text}]"); }
/// <summary> /// General verifier for codefixes. /// Creates a Document from the source string, then gets diagnostics on it and /// applies the relevant codefixes. /// Then gets the string after the codefix is applied and compares it with the /// expected result. /// Note: If any codefix causes new diagnostics to show up, the test fails unless /// allowNewCompilerDiagnostics is set to true. /// </summary> /// <param name="language"> The language the source code is in </param> /// <param name="analyzer"> The analyzer to be applied to the source code </param> /// <param name="codeFixProvider"> /// The codefix to be applied to the code wherever /// the relevant Diagnostic is found /// </param> /// <param name="oldSource"> /// A class in the form of a string before the CodeFix was /// applied to it /// </param> /// <param name="newSource"> /// A class in the form of a string after the CodeFix was /// applied to it /// </param> /// <param name="codeFixIndex"> /// Index determining which codefix to apply if there /// are multiple /// </param> /// <param name="allowNewCompilerDiagnostics"> /// A bool controlling whether or not the test will fail if the CodeFix introduces /// other warnings after being applied /// </param> public static VerifyCodeFixProviderResult VerifyFix(this CodeFixProvider codeFixProvider, string language, DiagnosticAnalyzer analyzer, string oldSource, string newSource, int?codeFixIndex, bool allowNewCompilerDiagnostics, IEnumerable <MetadataReference> additionalReferences = null) { var document = DiagnosticAnalyzerTestExtensions.CreateDocument(oldSource, language, additionalReferences); var analyzerDiagnostics = analyzer.GetSortedDiagnosticsFromDocuments(new[] { document }); var compilerDiagnostics = document.GetCompilerDiagnostics(); var attempts = analyzerDiagnostics.Length; for (var i = 0; i < attempts; ++i) { var actions = new List <CodeAction>(); var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); codeFixProvider.RegisterCodeFixesAsync(context).Wait(); if (!actions.Any()) { break; } if (codeFixIndex != null) { document = document.ApplyFix(actions.ElementAt((int)codeFixIndex)); break; } document = document.ApplyFix(actions.ElementAt(0)); analyzerDiagnostics = analyzer.GetSortedDiagnosticsFromDocuments(new[] { document }); var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, document.GetCompilerDiagnostics()); //check if applying the code fix introduced any new compiler diagnostics if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, document.GetCompilerDiagnostics()); var msg = GetNewComilerDiagnosticsIntroducedMessage(document, newCompilerDiagnostics); return(VerifyCodeFixProviderResult.Fail(msg)); } //check if there are analyzer diagnostics left after the code fix if (!analyzerDiagnostics.Any()) { break; } } //after applying all of the code fixes, compare the resulting string to the inputted one var actual = document.GetStringFromDocument(); return(newSource.Equals(actual) ? VerifyCodeFixProviderResult.Ok() : VerifyCodeFixProviderResult.Fail(newSource, actual)); }
public void TestParseOfNonTagQuotes() { var formatter = new Formatter("<a href=\"${'1' + '1'}\"/>").Parse(); Assert.That(formatter.Format(new TagModel(this)), Is.EqualTo("<a href=\"2\"/>")); }
public void Format(object key, object value, string expectedResult) { KeyValuePair <object, object> entry = new KeyValuePair <object, object>(key, value); Assert.AreEqual(expectedResult, Formatter.Format(entry)); }
public void CommentedObjectPropertyTextShouldNotBeChanged() { const string TEMPLATE = "abcd'\\$\\{Text\\}'efgh${Text}"; const string FORMATTED = "abcd'${Text}'efgh12345"; var model = new TestModel(); model.Text = "12345"; var formatter = new Formatter(TEMPLATE).Parse(); string formatted = formatter.Format(model); Assert.That(formatted, Is.EqualTo(FORMATTED)); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest var diagnostic = context.Diagnostics.First(); if (diagnostic.Id == StacksAnalyzer.CommandsEndWithCommand.Id) { var diagnosticSpan = diagnostic.Location.SourceSpan; // Find the type declaration identified by the diagnostic. var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <TypeDeclarationSyntax>().First(); // Register a code action that will invoke the fix. context.RegisterCodeFix( CodeAction.Create( title: "Append 'Command'", createChangedSolution: c => this.AppendCommandText(context.Document, "Command", declaration, c), equivalenceKey: "Append 'Command'"), diagnostic); } else if (diagnostic.Id == StacksAnalyzer.EventsEndWithEvents.Id) { var diagnosticSpan = diagnostic.Location.SourceSpan; // Find the type declaration identified by the diagnostic. var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType <TypeDeclarationSyntax>().First(); // Register a code action that will invoke the fix. context.RegisterCodeFix( CodeAction.Create( title: "Append 'Event'", createChangedSolution: c => this.AppendCommandText(context.Document, "Event", declaration, c), equivalenceKey: "Append 'Event'"), diagnostic); } else if (diagnostic.Id == StacksAnalyzer.MessagePropertiesAreImmutable.Id) { var diagnosticSpan = diagnostic.Location.SourceSpan; var property = root.FindNode(diagnosticSpan) as PropertyDeclarationSyntax; // Register a code action that will invoke the fix. context.RegisterCodeFix( CodeAction.Create( title: "Remove setter", createChangedDocument: async c => { var previousWhiteSpacesToken = SF.Token(property.GetLeadingTrivia(), SyntaxKind.StringLiteralToken, SyntaxTriviaList.Empty); var target = property.WithModifiers(SF.TokenList(previousWhiteSpacesToken, SF.Token(SyntaxKind.PublicKeyword))) .WithAccessorList(SF.AccessorList(SF.List(new[] { SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)) }))); var updated = await context.Document.GetSyntaxRootAsync(c); return(context.Document.WithSyntaxRoot(updated.ReplaceNode(property, new[] { target }))); }, equivalenceKey: "Remove setter"), diagnostic); context.RegisterCodeFix( CodeAction.Create( title: "Make setter private", createChangedDocument: async c => { var previousWhiteSpacesToken = SF.Token(property.GetLeadingTrivia(), SyntaxKind.StringLiteralToken, SyntaxTriviaList.Empty); var target = property.WithModifiers(SF.TokenList(previousWhiteSpacesToken, SF.Token(SyntaxKind.PublicKeyword))) .WithAccessorList(SF.AccessorList(SF.List(new[] { SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)), SF.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) .WithModifiers(SF.TokenList(SF.Token(SyntaxKind.PrivateKeyword))) .WithSemicolonToken(SF.Token(SyntaxKind.SemicolonToken)) }))); var updated = await context.Document.GetSyntaxRootAsync(c); return(context.Document.WithSyntaxRoot(updated.ReplaceNode(property, new[] { target }))); }, equivalenceKey: "Make setter private"), diagnostic); } else if (diagnostic.Id == StacksAnalyzer.UseCaseShouldHaveRules.Id) { var diagnosticSpan = diagnostic.Location.SourceSpan; var property = root.FindNode(diagnosticSpan) as ClassDeclarationSyntax; context.RegisterCodeFix( CodeAction.Create( title: "Create business rule", createChangedDocument: async c => { //property.Identifier.ValueText; var cu = SF.CompilationUnit().AddUsings( SF.UsingDirective(SF.IdentifierName("System")), SF.UsingDirective(SF.IdentifierName("Slalom.Stacks.Messaging.Validation"))); NamespaceDeclarationSyntax namespaceDeclarationSyntax = null; if (!SyntaxNodeHelper.TryGetParentSyntax(property, out namespaceDeclarationSyntax)) { } var ns = SF.NamespaceDeclaration(namespaceDeclarationSyntax.Name); var comp = await context.Document.Project.GetCompilationAsync(); string name = property.Identifier.Value + "_rule"; var command = ((IdentifierNameSyntax)((GenericNameSyntax)property.BaseList.Types[0].Type).TypeArgumentList.Arguments[0]).Identifier.ValueText; //if (comp.GetSymbolsWithName(x => x == name) != null) //{ // int i = 1; // var current = name + i; // while (comp.GetSymbolsWithName(x => x == current) != null) // { // i++; // } //} var cl = SF.ClassDeclaration(name) .WithModifiers(SF.TokenList(SF.Token(SyntaxKind.PublicKeyword))) .AddBaseListTypes(SF.SimpleBaseType(SF.ParseTypeName("BusinessRule<" + command + ">"))); ns = ns.AddMembers(cl); cu = cu.AddMembers(ns); SyntaxNode formattedNode = Formatter.Format(cu, context.Document.Project.Solution.Workspace); StringBuilder sb = new StringBuilder(); using (StringWriter writer = new StringWriter(sb)) { formattedNode.WriteTo(writer); } return(context.Document.Project.AddDocument(name + ".cs", sb.ToString(), namespaceDeclarationSyntax.Name.ToString().Split('.').Skip(1).Concat(new[] { "Rules" }))); }, equivalenceKey: "Create business rule"), diagnostic); } }
public void Then_All_Rows_Should_Have_The_Line_Prefix_At_Start_Of_Row() { var prefix = "ThisIsAPrefix"; var formatter = new Formatter<DummyObject>() .With(y => y.SomeInt, prefix.Length, 5, y => y.ToString("00000")) .With(y => y.SomeString, prefix.Length + 5, 6, y => y.ToString().PadLeft(6, '_')) .WithLinePrefix(prefix); var result = formatter.Format(_objectsToFormat); foreach (var item in result) { Assert.IsTrue(item.StartsWith(prefix)); } }
/// <summary> /// Writes a formatted string to this console's output stream using /// the specified format string and arguments. /// </summary> /// <param name="fmt"> /// A format string as described in <a /// href="../util/Formatter.html#syntax">Format string syntax</a> /// </param> /// <param name="args"> /// Arguments referenced by the format specifiers in the format /// string. If there are more arguments than format specifiers, the /// extra arguments are ignored. The number of arguments is /// variable and may be zero. The maximum number of arguments is /// limited by the maximum dimension of a Java array as defined by /// <cite>The Java™ Virtual Machine Specification</cite>. /// The behaviour on a /// <tt>null</tt> argument depends on the <a /// href="../util/Formatter.html#syntax">conversion</a>. /// </param> /// <exception cref="IllegalFormatException"> /// If a format string contains an illegal syntax, a format /// specifier that is incompatible with the given arguments, /// insufficient arguments given the format string, or other /// illegal conditions. For specification of all possible /// formatting errors, see the <a /// href="../util/Formatter.html#detail">Details</a> section /// of the formatter class specification. /// </exception> /// <returns> This console </returns> public Console Format(String fmt, params Object[] args) { Formatter.Format(fmt, args).Flush(); return(this); }
public void HandOverVariableScope() { var table = new Hashtable(); table.Add("some", new Hashtable()); var formatter = new Formatter("<c:set var='some.a' scope='Model'>AA</c:set><sharp:include file='SharpTags/c.htm'/>").Parse(); Assert.That(formatter.Format(new TagModel(table)), Is.EqualTo("bbAAbb")); }
private string GenerateUnitTestContents(TestGenerationContext context) { TestFramework testFramework = context.TestFramework; MockFramework mockFramework = context.MockFramework; string pascalCaseShortClassName = null; foreach (string suffix in ClassSuffixes) { if (className.EndsWith(suffix)) { pascalCaseShortClassName = suffix; break; } } if (pascalCaseShortClassName == null) { pascalCaseShortClassName = className; } string classVariableName = pascalCaseShortClassName.Substring(0, 1).ToLowerInvariant() + pascalCaseShortClassName.Substring(1); string fileTemplate = StaticBoilerplateSettings.GetTemplate(mockFramework, TemplateType.File); var builder = new StringBuilder(); for (int i = 0; i < fileTemplate.Length; i++) { char c = fileTemplate[i]; if (c == '$') { int endIndex = -1; for (int j = i + 1; j < fileTemplate.Length; j++) { if (fileTemplate[j] == '$') { endIndex = j; break; } } if (endIndex < 0) { // We couldn't find the end index for the replacement property name. Continue. builder.Append(c); } else { // Calculate values on demand from switch statement. Some are preset values, some need a bit of calc like base name, // some are dependent on the test framework (attributes), some need to pull down other templates and loop through mock fields string propertyName = fileTemplate.Substring(i + 1, endIndex - i - 1); switch (propertyName) { case "UsingStatements": WriteUsings(builder, context); break; case "Namespace": builder.Append(context.UnitTestNamespace); break; case "MockFieldDeclarations": WriteMockFieldDeclarations(builder, context); break; case "MockFieldInitializations": WriteMockFieldInitializations(builder, context); break; case "ExplicitConstructor": WriteExplicitConstructor(builder, context, FindIndent(fileTemplate, i)); break; case "ClassName": builder.Append(context.ClassName); break; case "ClassNameShort": builder.Append(GetShortClassName(context.ClassName)); break; case "ClassNameShortLower": builder.Append(GetShortClassNameLower(context.ClassName)); break; case "TestClassAttribute": builder.Append(TestFrameworkAbstraction.GetTestClassAttribute(testFramework)); break; case "TestInitializeAttribute": builder.Append(TestFrameworkAbstraction.GetTestInitializeAttribute(testFramework)); break; case "TestCleanupAttribute": builder.Append(TestFrameworkAbstraction.GetTestCleanupAttribute(testFramework)); break; case "TestMethodAttribute": builder.Append(TestFrameworkAbstraction.GetTestMethodAttribute(testFramework)); break; default: // We didn't recognize it, just pass through. builder.Append($"${propertyName}$"); break; } i = endIndex; } } else { builder.Append(c); } } SyntaxTree tree = CSharpSyntaxTree.ParseText(builder.ToString()); SyntaxNode formattedNode = Formatter.Format(tree.GetRoot(), CreateUnitTestBoilerplateCommandPackage.VisualStudioWorkspace); return(formattedNode.ToString()); }
private void ConvertDialog() { var dialogFiles = Tig.FS.ListDirectory("dlg") .Where(f => f.EndsWith(".dlg")) .Distinct() .ToList(); Console.WriteLine($"Found {dialogFiles.Count} dialog files."); var dlgFilePattern = new Regex(@"(\d{5}).*"); foreach (var dialogFile in dialogFiles) { var m = dlgFilePattern.Match(dialogFile); if (!m.Success) { Console.WriteLine($"Skipping dialog file that doesn't match expected pattern: {dialogFile}'."); continue; } var scriptId = int.Parse(m.Groups[1].Value); var associatedScript = _convertedScripts.FirstOrDefault(s => s.Type == ScriptType.Object && s.ScriptId == scriptId); if (associatedScript == null) { Console.WriteLine($"Dialog file {dialogFile} with id {scriptId} has no associated script!"); continue; } var outputDir = Path.Join( Path.GetDirectoryName(associatedScript.OutputPath), "Dialog" ); Directory.CreateDirectory(Path.Combine(_outputDirectory, outputDir)); var outputPath = Path.Join(outputDir, Path.GetFileNameWithoutExtension(associatedScript.OutputPath) + "Dialog.cs"); if (_writeDialog) { File.Delete(Path.Combine(_outputDirectory, outputPath)); } var dialogContent = Tig.FS.ReadTextFile("dlg/" + dialogFile); var parser = new DialogScriptParser(dialogFile, dialogContent); // We're going to build a class file for the dialog script that contains two methods, // and extends from the object script of the same script id var conditions = new List <(int, string, string)>(); var effects = new List <(int, string, string)>(); var skillChecks = new List <(int, SkillCheck)>(); while (parser.GetSingleLine(out var dialogLine, out var fileLine)) { var effectPython = dialogLine.effectField; if (effectPython == "pc.barter(npc)" && dialogLine.txt.StartsWith("b:", StringComparison.OrdinalIgnoreCase)) { continue; // Skip bogus barter effect (this is implied by B:) } try { if (!string.IsNullOrEmpty(effectPython)) { var converted = converter.ConvertSnippet(effectPython, associatedScript, DialogContext); effects.Add((dialogLine.key, effectPython, converted)); } } catch (Exception e) { Console.WriteLine( $"[e] Failed to convert effect for line {dialogLine.key} ({effectPython}): {e}"); effects.Add((dialogLine.key, effectPython, null)); } if (dialogLine.IsPcLine) { var conditionPython = dialogLine.testField; try { if (!string.IsNullOrEmpty(conditionPython)) { foreach (var skillCheck in converter.FindSkillChecks(conditionPython)) { skillChecks.Add((dialogLine.key, skillCheck)); } var converted = converter.ConvertSnippet(conditionPython, associatedScript, DialogContext); conditions.Add((dialogLine.key, conditionPython, converted)); } } catch (Exception e) { Console.WriteLine( $"[e] Failed to convert condition for line {dialogLine.key} ({conditionPython}): {e}"); conditions.Add((dialogLine.key, conditionPython, null)); } } } if (_writeDialog) { var dialogScript = new StringBuilder(); dialogScript.AppendLine(@" using System; using System.Collections.Generic; using System.Diagnostics; using OpenTemple.Core.GameObject; using OpenTemple.Core.Systems; using OpenTemple.Core.Systems.Dialog; using OpenTemple.Core.Systems.Feats; using OpenTemple.Core.Systems.D20; using OpenTemple.Core.Systems.Script; using OpenTemple.Core.Systems.Spells; using OpenTemple.Core.Systems.GameObjects; using OpenTemple.Core.Systems.D20.Conditions; using OpenTemple.Core.Location; using OpenTemple.Core.Systems.ObjScript; using OpenTemple.Core.Ui; using System.Linq; using OpenTemple.Core.Systems.Script.Extensions; using OpenTemple.Core.Utils; using static OpenTemple.Core.Systems.Script.ScriptUtilities; "); dialogScript.AppendLine("namespace " + associatedScript.Namespace + ".Dialog"); dialogScript.AppendLine("{"); dialogScript.Append("[DialogScript(").Append(associatedScript.ScriptId).AppendLine(")]"); dialogScript.AppendLine("public class " + associatedScript.ClassName + "Dialog : " + associatedScript.ClassName + ", IDialogScript"); dialogScript.AppendLine("{"); WriteDialogMethod(dialogScript, conditions, false); WriteDialogMethod(dialogScript, effects, true); WriteSkillChecksMethod(dialogScript, skillChecks); dialogScript.AppendLine("}"); dialogScript.AppendLine("}"); var parseOptions = new CSharpParseOptions(LanguageVersion.Latest); var syntaxTree = CSharpSyntaxTree.ParseText(dialogScript.ToString(), parseOptions); var formattedNode = Formatter.Format(syntaxTree.GetRoot(), workspace); File.WriteAllText(Path.Join(_outputDirectory, outputPath), formattedNode.ToFullString()); } } }
private string GenerateUnitTestContentsOld( string unitTestNamespace, string className, string classNamespace, IList <InjectableProperty> properties, IList <InjectableType> constructorTypes) { TestFramework testFramework = Utilities.FindTestFramework(this.SelectedProject.Project); MockFramework mockFramework = Utilities.FindMockFramework(this.SelectedProject.Project); if (mockFramework == MockFramework.Unknown) { mockFramework = MockFramework.Moq; } string pascalCaseShortClassName = null; foreach (string suffix in ClassSuffixes) { if (className.EndsWith(suffix)) { pascalCaseShortClassName = suffix; break; } } if (pascalCaseShortClassName == null) { pascalCaseShortClassName = className; } string classVariableName = pascalCaseShortClassName.Substring(0, 1).ToLowerInvariant() + pascalCaseShortClassName.Substring(1); List <InjectableType> injectedTypes = new List <InjectableType>(properties); injectedTypes.AddRange(constructorTypes.Where(t => t != null)); var mockFields = new List <MockField>(); foreach (InjectableType injectedType in injectedTypes) { mockFields.Add( new MockField( mockFramework == MockFramework.SimpleStubs ? "stub" + injectedType.TypeBaseName : "mock" + injectedType.TypeBaseName, mockFramework == MockFramework.SimpleStubs ? "Stub" + injectedType.TypeName : injectedType.TypeName)); } List <string> namespaces = new List <string>(); namespaces.AddRange(MockFrameworkAbstraction.GetUsings(mockFramework)); namespaces.Add(TestFrameworkAbstraction.GetUsing(testFramework)); namespaces.Add(classNamespace); namespaces.AddRange(injectedTypes.Select(t => t.TypeNamespace)); namespaces = namespaces.Distinct().ToList(); namespaces.Sort(StringComparer.Ordinal); StringBuilder builder = new StringBuilder(); foreach (string ns in namespaces) { builder.AppendLine($"using {ns};"); } builder.Append( Environment.NewLine + "namespace "); builder.Append(unitTestNamespace); builder.Append( Environment.NewLine + "{" + Environment.NewLine + $"[{TestFrameworkAbstraction.GetTestClassAttribute(testFramework)}]" + Environment.NewLine + "public class "); builder.Append(className); builder.Append( "Tests" + Environment.NewLine + "{" + Environment.NewLine); if (mockFramework == MockFramework.Moq) { builder.Append("private MockRepository mockRepository;" + Environment.NewLine); if (mockFields.Count > 0) { builder.AppendLine(); } } foreach (MockField field in mockFields) { if (mockFramework == MockFramework.SimpleStubs) { builder.AppendLine($"private {field.TypeName} {field.Name};"); } else { builder.AppendLine($"private Mock<{field.TypeName}> {field.Name};"); } } builder.Append( Environment.NewLine + $"[{TestFrameworkAbstraction.GetTestInitializeAttribute(testFramework)}]" + Environment.NewLine + "public void TestInitialize()" + Environment.NewLine + "{" + Environment.NewLine); if (mockFramework == MockFramework.Moq) { builder.AppendLine("this.mockRepository = new MockRepository(MockBehavior.Strict);"); if (mockFields.Count > 0) { builder.AppendLine(); } } foreach (MockField field in mockFields) { string fieldCreationStatement; if (mockFramework == MockFramework.SimpleStubs) { fieldCreationStatement = $"new {field.TypeName}()"; } else { fieldCreationStatement = $"this.mockRepository.Create<{field.TypeName}>()"; } builder.AppendLine($"this.{field.Name} = {fieldCreationStatement};"); } builder.Append( "}" + Environment.NewLine + Environment.NewLine); if (mockFramework == MockFramework.Moq) { builder.Append( $"[{TestFrameworkAbstraction.GetTestCleanupAttribute(testFramework)}]" + Environment.NewLine + "public void TestCleanup()" + Environment.NewLine + "{" + Environment.NewLine + "this.mockRepository.VerifyAll();" + Environment.NewLine + "}" + Environment.NewLine + Environment.NewLine); } builder.Append( $"[{TestFrameworkAbstraction.GetTestMethodAttribute(testFramework)}]" + Environment.NewLine + "public void TestMethod1()" + Environment.NewLine + "{" + Environment.NewLine + "" + Environment.NewLine + "" + Environment.NewLine); builder.AppendLine($"{className} {classVariableName} = this.Create{pascalCaseShortClassName}();"); builder.AppendLine(""); builder.AppendLine(""); builder.AppendLine("}"); builder.AppendLine(); builder.AppendLine($"private {className} Create{pascalCaseShortClassName}()"); builder.AppendLine("{"); builder.Append($"return new {className}"); if (constructorTypes.Count > 0) { builder.AppendLine("("); for (int i = 0; i < constructorTypes.Count; i++) { string mockReferenceStatement; InjectableType constructorType = constructorTypes[i]; if (constructorType == null) { mockReferenceStatement = "TODO"; } else if (mockFramework == MockFramework.SimpleStubs) { mockReferenceStatement = $"this.stub{constructorType.TypeBaseName}"; } else { mockReferenceStatement = $"this.mock{constructorType.TypeBaseName}.Object"; } builder.Append($" {mockReferenceStatement}"); if (i < constructorTypes.Count - 1) { builder.AppendLine(","); } } builder.Append(")"); } else if (properties.Count == 0) { builder.Append("()"); } if (properties.Count > 0) { builder.AppendLine(); builder.AppendLine("{"); foreach (InjectableProperty property in properties) { string mockReferenceStatement; if (mockFramework == MockFramework.SimpleStubs) { mockReferenceStatement = $"this.stub{property.TypeBaseName}"; } else { mockReferenceStatement = $"this.mock{property.TypeBaseName}.Object"; } builder.AppendLine($"{property.Name} = {mockReferenceStatement},"); } builder.Append(@"}"); } builder.AppendLine(";"); builder.AppendLine("}"); builder.AppendLine("}"); builder.AppendLine("}"); SyntaxTree tree = CSharpSyntaxTree.ParseText(builder.ToString()); SyntaxNode formattedNode = Formatter.Format(tree.GetRoot(), CreateUnitTestBoilerplateCommandPackage.VisualStudioWorkspace); return(formattedNode.ToString()); //return builder.ToString(); }
public async Task Run() { var token = default(CancellationToken); if (act is InsertionAction insertionAction) { var insertion = await insertionAction.CreateInsertion(token).ConfigureAwait(false); var document = await IdeApp.Workbench.OpenDocument(insertion.Location.SourceTree.FilePath, documentContext.Project); var parsedDocument = await document.UpdateParseDocument(); var model = await document.AnalysisDocument.GetSemanticModelAsync(token); if (parsedDocument != null) { var insertionPoints = InsertionPointService.GetInsertionPoints( document.Editor, model, insertion.Type, insertion.Location.SourceSpan.Start ); var options = new InsertionModeOptions( insertionAction.Title, insertionPoints, point => { if (!point.Success) { return; } var node = Formatter.Format(insertion.Node, document.RoslynWorkspace, document.GetOptionSet(), token); point.InsertionPoint.Insert(document.Editor, document, node.ToString()); // document = await Simplifier.ReduceAsync(document.AnalysisDocument, Simplifier.Annotation, cancellationToken: token).ConfigureAwait(false); } ); document.Editor.StartInsertionMode(options); return; } } var oldSolution = documentContext.AnalysisDocument.Project.Solution; var updatedSolution = oldSolution; using (var undo = editor.OpenUndoGroup()) { foreach (var operation in await act.GetOperationsAsync(token)) { var applyChanges = operation as ApplyChangesOperation; if (applyChanges == null) { operation.TryApply(documentContext.RoslynWorkspace, new RoslynProgressTracker(), token); continue; } if (updatedSolution == oldSolution) { updatedSolution = applyChanges.ChangedSolution; } operation.TryApply(documentContext.RoslynWorkspace, new RoslynProgressTracker(), token); } } await TryStartRenameSession(documentContext.RoslynWorkspace, oldSolution, updatedSolution, token); }
private string ModificationValueString(ModificationValue val, ResourceFormat fmt, bool depth) { string s = ""; bool uintTex = (fmt.compType == FormatComponentType.UInt); bool sintTex = (fmt.compType == FormatComponentType.SInt); int numComps = (int)(fmt.compCount); if (!depth) { if (uintTex) { for (int i = 0; i < numComps; i++) { s += colourLetterPrefix[i] + val.col.value.u[i].ToString() + "\n"; } } else if (sintTex) { for (int i = 0; i < numComps; i++) { s += colourLetterPrefix[i] + val.col.value.i[i].ToString() + "\n"; } } else { for (int i = 0; i < numComps; i++) { s += colourLetterPrefix[i] + Formatter.Format(val.col.value.f[i]) + "\n"; } } } if (val.depth >= 0.0f) { s += "\nD: " + Formatter.Format(val.depth); } else if (val.depth < -1.5f) { s += "\nD: ?"; } else { s += "\nD: -"; } if (val.stencil >= 0) { s += String.Format("\nS: 0x{0:X2}", val.stencil); } else if (val.stencil == -2) { s += "\nS: ?"; } else { s += "\nS: -"; } return(s); }
public void ObjectPropertyTextTemplateAtTheEndOfTheInputShouldBeChanged() { const string TEMPLATE = "abc${Text}"; const string FORMATTED = "abc12345"; var model = new TestModel(); model.Text = "12345"; var formatter = new Formatter(TEMPLATE).Parse(); string formatted = formatter.Format(model); Assert.That(formatted, Is.EqualTo(FORMATTED)); }
public PixelHistoryView(Core core, FetchTexture tex, Point pt, UInt32 sampleIdx, float rangemin, float rangemax, bool[] channels) { InitializeComponent(); Icon = global::renderdocui.Properties.Resources.icon; m_Core = core; events.Font = core.Config.PreferredFont; texture = tex; pixel = pt; rangeMin = rangemin; rangeMax = rangemax; visibleChannels = channels; sample = sampleIdx; Text = String.Format("Pixel History on {0} for ({1}, {2})", tex.name, pt.X, pt.Y); if (tex.msSamp > 1) { Text += String.Format(" @ Sample {0}", sample); } string channelStr = ""; numChannels = 0; channelIdx = 0; if (channels[0]) { channelStr += "R"; numChannels++; channelIdx = 0; } if (channels[1]) { channelStr += "G"; numChannels++; channelIdx = 1; } if (channels[2]) { channelStr += "B"; numChannels++; channelIdx = 2; } channelStr += " channel"; if (numChannels > 1) { channelStr += "s"; } // if alpha channel is enabled it only does anything if the // other channels are all disabled. There is no RGBA preview if (numChannels == 0 && channels[3]) { channelStr = "Alpha"; numChannels = 1; channelIdx = 3; } historyContext.Text = String.Format("Preview colours displayed in visible range {0} - {1} with {2} visible.", Formatter.Format(rangemin), Formatter.Format(rangemax), channelStr) + Environment.NewLine; historyContext.Text += Environment.NewLine; historyContext.Text += "Double click to jump to an event." + Environment.NewLine; historyContext.Text += "Right click to debug an event, or hide failed events."; eventsHidden.Text = ""; modifications = null; events.BeginUpdate(); events.Nodes.Clear(); events.Nodes.Add(new object[] { "Loading...", "", "", "", "" }); events.EndUpdate(); }
public void PlainTextTempalteShouldNotBeChanged() { const string TEMPLATE = "abcdefgh"; var formatter = new Formatter(TEMPLATE).Parse(); string formatted = formatter.Format(new object()); Assert.That(formatted, Is.EqualTo(TEMPLATE)); }
private void generateBySetToolStripMenuItem_Click(object sender, EventArgs e) { //generator. DirectoryInfo dir = new DirectoryInfo("c:/gram_pv/pv_deps_grams"); string pathToGrammar = ""; string fileToSaveTest = ""; bool testPassed = false; bool TestGenerated = false; foreach (FileInfo f in dir.GetFiles()) { pathToGrammar = f.FullName; fileToSaveTest = f.Name.Substring(4, f.Name.Length - 8); if (File.Exists("c:/gram_pv/pv_deps_tests/SF1D-test_" + fileToSaveTest + ".c")) { continue; } Grammar gr = Grammar.FromTextFile(pathToGrammar); Generator generator = new Generator(gr); generator.Options.LevelRestriction = 1000; generator.Options.AlternativeAlg = AlternativeSelectAlg.RndDistr; generator.Options.RREnable = true; generator.Options.TestsAmount = 1; generator.Options.AllEnumInOne = false; generator.ConfigFilePath = mTaskDoc.CurrentFilePath; TestGenerated = false; while (!TestGenerated) { string s = generator.GenerateAll(); if (mGenerationOptionsForm.cbPPprocessingEnabled.Checked) { string configDir = Program.WorkingDir + VALID_PROCESSING_PATH; string[] myArgs = new string[4] { "-c-10", "-l-C", "-p-" + configDir + "config.xml", "-s-ForTests" }; ArgsParser aParser = new ArgsParser(myArgs); ConfigParser parser = new ConfigParser(aParser.configTest, configDir + @"\members.xml"); replaceHolding sFormat = new replaceHolding(s, parser.inds, parser.arrayLength(), parser.IndexCount()); s = sFormat.PrintText(); } else { s = Formatter.Format(s); } // e.Text = s; // Проверка компилятором MinGWProcessing checkMinGW = new MinGWProcessing(); testPassed = checkMinGW.MinGW(s); if (testPassed) { File.WriteAllText("c:/gram_pv/pv_deps_tests/SF1D-test_" + fileToSaveTest + ".c", s); TestGenerated = true; } else { TestGenerated = false; } } } }
public void Setting_Local_Affects_Formatting_Of_Number_EN_After_Cout() { const string TEMPLATE = "<fmt:setLocale value='en-GB' scope='Page'/><c:out value=\"${'0.00'+'1.00'}%\"/>"; const string FORMATTED = "1.00%"; var model = new TestModel(); model.Text = ""; var formatter = new Formatter(TEMPLATE).Parse(); string formatted = formatter.Format(model); Assert.That(formatted, Is.EqualTo(FORMATTED)); }
private void VerifyFix( Document document, DiagnosticAnalyzer analyzerOpt, CodeFixProvider codeFixProvider, string newSource, string newSourceFileName, IEnumerable <TestAdditionalDocument> additionalFiles, int?codeFixIndex, bool allowNewCompilerDiagnostics, bool onlyFixFirstFixableDiagnostic, TestValidationMode validationMode) { var fixableDiagnosticIds = codeFixProvider.FixableDiagnosticIds.ToSet(); Func <IEnumerable <Diagnostic>, ImmutableArray <Diagnostic> > getFixableDiagnostics = diags => diags.Where(d => fixableDiagnosticIds.Contains(d.Id)).ToImmutableArrayOrEmpty(); var analyzerDiagnostics = GetSortedDiagnostics(analyzerOpt, new[] { document }, additionalFiles: additionalFiles, validationMode: validationMode); var compilerDiagnostics = document.GetSemanticModelAsync().Result.GetDiagnostics(); var fixableDiagnostics = getFixableDiagnostics(analyzerDiagnostics.Concat(compilerDiagnostics)); if (fixableDiagnostics.IsDefaultOrEmpty && analyzerOpt != null && analyzerOpt.SupportedDiagnostics.Length == 0) { // Not implemented analyzer return; } var diagnosticIndexToFix = 0; while (diagnosticIndexToFix < fixableDiagnostics.Length) { var actions = new List <CodeAction>(); var context = new CodeFixContext(document, fixableDiagnostics[diagnosticIndexToFix], (a, d) => actions.Add(a), CancellationToken.None); codeFixProvider.RegisterCodeFixesAsync(context).Wait(); if (!actions.Any()) { break; } if (codeFixIndex == null) { codeFixIndex = 0; } if (codeFixIndex >= actions.Count) { throw new Exception($"Unable to invoke code fix at index '{codeFixIndex.Value}', only '{actions.Count}' code fixes were registered."); } document = document.Apply(actions.ElementAt(codeFixIndex.Value)); additionalFiles = document.Project.AdditionalDocuments.Select(a => new TestAdditionalDocument(a)); if (onlyFixFirstFixableDiagnostic) { break; } analyzerDiagnostics = GetSortedDiagnostics(analyzerOpt, new[] { document }, additionalFiles: additionalFiles, validationMode: validationMode); var updatedCompilerDiagnostics = document.GetSemanticModelAsync().Result.GetDiagnostics(); var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, updatedCompilerDiagnostics); if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) { // Format and get the compiler diagnostics again so that the locations make sense in the output document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, document.GetSemanticModelAsync().Result.GetDiagnostics()); Assert.True(false, string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n", newCompilerDiagnostics.Select(d => d.ToString()).Join("\r\n"), document.GetSyntaxRootAsync().Result.ToFullString())); } var newFixableDiagnostics = getFixableDiagnostics(analyzerDiagnostics.Concat(updatedCompilerDiagnostics)); if (fixableDiagnostics.SetEquals(newFixableDiagnostics, DiagnosticComparer.Instance)) { diagnosticIndexToFix++; } else { fixableDiagnostics = newFixableDiagnostics; } } var actualText = GetActualTextForNewDocument(document, newSourceFileName); Assert.Equal(newSource, actualText.ToString()); }
public void TestFSharpTemplate() { var raw = new Hashtable() { {"a", "B"}, {"c", "D"}, {"now", new DateTime(2012,11,5,17,30,0).ToString("dd-MM-yyyy hh:mm:yyyy")} }; var formatter = new Formatter("<!-- This file is generated at ${now} -->\n${a} ==> ${c}").Parse(); Assert.That(formatter.Format(new TagModel(raw)), Is.EqualTo("<!-- This file is generated at 05-11-2012 05:30:2012 -->\nB ==> D")); }
public static void Main(string [] args) { if (args.Length != 2) { Console.WriteLine("Usage: CheeseCake2 FileName OptionFileName"); return; } var sourceFileName = args [0]; var optionFileName = args [1]; var text = File.ReadAllText(sourceFileName); var csharpParseOptions = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Regular, new List <string> { "UNITY_EDITOR", "UNITY_IOS", "UNITY_ANDROID" }); var workspace = new AdhocWorkspace(); var tree = CSharpSyntaxTree.ParseText(text, csharpParseOptions); var userOptions = JsonConvert.DeserializeObject <UserOptions> (File.ReadAllText(optionFileName)); var options = workspace.Options; // FormattingOptions options = options.WithChangedOption(FormattingOptions.IndentationSize, LanguageNames.CSharp, userOptions.FormattingOptions.IndentationSize); options = options.WithChangedOption(FormattingOptions.TabSize, LanguageNames.CSharp, userOptions.FormattingOptions.TabSize); options = options.WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, userOptions.FormattingOptions.UseTabs); options = options.WithChangedOption(FormattingOptions.NewLine, LanguageNames.CSharp, Environment.NewLine); options = options.WithChangedOption(FormattingOptions.SmartIndent, LanguageNames.CSharp, FormattingOptions.IndentStyle.Smart); // CSharpFormattingOptions options = options.WithChangedOption(CSharpFormattingOptions.SpacingAfterMethodDeclarationName, userOptions.CSharpFormattingOptions.SpacingAfterMethodDeclarationName); options = options.WithChangedOption(CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis, userOptions.CSharpFormattingOptions.SpaceWithinMethodDeclarationParenthesis); options = options.WithChangedOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses, userOptions.CSharpFormattingOptions.SpaceBetweenEmptyMethodDeclarationParentheses); options = options.WithChangedOption(CSharpFormattingOptions.SpaceAfterMethodCallName, userOptions.CSharpFormattingOptions.SpaceAfterMethodCallName); options = options.WithChangedOption(CSharpFormattingOptions.SpaceWithinMethodCallParentheses, userOptions.CSharpFormattingOptions.SpaceWithinMethodCallParentheses); options = options.WithChangedOption(CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses, userOptions.CSharpFormattingOptions.SpaceBetweenEmptyMethodCallParentheses); options = options.WithChangedOption(CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword, userOptions.CSharpFormattingOptions.SpaceAfterControlFlowStatementKeyword); options = options.WithChangedOption(CSharpFormattingOptions.SpaceWithinExpressionParentheses, userOptions.CSharpFormattingOptions.SpaceWithinExpressionParentheses); options = options.WithChangedOption(CSharpFormattingOptions.SpaceWithinCastParentheses, userOptions.CSharpFormattingOptions.SpaceWithinCastParentheses); options = options.WithChangedOption(CSharpFormattingOptions.SpaceWithinOtherParentheses, userOptions.CSharpFormattingOptions.SpaceWithinOtherParentheses); options = options.WithChangedOption(CSharpFormattingOptions.SpaceAfterCast, userOptions.CSharpFormattingOptions.SpaceAfterCast); options = options.WithChangedOption(CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration, userOptions.CSharpFormattingOptions.SpacesIgnoreAroundVariableDeclaration); options = options.WithChangedOption(CSharpFormattingOptions.SpaceBeforeOpenSquareBracket, userOptions.CSharpFormattingOptions.SpaceBeforeOpenSquareBracket); options = options.WithChangedOption(CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets, userOptions.CSharpFormattingOptions.SpaceBetweenEmptySquareBrackets); options = options.WithChangedOption(CSharpFormattingOptions.SpaceWithinSquareBrackets, userOptions.CSharpFormattingOptions.SpaceWithinSquareBrackets); options = options.WithChangedOption(CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration, userOptions.CSharpFormattingOptions.SpaceAfterColonInBaseTypeDeclaration); options = options.WithChangedOption(CSharpFormattingOptions.SpaceAfterComma, userOptions.CSharpFormattingOptions.SpaceAfterComma); options = options.WithChangedOption(CSharpFormattingOptions.SpaceAfterDot, userOptions.CSharpFormattingOptions.SpaceAfterDot); options = options.WithChangedOption(CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement, userOptions.CSharpFormattingOptions.SpaceAfterSemicolonsInForStatement); options = options.WithChangedOption(CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration, userOptions.CSharpFormattingOptions.SpaceBeforeColonInBaseTypeDeclaration); options = options.WithChangedOption(CSharpFormattingOptions.SpaceBeforeComma, userOptions.CSharpFormattingOptions.SpaceBeforeComma); options = options.WithChangedOption(CSharpFormattingOptions.SpaceBeforeDot, userOptions.CSharpFormattingOptions.SpaceBeforeDot); options = options.WithChangedOption(CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement, userOptions.CSharpFormattingOptions.SpaceBeforeSemicolonsInForStatement); options = options.WithChangedOption(CSharpFormattingOptions.SpacingAroundBinaryOperator, userOptions.CSharpFormattingOptions.SpacingAroundBinaryOperator); options = options.WithChangedOption(CSharpFormattingOptions.IndentBraces, userOptions.CSharpFormattingOptions.IndentBraces); options = options.WithChangedOption(CSharpFormattingOptions.IndentBlock, userOptions.CSharpFormattingOptions.IndentBlock); options = options.WithChangedOption(CSharpFormattingOptions.IndentSwitchSection, userOptions.CSharpFormattingOptions.IndentSwitchSection); options = options.WithChangedOption(CSharpFormattingOptions.IndentSwitchCaseSection, userOptions.CSharpFormattingOptions.IndentSwitchCaseSection); options = options.WithChangedOption(CSharpFormattingOptions.LabelPositioning, userOptions.CSharpFormattingOptions.LabelPositioning); options = options.WithChangedOption(CSharpFormattingOptions.WrappingPreserveSingleLine, userOptions.CSharpFormattingOptions.WrappingPreserveSingleLine); options = options.WithChangedOption(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, userOptions.CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine); options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInTypes, userOptions.CSharpFormattingOptions.NewLinesForBracesInTypes); options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInMethods, userOptions.CSharpFormattingOptions.NewLinesForBracesInMethods); options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInProperties, userOptions.CSharpFormattingOptions.NewLinesForBracesInProperties); options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInAccessors, userOptions.CSharpFormattingOptions.NewLinesForBracesInAccessors); options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods, userOptions.CSharpFormattingOptions.NewLinesForBracesInAnonymousMethods); options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, userOptions.CSharpFormattingOptions.NewLinesForBracesInControlBlocks); options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes, userOptions.CSharpFormattingOptions.NewLinesForBracesInAnonymousTypes); options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers, userOptions.CSharpFormattingOptions.NewLinesForBracesInObjectCollectionArrayInitializers); options = options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody, userOptions.CSharpFormattingOptions.NewLinesForBracesInLambdaExpressionBody); options = options.WithChangedOption(CSharpFormattingOptions.NewLineForElse, userOptions.CSharpFormattingOptions.NewLineForElse); options = options.WithChangedOption(CSharpFormattingOptions.NewLineForCatch, userOptions.CSharpFormattingOptions.NewLineForCatch); options = options.WithChangedOption(CSharpFormattingOptions.NewLineForFinally, userOptions.CSharpFormattingOptions.NewLineForFinally); options = options.WithChangedOption(CSharpFormattingOptions.NewLineForMembersInObjectInit, userOptions.CSharpFormattingOptions.NewLineForMembersInObjectInit); options = options.WithChangedOption(CSharpFormattingOptions.NewLineForMembersInAnonymousTypes, userOptions.CSharpFormattingOptions.NewLineForMembersInAnonymousTypes); options = options.WithChangedOption(CSharpFormattingOptions.NewLineForClausesInQuery, userOptions.CSharpFormattingOptions.NewLineForClausesInQuery); var formattedRoot = Formatter.Format(tree.GetRoot(), workspace, options); var formattedText = formattedRoot.ToFullString(); File.WriteAllText(sourceFileName, formattedText, Encoding.UTF8); }
public void TestParseOfRandomDollarSigns() { var formatter = new Formatter("A$A").Parse(); Assert.That(formatter.Format(new TagModel(this)), Is.EqualTo("A$A")); }
/// <summary> /// General verifier for Code Fixes. Creates a <see cref="Document"/> from the source /// string, then gets diagnostics on it and applies the relevant Code Fixes. Then gets /// the string after the code fix is applied and compares it with the expected result. /// Note, if any code fix causes new diagnostics to show up, the test fails unless /// <paramref name="allowNewCompilerDiagnostics"/> is set to true. /// </summary> /// <param name="language">The language the source code is in.</param> /// <param name="givenSource">A class in the form of a string before the Code Fix was /// applied to it.</param> /// <param name="expectedSource">A class in the form of a string after the Code Fix was /// applied to it.</param> /// <param name="codeFixIndex">Index determining which Code Fix to apply if there are /// multiple.</param> /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the /// test will fail if the Code Fix introduces other warnings after being applied.</param> /// <exception cref="CompilerDiagnosticsNotAllowedException"></exception> public void VerifyFix(string language, string givenSource, string expectedSource , int?codeFixIndex = null, bool allowNewCompilerDiagnostics = false) { if (IsNullOrEmpty(expectedSource)) { return; } OnVerifyingFix(language, givenSource, expectedSource, codeFixIndex, allowNewCompilerDiagnostics); var document = CreateDocument(givenSource, language); OnDiagnosticAnalyzerRequested(language, out var analyerRequestedArgs); var analyzerDiagnostics = GetSortedDiagnosticsFromCompiledDocuments(analyerRequestedArgs.Analyzer, document); var compilerDiagnostics = GetCompilerDiagnostics(document).ToArray(); // ReSharper disable once PossibleMultipleEnumeration var attempts = analyzerDiagnostics.Count(); OnCodeFixProviderRequired(language, out var codeFixProviderArgs); // ReSharper disable once PossibleMultipleEnumeration // Check if there are analyzer diagnostics left after the code fix. for (var i = 0; i < attempts && analyzerDiagnostics.Any(); ++i) { var actions = new List <CodeAction>(); // ReSharper disable once PossibleMultipleEnumeration var context = new CodeFixContext(document, analyzerDiagnostics.First() , (a, d) => actions.Add(a), CancellationToken.None); codeFixProviderArgs.CodeFixProvider.RegisterCodeFixesAsync(context).Wait(); if (!actions.Any()) { break; } if (codeFixIndex != null) { document = ApplyFix(document, actions.ElementAt((int)codeFixIndex)); break; } document = ApplyFix(document, actions.ElementAt(0)); analyzerDiagnostics = GetSortedDiagnosticsFromCompiledDocuments(analyerRequestedArgs.Analyzer, document); var newCompilerDiagnostics = FilterNewDiagnostics(compilerDiagnostics , GetCompilerDiagnostics(document)).SortDiagnostics().ToArray(); if (allowNewCompilerDiagnostics || !newCompilerDiagnostics.Any()) { continue; } // Format and get the compiler diagnostics again so that the locations make sense in the output. document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result , Formatter.Annotation, document.Project.Solution.Workspace)); newCompilerDiagnostics = FilterNewDiagnostics(compilerDiagnostics , GetCompilerDiagnostics(document)).SortDiagnostics().ToArray(); throw new CompilerDiagnosticsNotAllowedException( "Fix introduced new compiler diagnostics:" + $"\r\n{Join("\r\n", newCompilerDiagnostics.Select(d => $"{d}"))}" + $"\r\n\r\nNew document:\r\n{document.GetSyntaxRootAsync().Result.ToFullString()}"); } // After applying all of the Code Fixes, compare the resulting string to the inputted one. var fixedSource = GetStringFromDocument(document); OnAssertCodeFixSuccess(givenSource, fixedSource, expectedSource); }
public void TwoObjectPropertiesTextTemplateShouldBeChanged() { const string TEMPLATE = "abcd${Text}efgh${Text}"; const string FORMATTED = "abcd12345efgh12345"; var model = new TestModel(); model.Text = "12345"; var formatter = new Formatter(TEMPLATE).Parse(); string formatted = formatter.Format(model); Assert.That(formatted, Is.EqualTo(FORMATTED)); }
private static async Task <int> Main(string[] args) { FixClientBuilder(); // TODO: Figure out why `dotnet run` from generateapis.sh is sending 6 args instead of 3 as in: arg1 arg2 arg3 arg1 arg2 arg3 if (args.Length < 3) { Console.WriteLine("Arguments: <project file> <api client name> <user client name>"); return(1); } var projectFile = args[0]; var apiClientName = args[1]; var userClientName = args[2]; MSBuildLocator.RegisterDefaults(); var workspace = MSBuildWorkspace.Create(new Dictionary <string, string> { ["TargetFramework"] = "net45" }); Project project; try { project = await workspace.OpenProjectAsync(projectFile); } catch (FileNotFoundException) { Console.WriteLine($"Could not find project file {projectFile}"); return(2); } var compilation = await project.GetCompilationAsync(); var symbols = compilation.GetSymbolsWithName(name => name == apiClientName, SymbolFilter.Type).ToList(); if (symbols.Count != 1) { Console.WriteLine($"Could not find type {apiClientName}"); var errors = compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToList(); if (errors.Count != 0) { Console.WriteLine($"Errors: {errors.Count}, first error: {errors[0]}"); } return(2); } var apiClientSymbol = (INamedTypeSymbol)symbols[0]; // Find the API client from a generated file (there should be only one). var generatedApiClientSyntax = apiClientSymbol.DeclaringSyntaxReferences .Select(syntaxReference => syntaxReference.GetSyntax()) .Cast <ClassDeclarationSyntax>() .SingleOrDefault( syntax => syntax.SyntaxTree.GetRoot().GetLeadingTrivia().ToFullString().Contains("// Generated code. DO NOT EDIT!")); if (generatedApiClientSyntax == null) { Console.WriteLine($"Could not find an auto-generated file containing the {apiClientName} definition"); return(3); } var syntaxTree = generatedApiClientSyntax.SyntaxTree; var semanticModel = compilation.GetSemanticModel(syntaxTree); var generator = SyntaxGenerator.GetGenerator(project.GetDocument(syntaxTree)); var requestMethodRewriter = new RequestMethodRewriter(semanticModel); var nonRequestMethodRewriter = new ClientMethodRewriter(semanticModel); var requestMethodToImplRewriter = new RequestMethodToImplRewriter(); var convertToAsyncCancellationTokenOverload = new ConvertToAsyncCancellationTokenOverloadRewriter(); var userClientSyntax = (ClassDeclarationSyntax)generator.ClassDeclaration( userClientName, accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Partial) .WithLeadingTrivia(generatedApiClientSyntax.GetLeadingTrivia()); var userClientImplSyntax = (ClassDeclarationSyntax)generator.ClassDeclaration( userClientName + "Impl", accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed | DeclarationModifiers.Partial, baseType: ParseTypeName(userClientName)) .WithLeadingTrivia(generatedApiClientSyntax.GetLeadingTrivia()); // Copy the request methods from the API client with the user client. We only require these to be copied since // we already have handwritten flattening overloads to change ByteString to BigtableByteString. foreach (var methodSyntax in generatedApiClientSyntax.Members.OfType <MethodDeclarationSyntax>()) { var method = semanticModel.GetDeclaredSymbol(methodSyntax); if (method.DeclaredAccessibility != Accessibility.Public || method.Parameters.IsEmpty) { continue; } if (method.Parameters.Length == 2 && method.Parameters[0].Type.Name.EndsWith("Request")) { var clientMethod = (MethodDeclarationSyntax)requestMethodRewriter.Visit(methodSyntax); userClientSyntax = userClientSyntax.AddMembers(clientMethod); if (method.Parameters[1].Type.Name.EndsWith(nameof(CallSettings))) { var clientImplMethod = (MethodDeclarationSyntax)requestMethodToImplRewriter.Visit(clientMethod); if (s_customStreamMethods.TryGetValue(method.Name, out var customStreamMethodInfo) && customStreamMethodInfo.SplitSyncAndAsync) { var asyncMethod = clientMethod.ToAsync(); userClientSyntax = userClientSyntax.AddMembers(asyncMethod); var asyncMethodWithCancellationToken = (MethodDeclarationSyntax)convertToAsyncCancellationTokenOverload.Visit(asyncMethod); userClientSyntax = userClientSyntax.AddMembers(asyncMethodWithCancellationToken); var clientImplSyncMethod = clientImplMethod.WithBodySafe( Task().Member(nameof(System.Threading.Tasks.Task.Run)) .Invoke(Lambda(asyncMethod.Invoke(clientImplMethod.ParameterList.AsArguments()))) .Member(nameof(gax::TaskExtensions.ResultWithUnwrappedExceptions)).Invoke()); userClientImplSyntax = userClientImplSyntax.AddMembers(clientImplSyncMethod); var clientImplAsyncMethod = clientImplMethod.ToAsync(); userClientImplSyntax = userClientImplSyntax.AddMembers(clientImplAsyncMethod); } else { userClientImplSyntax = userClientImplSyntax.AddMembers(clientImplMethod); } } } else if ( method.Name != "Create" && method.Name != "CreateAsync" && !s_customStreamMethods.ContainsKey(method.Name) && !method.Parameters.Any(p => p.Type.Name == "ByteString")) { // TODO: We could also have this remap to BigtableByteString automatically, but we currently // have some validations for most methods with ByteStrings which I think we's lose by // autogenerating at the moment. // For any other methods which aren't custom streaming methods and which don't use ByteString, // which we remap to BigtableByteString, copy them (with some small fix ups) into the generated // client. userClientSyntax = userClientSyntax.AddMembers( (MethodDeclarationSyntax)nonRequestMethodRewriter.Visit(methodSyntax)); } } // Create a CompilationUnitSyntax from the Usings node of the original file, which will also contain the // copyright notice and generated code warnings in its leading trivia. // We also need a using directive for GAX, so that we can use ResultWithUnwrappedExceptions. var usings = syntaxTree.GetCompilationUnitRoot().Usings .Add(UsingDirective(ParseName(typeof(gax::TaskExtensions).Namespace))); var compilationUnit = CompilationUnit().WithUsings(usings); // Add in the namespace with the ...Client and ...ClientImpl classes. compilationUnit = compilationUnit.AddMembers( (NamespaceDeclarationSyntax)generator.NamespaceDeclaration( apiClientSymbol.ContainingNamespace.ToDisplayString(), userClientSyntax, userClientImplSyntax)); // Use idiomatic formatting for the project. compilationUnit = (CompilationUnitSyntax)Formatter.Format( compilationUnit, workspace, workspace.Options.WithChangedOption(FormattingOptions.NewLine, LanguageNames.CSharp, "\n")); var resultText = compilationUnit.ToFullString(); try { var resultPath = Path.Combine(Path.GetDirectoryName(projectFile), $"{userClientName}.cs"); File.WriteAllText(resultPath, resultText); } catch (Exception e) { Console.WriteLine($"Could not write the auto-generated {userClientName}:\n{e}"); return(4); } return(0); }
public ForeignRelationshipMapping(PropertyInfo property, PropertyInfo id, Formatter<PropertyInfo> keyFormatter) : base(property, keyFormatter.Format(property)) { this.id = id; }
public void FormatSpansIndividuallyWithoutCollapsing() { var code = @"class C { public void M() { [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] if(true){} [|if(true){}|] } }"; var expected = @"class C { public void M() { if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if(true){} if (true) { } } }"; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code)) { var subjectDocument = workspace.Documents.Single(); var spans = subjectDocument.SelectedSpans; var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var syntaxRoot = document.GetSyntaxRootAsync().Result; var node = Formatter.Format(syntaxRoot, spans, workspace); Assert.Equal(expected, node.ToFullString()); } }
public void It_Should_Throw_Format_Gap_Exception() { var formatter = new Formatter<DummyObject>() .With(y => y.SomeInt, 0, 4, y => y.ToString()) .With(y => y.SomeString, 5, 3, y => y.ToString()); try { IEnumerable<DummyObject> items = new List<DummyObject>(); formatter.Format(items); Assert.Fail("Should throw MissingFormatSpecificationException"); } catch (FormatGapException) { } }
public void FormatSpansWithCollapsing() { var code = @"class C { public void M() { [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] [|if(true){}|] while(true){} [|if(true){}|] } }"; var expected = @"class C { public void M() { if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } if (true) { } while (true) { } if (true) { } } }"; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(code)) { var subjectDocument = workspace.Documents.Single(); var spans = subjectDocument.SelectedSpans; workspace.Options = workspace.Options.WithChangedOption(FormattingOptions.AllowDisjointSpanMerging, true); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var syntaxRoot = document.GetSyntaxRootAsync().Result; var node = Formatter.Format(syntaxRoot, spans, workspace); Assert.Equal(expected, node.ToFullString()); } }
public void And_Prefix_Is_Used_It_Should_Be_Applied_At_Start_Of_Row() { var prefix = "ThisIsAPrefix"; var formatter = new Formatter<DummyObject>() .With(y => y.SomeInt, 1, 5, y => y.ToString("00000")) .With(y => y.SomeString, 2, 6, y => y.ToString().PadLeft(6, '_')) .WithLinePrefix(prefix) .WithDelimiter(";"); var result = formatter.Format(_objectsToFormat); foreach (var item in result) { Assert.IsTrue(item.StartsWith(prefix + ";")); } }
public void Format_should_format_correctly() { var sut = new Formatter(); Assert.AreEqual(TestGameString, sut.Format(_testGame)); }
public void Then_The_Static_Field_Should_Be_Printed() { var formatter = new Formatter<DummyObject>() .With("Hello", 0) .With(y => y.SomeInt, 1, 5, y => y.ToString("00000")) .With("World!", 2) .WithDelimiter(";"); var result = formatter.Format(_objectsToFormat); for (int i = 0; i < _objectsToFormat.Count; i++) { var expected = "Hello;" + _objectsToFormat[i].SomeInt.ToString("00000") + ";World!"; Assert.AreEqual(expected, result.ElementAt(i)); } }
public void HandleNestedIncludeWithParentDirs() { var formatter = new Formatter("<sharp:include file='SharpTags/withparent.htm'/>").Parse(); Assert.That(formatter.Format(new TagModel(new Hashtable())), Is.EqualTo("parent aa")); }
public string Format(string raw) { var formatter = new Formatter(); return formatter.Format(raw, false, FormattingContext.Unknown, null); }
public override string ToString() { return(Formatter.Format(this)); }
public void Format(char value, string expectedResult) { Assert.AreEqual(expectedResult, Formatter.Format(value)); }
private SDTokenList ParseContentTokens(XElement xmlElement, bool multilang) { var content = new SDTokenList(); foreach (var element in xmlElement.Nodes()) { var textElement = element as XText; if (textElement != null) { var newLines = new[] { "\r\n", "\n" }; var text = element.ToString(); while (true) { foreach (var newLine in newLines) { if (text.StartsWith(newLine)) { text = text.Substring(newLine.Length); } if (text.EndsWith(newLine)) { text = text.Substring(0, text.Length - newLine.Length); } } text = text.Trim(); var shouldBreak = true; foreach (var newLine in newLines) { if (text.StartsWith(newLine) || text.EndsWith(newLine)) { shouldBreak = false; break; } } if (shouldBreak) { // Replace single newline occurrences by a space (this is just a newline in the docs, not a new paragraph) foreach (var newLine in newLines) { text = text.Replace(newLine, " "); } // Remove duplicate spaces that were used for indentation while (text.Contains(" ")) { text = text.Replace(" ", " "); } break; } } content.Add(new SDToken { Role = SDTokenRole.Text, Text = text }); } var nodeElement = element as XElement; if (nodeElement != null) { switch (nodeElement.Name.LocalName.ToLower()) { case "see": var seeToken = new SDSeeToken(nodeElement.ToString()); _seeTokens.Add(seeToken); content.Add(seeToken); break; case "typeparamref": content.Add(new SDToken { Role = SDTokenRole.TypeParamRef, Text = nodeElement.Attribute("name")?.Value }); break; case "paramref": content.Add(new SDToken { Role = SDTokenRole.ParamRef, Text = nodeElement.Attribute("name")?.Value }); break; case "code": var workspace = MSBuildWorkspace.Create(); var formattedResult = Formatter.Format(CSharpSyntaxTree.ParseText(nodeElement.Value, CSharpParseOptions.Default).GetRoot(), workspace); content.Add(new SDCodeToken { Text = formattedResult.ToString(), IsInline = false }); break; case "c": content.Add(new SDCodeToken { Text = nodeElement.Value, IsInline = true }); break; case "para": content.Add(new SDToken { Text = nodeElement.Value, Role = SDTokenRole.Paragraph }); break; } } } return(content); }
protected static void CheckCanBeAssigned(GroboIL il, Type to, Type from) { if (!CanBeAssigned(to, from, il.VerificationKind)) { ThrowError(il, string.Format("Unable to set a value of type '{0}' to an instance of type '{1}'", Formatter.Format(from), Formatter.Format(to))); } }
public void TestParseNestedLiteralHandling() { var model = new Hashtable(); var reflection = new TagModel(model); var page = "[\"'Index'\"]"; var expected = "[\"'Index'\"]"; var tag = new Formatter(page).Parse(); Assert.That(tag.Format(reflection), Is.EqualTo(expected)); }