public override string Interpret(ref Formatter.ParseUnit pu) { // go statements reset a bunch of stuff pu.clauseStack.Clear(); pu.indentDepth = 0; return this.GetNewLine(pu) + pu.token.Value.Text.ToUpper() + this.GetNewLine(pu); }
public override string Interpret(ref Formatter.ParseUnit pu) { Token t; try { t = pu.clauseStack.Peek(); if (!this.isUnion(pu) && (t.Type == "TOKEN_SELECT" || t.Type == "TOKEN_UPDATE" || t.Type == "TOKEN_DELETE" || t.Type == "TOKEN_INSERT" || t.Type == "TOKEN_DECLARE")) { pu.clauseStack.Clear(); pu.indentDepth = 0; } } catch (Exception) { } bool shouldIncreaseIndent = this.shouldIncreaseIndent(pu); pu.clauseStack.Push(pu.token.Value); if (shouldIncreaseIndent && !this.isUnion(pu)) { pu.indentDepth = pu.indentDepth + 1; } return this.FormatOwnLine(pu); }
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 override string Interpret(ref Formatter.ParseUnit pu) { if (pu.token.Value.Type == "(") { Token t; bool isCreate = false; try { t = pu.clauseStack.Peek(); if (t.Type == "TOKEN_CREATE") { pu.indentDepth = 1; isCreate = true; } } catch (Exception) { } pu.clauseStack.Push(pu.token.Value); if (isCreate) { return pu.token.Value.Text + this.GetNewLine(pu); } } else { Token t = pu.clauseStack.Peek(); if (t.Type == "TOKEN_SELECT" && pu.clauseStack.Count > 1) { pu.clauseStack.Pop(); // Take a select off the stack if (pu.clauseStack.Peek().Type == "(") { pu.clauseStack.Pop(); // Remove the wrapping parentheis pu.indentDepth = pu.indentDepth - 1; return this.GetNewLine(pu) + pu.token.Value.Text + " "; } } else if (t.Type == "(" && pu.clauseStack.Count > 1) { pu.clauseStack.Pop(); if (pu.clauseStack.Peek().Type == "TOKEN_CREATE") { pu.clauseStack.Pop(); pu.indentDepth = pu.indentDepth - 1; return this.GetNewLine(pu) + pu.token.Value.Text + " "; } } else { pu.clauseStack.Pop(); } } if (pu.token.Value.Type == ")") { return pu.token.Value.Text + " "; } return pu.token.Value.Text; }
public override string Interpret(ref Formatter.ParseUnit pu) { Token t = null; Token t2 = null; try { t = pu.clauseStack.Peek(); if (t.Type == "(") { pu.clauseStack.Pop(); try { t2 = pu.clauseStack.Peek(); } finally { pu.clauseStack.Push(t); } } } catch (Exception) { return ", "; } if (t2 != null && t2.Type == "TOKEN_CREATE") { return "," + this.GetNewLine(pu); } if (t.Type == "TOKEN_SELECT" || t.Type == "TOKEN_DECLARE") { return "," + this.GetNewLine(pu); } return ", "; }
static void Main(string[] args) { var textfileadapter = new TextfileAdapter(); var formatter = new Formatter(); var config = new FlowRuntimeConfiguration() .AddStreamsFrom("TelegramProblem.run.flow", Assembly.GetExecutingAssembly()) .AddAction<string>("read", textfileadapter.Read).MakeAsync() .AddAction<string>("write", textfileadapter.Write, true) .AddAction<string, string>("decompose", formatter.Decompose) .AddAction<string, string>("concatenate", formatter.Concatenate) .AddAction<Tuple<string, string>>("textfileadapter_config", textfileadapter.Config) .AddAction<int>("formatter_config", formatter.Config); using(var fr = new FlowRuntime(config)) { fr.UnhandledException += Console.WriteLine; fr.Process(".configFilenames", new Tuple<string,string>("source.txt", "target.txt")); fr.Process(".configLineWidth", 60); fr.Process(".run"); fr.WaitForResult(); Console.WriteLine(File.ReadAllText("target.txt")); } }
public TcpConnection(string address, int port, Formatter formatter) { if (port < 0) throw new ArgumentException(); _address = address; _port = port; _formatter = formatter; }
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 override string Interpret(ref Formatter.ParseUnit pu) { pu.clauseStack.Clear(); pu.indentDepth = 0; pu.clauseStack.Push(pu.token.Value); return this.FormatOwnLine(pu); }
public void Formatter_Format_ShouldReturnExpectedValues() { var timeSpan = TimeSpan.Parse((string)TestContext.DataRow["timeSpan"]); var formattedValue = (string)TestContext.DataRow["formattedValue"]; var actual = new Formatter().Format(timeSpan); Assert.AreEqual(formattedValue, actual, "input: " + timeSpan); }
public override string Interpret(ref Formatter.ParseUnit pu) { pu.clauseStack.Push(pu.token.Value); string returnString = this.GetNewLine(pu) + pu.token.Value.Text.ToUpper(); pu.indentDepth = pu.indentDepth + 1; return returnString; }
/// <summary> /// Initializes a new instance of the <see cref="Stats"/> class. /// </summary> /// <param name="expectedIterations">The number of expected iterations.</param> /// <param name="formatter">The value formatter.</param> /// <param name="averageFormatter">The average value formatter.</param> public Stats(int expectedIterations, Formatter formatter, Formatter averageFormatter) { ExpectedIterations = expectedIterations; TotalIterations = 0; Total = 0; Min = double.MaxValue; Max = double.MinValue; Format = formatter; FormatAverage = averageFormatter; }
public override string Interpret(ref Formatter.ParseUnit pu) { Token t = pu.clauseStack.Peek(); if (t.Type == "TOKEN_BEGIN" || t.Type == "TOKEN_CASE") { pu.clauseStack.Pop(); pu.indentDepth -= 1; } return this.GetNewLine(pu) + pu.token.Value.Text.ToUpper() + this.GetNewLine(pu); }
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)); }
public override void Build(DomainMapper masterMap, Formatter<PropertyInfo> formatter) { base.Build(masterMap, formatter); var mappedType = masterMap.For(Property.PropertyType.GetGenericArguments()[0]); if(!mappedType.SubMappings.Any()) throw new Exception(string.Format("No mappings found type {0}", Property.PropertyType.GetGenericArguments()[0])); var foreignKey = mappedType.SubMappings.OfType<IdMapping>().First().Property; this.foreignRelationshipMapping = new ReverseForeignRelationshipMapping(Property, type, parentType, foreignKey, formatter); masterMap.For(type).Map(mapping => mapping.MapForeignRelationship(masterMap, Property, type, formatter)); }
/// <summary> /// Format a data type into a string in a localisation namespace /// </summary> /// <param name="dataType">The data type to format</param> /// <param name="elementName">The name of the element</param> public static void SerialiseDataType(IGraphable dataType, XmlWriter xmlWriter, string elementName, string localNamespace) { if (dataType != null) { xmlWriter.WriteStartElement(elementName, localNamespace); Formatter fmtr = new Formatter(); fmtr.GraphAides.Add(typeof(MARC.Everest.Formatters.XML.Datatypes.R1.Formatter)); fmtr.GraphObject(xmlWriter, dataType); xmlWriter.WriteEndElement(); } }
public override string Interpret(ref Formatter.ParseUnit pu) { if (this.IsJoin(pu)) { return this.GetNewLine(pu) + this.GetNewLine(pu) + pu.token.Value.Text.ToUpper(); } else { return pu.token.Value.Text.ToUpper(); } }
public string FormatWithPhase1And2(Formatter formatter) { var content = this.GetContent(); if (content == null) { this.formatPhase1Cache = string.Empty; this.formatPhase3Cache = string.Empty; this.links = new string[0]; } return this.formatPhase1Cache ?? (this.formatPhase1Cache = FormattingPipeline.FormatWithPhase1And2(formatter, content.Content, false, FormattingContext.PageContent, this.page, out this.links)); }
public Provider(ApiSchema schema, string address, int port, string phone, ITelegramPersist persist) { _address = address; _port = port; _phone = phone; _persist = persist; _formatter = new Formatter(); Combinator.Setup(schema, _formatter); _settings = LoadSettings(); _connection = new TcpConnection(_address, _port, _formatter); }
public override string Interpret(ref Formatter.ParseUnit pu) { if (this.IsToken(pu.token.Value)) { Console.WriteLine(pu.token.Value.Type); return this.GetNewLine(pu) + pu.token.Value.Text.ToUpper(); } if (this.shouldCapitalize(pu.token.Value.Type)) { return pu.token.Value.Text.ToUpper(); } return pu.token.Value.Text; }
public string GetColumnText(Formatter formatter) { string columnText = _column.GetColumnText(formatter); string aliasText = formatter.GetResultText(_result); string sql = columnText; if (columnText != aliasText) { sql += " " + aliasText; } return sql; }
public override string Interpret(ref Formatter.ParseUnit pu) { // TODO this needs to be changed so that if there is already white space around the token, we don't add more. if (pu.token.Previous != null && Operator.operators.Contains(pu.token.Previous.Value.Type)) { return pu.token.Value.Text + " "; } else if (pu.token.Next != null && Operator.operators.Contains(pu.token.Next.Value.Type)) { return " " + pu.token.Value.Text; } return " " + pu.token.Value.Text + " "; }
protected override void RunCore() { this.Log.Info("{2} catégorie {0} aux pages liées par la page {1}", this.category, this.FullName, this.remove ? "Suppression" : "Ajout"); var formatter = new Formatter(); foreach (var page in this.Pages) { this.Log.Info("Chargement page {0}", page.FullName); var content = page.GetContent(); var formatted = page.FormatWithPhase1And2(formatter); this.Log.Info("Examen {0} liens", page.Links.Length); foreach (var link in page.Links) { var linkedPage = this.FindPage(link); if (linkedPage == null) continue; var categories = linkedPage.Categories; if (!this.remove) { if (!categories.Any(p => p.FullName == this.category)) { this.Log.Info("Ajout catégorie {0} à la page {1}", this.category, linkedPage.FullName); var newList = categories.Select(c => c.FullName).Union(new[] { this.category }).ToArray(); linkedPage.ProviderRebindPage(newList); } } else { if (categories.Any(p => p.FullName == this.category)) { this.Log.Info("Suppression catégorie {0} à la page {1}", this.category, linkedPage.FullName); var newList = categories.Where(c => c.FullName != this.category).Select(c => c.FullName).ToArray(); linkedPage.ProviderRebindPage(newList); } } } } }
public override string Interpret(ref Formatter.ParseUnit pu) { // Check to see if this join is on it's own. try { LinkedListNode<Token> t = pu.token; for(int i = 0; i < 3; i = i + 1) { t = t.Previous; if (t.Value.Type == "TOKEN_ORDER" || t.Value.Type == "TOKEN_GROUP") { return pu.token.Value.Text.ToUpper() + this.GetNewLine(pu); } } } catch (Exception) { } return pu.token.Value.Text.ToUpper(); }
protected bool isUnion(Formatter.ParseUnit pu) { LinkedListNode<Token> currentNode = pu.token; for (int i = 0; i < 3; i = i + 1) { currentNode = currentNode.Previous; if (currentNode == null) { return false; } if (currentNode.Value.Type == "TOKEN_UNION") { return true; } } return false; }
public void DeserializeGeneric_BinaryFormatted_Deserialized() { // ReSharper disable once AssignNullToNotNullAttribute var serializationInfo = new SerializedValue(typeof(TestData).AssemblyQualifiedName, new byte[0]); var subject = new Formatter( _binarySerializerMock.Object, _unityJsonSerializerMock.Object, _formatSelectorMock.Object); var testData = new TestData(); _binarySerializerMock.Setup(mock => mock.Deserialize(It.IsAny<byte[]>())) .Returns(testData); var result = subject.Deserialize<TestData>(serializationInfo); Assert.AreEqual(testData, result); }
public override string Interpret(ref Formatter.ParseUnit pu) { Regex r = White.wsCheck; if (r.IsMatch(pu.sqlBits.Last.Value)) { return ""; } if (pu.token.Next != null && this.needsManual(pu.token.Next.Value)) { return ""; } if (pu.token.Previous != null && this.needsManual(pu.token.Previous.Value)) { return ""; } return " "; }
public static string Interpolate(this string value, object args, Formatter formatter = Formatter.Henri) { switch (formatter) { case Formatter.Haack: return HaackFormatter.HaackFormat(value, args); case Formatter.Hanselman: return HanselmanFormatter.HanselFormat(args, value); case Formatter.Henri: return HenriFormatter.HenriFormat(value, args); case Formatter.James: return JamesFormatter.JamesFormat(value, args); case Formatter.Oskar: return OskarFormatter.OskarFormat(value, args); default: var message = String.Format("Unknown value {0}", formatter); throw new ArgumentOutOfRangeException("formatter", formatter, message); } }
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); } }
// IGenerator public void OutputDataOp(int offset) { Formatter formatter = SourceFormatter; byte[] data = Project.FileData; Anattrib attr = Project.GetAnattrib(offset); string labelStr = string.Empty; if (attr.Symbol != null) { labelStr = mLocalizer.ConvLabel(attr.Symbol.Label); } string commentStr = SourceFormatter.FormatEolComment(Project.Comments[offset]); string opcodeStr, operandStr; FormatDescriptor dfd = attr.DataDescriptor; Debug.Assert(dfd != null); int length = dfd.Length; Debug.Assert(length > 0); bool multiLine = false; switch (dfd.FormatType) { case FormatDescriptor.Type.Default: if (length != 1) { Debug.Assert(false); length = 1; } opcodeStr = sDataOpNames.DefineData1; int operand = RawData.GetWord(data, offset, length, false); operandStr = formatter.FormatHexValue(operand, length * 2); break; case FormatDescriptor.Type.NumericLE: opcodeStr = sDataOpNames.GetDefineData(length); operand = RawData.GetWord(data, offset, length, false); operandStr = PseudoOp.FormatNumericOperand(formatter, Project.SymbolTable, mLocalizer.LabelMap, dfd, operand, length, PseudoOp.FormatNumericOpFlags.None); break; case FormatDescriptor.Type.NumericBE: opcodeStr = sDataOpNames.GetDefineBigData(length); if ((string.IsNullOrEmpty(opcodeStr))) { // Nothing defined, output as comma-separated single-byte values. GenerateShortSequence(offset, length, out opcodeStr, out operandStr); } else { operand = RawData.GetWord(data, offset, length, true); operandStr = PseudoOp.FormatNumericOperand(formatter, Project.SymbolTable, mLocalizer.LabelMap, dfd, operand, length, PseudoOp.FormatNumericOpFlags.None); } break; case FormatDescriptor.Type.Fill: opcodeStr = sDataOpNames.Fill; operandStr = length + "," + formatter.FormatHexValue(data[offset], 2); break; case FormatDescriptor.Type.Dense: multiLine = true; opcodeStr = operandStr = null; OutputDenseHex(offset, length, labelStr, commentStr); break; case FormatDescriptor.Type.Junk: int fillVal = Helper.CheckRangeHoldsSingleValue(data, offset, length); if (fillVal >= 0) { opcodeStr = sDataOpNames.Fill; if (dfd.FormatSubType == FormatDescriptor.SubType.Align256 && GenCommon.CheckJunkAlign(offset, dfd, Project.AddrMap)) { // special syntax for page alignment operandStr = "\\," + formatter.FormatHexValue(fillVal, 2); } else { operandStr = length + "," + formatter.FormatHexValue(fillVal, 2); } } else { // treat same as Dense multiLine = true; opcodeStr = operandStr = null; OutputDenseHex(offset, length, labelStr, commentStr); } break; case FormatDescriptor.Type.StringGeneric: case FormatDescriptor.Type.StringReverse: case FormatDescriptor.Type.StringNullTerm: case FormatDescriptor.Type.StringL8: case FormatDescriptor.Type.StringL16: case FormatDescriptor.Type.StringDci: multiLine = true; opcodeStr = operandStr = null; OutputString(offset, labelStr, commentStr); break; default: opcodeStr = "???"; operandStr = "***"; break; } if (!multiLine) { opcodeStr = formatter.FormatPseudoOp(opcodeStr); OutputLine(labelStr, opcodeStr, operandStr, commentStr); } }
public override void replay(Formatter formatter) { throw new NotImplementedException(); }
private SyntaxNode FormatNode(SyntaxNode node, CancellationToken cancellationToken) => Formatter.Format(node, _document.Project.Solution.Workspace.Services, _options, cancellationToken);
public async Task SimpleAsync(CommandContext ctx, [RemainingText, Description("String to analyze.")] string text) { if (string.IsNullOrEmpty(text)) { throw new ArgumentNullException(nameof(text), "You need to supply a non-null string."); } var cps = text.ToCodepoints().Select(xcp => string.Concat("`U+", xcp.Codepoint, "` (", xcp.Name, (xcp.UnihanData.IsUnihan ? string.Concat(" / ", xcp.UnihanData.Definition) : ""), ") - ", Formatter.Sanitize(xcp.CodepointString), " - <http://www.fileformat.info/info/unicode/char/", xcp.Codepoint, ">")); var pgs = new List <Page>(); var pn = 1; var sb = new StringBuilder(); foreach (var xcp in cps) { if (sb.Length + xcp.Length > 1000) { sb.Append("\nPage: ").Append(pn++.ToString("#,##0")).Append(" of "); pgs.Add(new Page { Content = sb.ToString() }); sb = new StringBuilder(); } sb.Append(xcp).Append("\n"); } sb.Append("\nPage: ").Append(pn++).Append(" of "); pgs.Add(new Page { Content = sb.ToString() }); foreach (var xpg in pgs) { xpg.Content = string.Concat(xpg.Content, pgs.Count.ToString("#,##0")); } if (pgs.Count == 1) { var cnt = pgs.First().Content; cnt = cnt.Substring(0, cnt.LastIndexOf("\n\n")); await ctx.RespondAsync(cnt).ConfigureAwait(false); } else { var interact = ctx.Client.GetInteractivity(); await interact.SendPaginatedMessage(ctx.Channel, ctx.User, pgs).ConfigureAwait(false); } }
public async Task TestDoNotAddDuplicateImportIfNamespaceIsDefinedInSourceAndExternalAssembly(bool safe, bool useSymbolAnnotations) { var externalCode = @"namespace N.M { public class A : System.Attribute { } }"; var code = @"using System; using N.M; class C { public void M1(String p1) { } public void M2([A] String p2) { } }"; var otherAssemblyReference = GetInMemoryAssemblyReferenceForCode(externalCode); var ws = new AdhocWorkspace(); var emptyProject = ws.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Default, "test", "test.dll", LanguageNames.CSharp, metadataReferences: new[] { TestReferences.NetFx.v4_0_30319.mscorlib })); var project = emptyProject .AddMetadataReferences(new[] { otherAssemblyReference }) .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); project = project.AddDocument("duplicate.cs", externalCode).Project; var document = project.AddDocument("test.cs", code); var options = document.Project.Solution.Workspace.Options; var compilation = await document.Project.GetCompilationAsync(CancellationToken.None); var compilerDiagnostics = compilation.GetDiagnostics(CancellationToken.None); Assert.Empty(compilerDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error)); var attribute = compilation.GetTypeByMetadataName("N.M.A"); var syntaxRoot = await document.GetSyntaxRootAsync(CancellationToken.None).ConfigureAwait(false); SyntaxNode p1SyntaxNode = syntaxRoot.DescendantNodes().OfType <ParameterSyntax>().FirstOrDefault(); // Add N.M.A attribute to p1. var editor = await DocumentEditor.CreateAsync(document, CancellationToken.None).ConfigureAwait(false); var attributeSyntax = editor.Generator.Attribute(editor.Generator.TypeExpression(attribute)); editor.AddAttribute(p1SyntaxNode, attributeSyntax); var documentWithAttribute = editor.GetChangedDocument(); // Add namespace import. var imported = useSymbolAnnotations ? await ImportAdder.AddImportsFromSymbolAnnotationAsync(documentWithAttribute, safe, null, CancellationToken.None).ConfigureAwait(false) : await ImportAdder.AddImportsFromSyntaxesAsync(documentWithAttribute, safe, null, CancellationToken.None).ConfigureAwait(false); var formatted = await Formatter.FormatAsync(imported, options); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(@"using System; using N.M; class C { public void M1([global::N.M.A] String p1) { } public void M2([A] String p2) { } }", actualText); }
/// <summary> /// Formats the text with markup as specified in Oxide.Core.Libraries.Covalence.Formatter /// into the game-specific markup language /// </summary> /// <param name="text">text to format</param> /// <returns>formatted text</returns> public string FormatText(string text) => Formatter.ToUnity(text);
private void btnSaveCategory_Click(object sender, System.EventArgs e) { CategoryInfo category = SubsiteCatalogHelper.GetCategory(this.categoryId); if (category == null) { this.ShowMsg("编缉商品分类错误,未知", false); return; } //if (this.fileUpload.HasFile) //{ // try // { // ResourcesHelper.DeleteImage(category.Icon); // category.Icon = SubsiteCatalogHelper.UploadCategoryIcon(this.fileUpload.PostedFile); // } // catch // { // this.ShowMsg("图片上传失败,您选择的不是图片类型的文件,或者网站的虚拟目录没有写入文件的权限", false); // return; // } //} category.AssociatedProductType = this.dropProductTypes.SelectedValue; category.Name = this.txtCategoryName.Text; category.RewriteName = this.txtRewriteName.Text; category.MetaTitle = this.txtPageKeyTitle.Text; category.MetaKeywords = this.txtPageKeyWords.Text; category.MetaDescription = this.txtPageDesc.Text; category.Notes1 = this.fckNotes1.Text; category.Notes2 = this.fckNotes2.Text; category.Notes3 = this.fckNotes3.Text; if (category.Depth > 1) { CategoryInfo category2 = SubsiteCatalogHelper.GetCategory(category.ParentCategoryId.Value); if (string.IsNullOrEmpty(category.Notes1)) { category.Notes1 = category2.Notes1; } if (string.IsNullOrEmpty(category.Notes2)) { category.Notes2 = category2.Notes2; } if (string.IsNullOrEmpty(category.Notes3)) { category.Notes3 = category2.Notes3; } if (string.IsNullOrEmpty(category.Notes4)) { category.Notes4 = category2.Notes4; } if (string.IsNullOrEmpty(category.Notes5)) { category.Notes5 = category2.Notes5; } } ValidationResults validationResults = Validation.Validate <CategoryInfo>(category, new string[] { "ValCategory" }); string text = string.Empty; if (!validationResults.IsValid) { foreach (ValidationResult current in (System.Collections.Generic.IEnumerable <ValidationResult>)validationResults) { text += Formatter.FormatErrorMessage(current.Message); } this.ShowMsg(text, false); } else { CategoryActionStatus categoryActionStatus = SubsiteCatalogHelper.UpdateCategory(category); if (categoryActionStatus == CategoryActionStatus.Success) { this.ShowMsg("成功修改了当前商品分类", true); this.BindCategoryInfo(category); return; } if (categoryActionStatus == CategoryActionStatus.UpdateParentError) { this.ShowMsg("不能自己成为自己的上级分类", false); return; } this.ShowMsg("编缉商品分类错误,未知", false); return; } }
/// <summary> /// Returns an updated <paramref name="memberDeclaration"/> with all the new /// local declaration statements annotated with <see cref="s_newLocalDeclarationStatementAnnotation"/> /// moved closer to first reference and all the existing /// local declaration statements annotated with <see cref="s_existingLocalDeclarationWithoutInitializerAnnotation"/> /// whose declared local is no longer used removed. /// </summary> private async Task <SyntaxNode> AdjustLocalDeclarationsAsync( SyntaxNode memberDeclaration, Document document, CancellationToken cancellationToken) { var service = document.GetLanguageService <IMoveDeclarationNearReferenceService>(); var syntaxFacts = document.GetLanguageService <ISyntaxFactsService>(); var originalDocument = document; var originalDeclStatementsToMoveOrRemove = memberDeclaration.DescendantNodes() .Where(n => n.HasAnnotation(s_newLocalDeclarationStatementAnnotation) || n.HasAnnotation(s_existingLocalDeclarationWithoutInitializerAnnotation)) .ToImmutableArray(); if (originalDeclStatementsToMoveOrRemove.IsEmpty) { return(memberDeclaration); } // Moving declarations closer to a reference can lead to conflicting edits. // So, we track all the declaration statements to be moved upfront, and update // the root, document, editor and memberDeclaration for every edit. // Finally, we apply replace the memberDeclaration in the originalEditor as a single edit. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var rootWithTrackedNodes = root.TrackNodes(originalDeclStatementsToMoveOrRemove); // Run formatter prior to invoking IMoveDeclarationNearReferenceService. rootWithTrackedNodes = Formatter.Format(rootWithTrackedNodes, originalDeclStatementsToMoveOrRemove.Select(s => s.Span), document.Project.Solution.Workspace, cancellationToken: cancellationToken); document = document.WithSyntaxRoot(rootWithTrackedNodes); await OnDocumentUpdatedAsync().ConfigureAwait(false); foreach (TLocalDeclarationStatementSyntax originalDeclStatement in originalDeclStatementsToMoveOrRemove) { // Get the current declaration statement. var declStatement = memberDeclaration.GetCurrentNode(originalDeclStatement); var documentUpdated = false; // Check if the variable declaration is unused after all the fixes, and hence can be removed. if (await TryRemoveUnusedLocalAsync(declStatement, originalDeclStatement).ConfigureAwait(false)) { documentUpdated = true; } else if (declStatement.HasAnnotation(s_newLocalDeclarationStatementAnnotation)) { // Otherwise, move the declaration closer to the first reference if possible. if (await service.CanMoveDeclarationNearReferenceAsync(document, declStatement, cancellationToken).ConfigureAwait(false)) { document = await service.MoveDeclarationNearReferenceAsync(document, declStatement, cancellationToken).ConfigureAwait(false); documentUpdated = true; } } if (documentUpdated) { await OnDocumentUpdatedAsync().ConfigureAwait(false); } } return(memberDeclaration); // Local functions. async Task OnDocumentUpdatedAsync() { root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); memberDeclaration = syntaxFacts.GetContainingMemberDeclaration(root, memberDeclaration.SpanStart); } async Task <bool> TryRemoveUnusedLocalAsync(TLocalDeclarationStatementSyntax newDecl, TLocalDeclarationStatementSyntax originalDecl) { // If we introduced this new local declaration statement while computing the code fix, // but all it's existing references were removed as part of FixAll, then we // can remove the unncessary local declaration statement. // Additionally, if this is an existing local declaration without an initializer, // such that the local has no references anymore, we can remove it. if (newDecl.HasAnnotation(s_unusedLocalDeclarationAnnotation) || newDecl.HasAnnotation(s_existingLocalDeclarationWithoutInitializerAnnotation)) { // Check if we have no references to local in fixed code. if (await IsLocalDeclarationWithNoReferencesAsync(newDecl, document, cancellationToken).ConfigureAwait(false)) { document = document.WithSyntaxRoot( root.RemoveNode(newDecl, SyntaxGenerator.DefaultRemoveOptions)); return(true); } } return(false); } }
private IEnumerable <AbstractFormattingRule> GetFormattingRules(Document document) { var indentStyle = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None).GetOption(FormattingOptions.SmartIndent); return(SpecializedCollections.SingletonEnumerable(BraceCompletionFormattingRule.ForIndentStyle(indentStyle)).Concat(Formatter.GetDefaultFormattingRules(document))); }
public async Task 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 = TestWorkspace.CreateCSharp(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 = await document.GetSyntaxRootAsync(); var node = Formatter.Format(syntaxRoot, spans, workspace); Assert.Equal(expected, node.ToFullString()); } }
public async Task 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 = TestWorkspace.CreateCSharp(code)) { var subjectDocument = workspace.Documents.Single(); var spans = subjectDocument.SelectedSpans; var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var syntaxRoot = await document.GetSyntaxRootAsync(); var node = Formatter.Format(syntaxRoot, spans, workspace); Assert.Equal(expected, node.ToFullString()); } }
public virtual void PrintStatistics(string itemsName) { if (!m_verbose) { return; } bool print = false; string col = " "; StringBuilder sb = new StringBuilder(); string newline = Environment.NewLine; sb.Append("------------> ").Append(GetType().GetTypeInfo().Name).Append(" statistics (").Append(printNum).Append("): ").Append(newline); int nut = TotalItemsCount; if (nut > lastPrintedNumUniqueTexts) { print = true; sb.Append("total count of " + itemsName + ": ").Append(Formatter.Format(0, nut, col)).Append(newline); lastPrintedNumUniqueTexts = nut; } long nub = TotalBytesCount; if (nub > lastPrintedNumUniqueBytes) { print = true; sb.Append("total bytes of " + itemsName + ": ").Append(Formatter.Format(0, nub, col)).Append(newline); lastPrintedNumUniqueBytes = nub; } if (ItemsCount > 0) { print = true; sb.Append("num " + itemsName + " added since last inputs reset: ").Append(Formatter.Format(0, ItemsCount, col)).Append(newline); sb.Append("total bytes added for " + itemsName + " since last inputs reset: ").Append(Formatter.Format(0, BytesCount, col)).Append(newline); } if (print) { Console.WriteLine(sb.Append(newline).ToString()); printNum++; } }
internal override async Task <CompletionChange> GetChangeAsync(Document document, CompletionItem completionItem, TextSpan completionListSpan, char?commitKey, CancellationToken cancellationToken) { var containingNamespace = ImportCompletionItem.GetContainingNamespace(completionItem); if (await ShouldCompleteWithFullyQualifyTypeName().ConfigureAwait(false)) { var fullyQualifiedName = $"{containingNamespace}.{completionItem.DisplayText}"; var change = new TextChange(completionListSpan, fullyQualifiedName); return(CompletionChange.Create(change)); } // Find context node so we can use it to decide where to insert using/imports. var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var addImportContextNode = root.FindToken(completionListSpan.Start, findInsideTrivia: true).Parent; // Add required using/imports directive. var addImportService = document.GetRequiredLanguageService <IAddImportsService>(); var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = optionSet.GetOption(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language); var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var importNode = CreateImport(document, containingNamespace); var rootWithImport = addImportService.AddImport(compilation, root, addImportContextNode, importNode, placeSystemNamespaceFirst, cancellationToken); var documentWithImport = document.WithSyntaxRoot(rootWithImport); // This only formats the annotated import we just added, not the entire document. var formattedDocumentWithImport = await Formatter.FormatAsync(documentWithImport, Formatter.Annotation, cancellationToken : cancellationToken).ConfigureAwait(false); var builder = ArrayBuilder <TextChange> .GetInstance(); // Get text change for add import var importChanges = await formattedDocumentWithImport.GetTextChangesAsync(document, cancellationToken).ConfigureAwait(false); builder.AddRange(importChanges); // Create text change for complete type name. // // Note: Don't try to obtain TextChange for completed type name by replacing the text directly, // then use Document.GetTextChangesAsync on document created from the changed text. This is // because it will do a diff and return TextChanges with minimum span instead of actual // replacement span. // // For example: If I'm typing "asd", the completion provider could be triggered after "a" // is typed. Then if I selected type "AsnEncodedData" to commit, by using the approach described // above, we will get a TextChange of "AsnEncodedDat" with 0 length span, instead of a change of // the full display text with a span of length 1. This will later mess up span-tracking and end up // with "AsnEncodedDatasd" in the code. builder.Add(new TextChange(completionListSpan, completionItem.DisplayText)); // Then get the combined change var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.WithChanges(builder); return(CompletionChange.Create(Utilities.Collapse(newText, builder.ToImmutableAndFree()))); async Task <bool> ShouldCompleteWithFullyQualifyTypeName() { if (!IsAddingImportsSupported(document)) { return(true); } // We might need to qualify unimported types to use them in an import directive, because they only affect members of the containing // import container (e.g. namespace/class/etc. declarations). // // For example, `List` and `StringBuilder` both need to be fully qualified below: // // using CollectionOfStringBuilders = System.Collections.Generic.List<System.Text.StringBuilder>; // // However, if we are typing in an C# using directive that is inside a nested import container (i.e. inside a namespace declaration block), // then we can add an using in the outer import container instead (this is not allowed in VB). // // For example: // // using System.Collections.Generic; // using System.Text; // // namespace Foo // { // using CollectionOfStringBuilders = List<StringBuilder>; // } // // Here we will always choose to qualify the unimported type, just to be consistent and keeps things simple. return(await IsInImportsDirectiveAsync(document, completionListSpan.Start, cancellationToken).ConfigureAwait(false)); } }
public string GetStatusBarText(int count) => Format(section => section?.StatusBar, new { count = Formatter.ToFormattedString(count) });
private async Task <Solution> EncapsulateFieldAsync( Document document, IFieldSymbol field, bool updateReferences, CancellationToken cancellationToken) { var originalField = field; var(finalFieldName, generatedPropertyName) = GenerateFieldAndPropertyNames(field); // Annotate the field declarations so we can find it after rename. var fieldDeclaration = field.DeclaringSyntaxReferences.First(); var declarationAnnotation = new SyntaxAnnotation(); document = document.WithSyntaxRoot(fieldDeclaration.SyntaxTree.GetRoot(cancellationToken).ReplaceNode(fieldDeclaration.GetSyntax(cancellationToken), fieldDeclaration.GetSyntax(cancellationToken).WithAdditionalAnnotations(declarationAnnotation))); var solution = document.Project.Solution; foreach (var linkedDocumentId in document.GetLinkedDocumentIds()) { var linkedDocument = solution.GetDocument(linkedDocumentId); var linkedRoot = await linkedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var linkedFieldNode = linkedRoot.FindNode(fieldDeclaration.Span); if (linkedFieldNode.Span != fieldDeclaration.Span) { continue; } var updatedRoot = linkedRoot.ReplaceNode(linkedFieldNode, linkedFieldNode.WithAdditionalAnnotations(declarationAnnotation)); solution = solution.WithDocumentSyntaxRoot(linkedDocumentId, updatedRoot); } document = solution.GetDocument(document.Id); // Resolve the annotated symbol and prepare for rename. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var compilation = semanticModel.Compilation; field = field.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol as IFieldSymbol; // We couldn't resolve field after annotating its declaration. Bail if (field == null) { return(null); } var solutionNeedingProperty = await UpdateReferencesAsync( updateReferences, solution, document, field, finalFieldName, generatedPropertyName, cancellationToken).ConfigureAwait(false); document = solutionNeedingProperty.GetDocument(document.Id); var markFieldPrivate = field.DeclaredAccessibility != Accessibility.Private; var rewrittenFieldDeclaration = await RewriteFieldNameAndAccessibilityAsync(finalFieldName, markFieldPrivate, document, declarationAnnotation, cancellationToken).ConfigureAwait(false); var formattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(document, cancellationToken).ConfigureAwait(false); document = await Formatter.FormatAsync(document.WithSyntaxRoot(rewrittenFieldDeclaration), Formatter.Annotation, formattingOptions, cancellationToken).ConfigureAwait(false); solution = document.Project.Solution; foreach (var linkedDocumentId in document.GetLinkedDocumentIds()) { var linkedDocument = solution.GetDocument(linkedDocumentId); var linkedDocumentFormattingOptions = await SyntaxFormattingOptions.FromDocumentAsync(linkedDocument, cancellationToken).ConfigureAwait(false); var updatedLinkedRoot = await RewriteFieldNameAndAccessibilityAsync(finalFieldName, markFieldPrivate, linkedDocument, declarationAnnotation, cancellationToken).ConfigureAwait(false); var updatedLinkedDocument = await Formatter.FormatAsync(linkedDocument.WithSyntaxRoot(updatedLinkedRoot), Formatter.Annotation, linkedDocumentFormattingOptions, cancellationToken).ConfigureAwait(false); solution = updatedLinkedDocument.Project.Solution; } document = solution.GetDocument(document.Id); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newDeclaration = newRoot.GetAnnotatedNodes <SyntaxNode>(declarationAnnotation).First(); field = semanticModel.GetDeclaredSymbol(newDeclaration, cancellationToken) as IFieldSymbol; var generatedProperty = GenerateProperty( generatedPropertyName, finalFieldName, originalField.DeclaredAccessibility, originalField, field.ContainingType, new SyntaxAnnotation(), document); var solutionWithProperty = await AddPropertyAsync( document, document.Project.Solution, field, generatedProperty, formattingOptions, cancellationToken).ConfigureAwait(false); return(solutionWithProperty); }
private RazorDocumentRangeFormattingResponse Format(RazorDocumentRangeFormattingParams @params) { if (@params.Kind == RazorLanguageKind.Razor) { throw new InvalidOperationException("We shouldn't be asked to format Razor language kind."); } var options = @params.Options; var response = new RazorDocumentRangeFormattingResponse(); if (@params.Kind == RazorLanguageKind.CSharp) { var codeDocument = _documents[@params.HostDocumentFilePath]; var csharpSourceText = codeDocument.GetCSharpSourceText(); var csharpDocument = GetCSharpDocument(codeDocument, @params.Options); if (!csharpDocument.TryGetSyntaxRoot(out var root)) { throw new InvalidOperationException("Couldn't get syntax root."); } var spanToFormat = @params.ProjectedRange.AsTextSpan(csharpSourceText); var changes = Formatter.GetFormattedTextChanges(root, spanToFormat, csharpDocument.Project.Solution.Workspace); response.Edits = changes.Select(c => c.AsTextEdit(csharpSourceText)).ToArray(); } else if (@params.Kind == RazorLanguageKind.Html) { response.Edits = Array.Empty <TextEdit>(); var codeDocument = _documents[@params.HostDocumentFilePath]; var generatedHtml = codeDocument.GetHtmlDocument().GeneratedHtml; generatedHtml = generatedHtml.Replace("\r", "", StringComparison.Ordinal).Replace("\n", "\r\n", StringComparison.Ordinal); // Get formatted baseline file var baselineInputFileName = Path.ChangeExtension(_baselineFileName, ".input.html"); var baselineOutputFileName = Path.ChangeExtension(_baselineFileName, ".output.html"); var baselineInputFile = TestFile.Create(baselineInputFileName, GetType().GetTypeInfo().Assembly); var baselineOutputFile = TestFile.Create(baselineOutputFileName, GetType().GetTypeInfo().Assembly); if (GenerateBaselines) { if (baselineInputFile.Exists()) { // If it already exists, we only want to update if the input is different. var inputContent = baselineInputFile.ReadAllText(); if (string.Equals(inputContent, generatedHtml, StringComparison.Ordinal)) { return(response); } } var baselineInputFilePath = Path.Combine(_projectPath, baselineInputFileName); File.WriteAllText(baselineInputFilePath, generatedHtml); var baselineOutputFilePath = Path.Combine(_projectPath, baselineOutputFileName); File.WriteAllText(baselineOutputFilePath, generatedHtml); return(response); } if (!baselineInputFile.Exists()) { throw new XunitException($"The resource {baselineInputFileName} was not found."); } if (!baselineOutputFile.Exists()) { throw new XunitException($"The resource {baselineOutputFileName} was not found."); } var baselineInputHtml = baselineInputFile.ReadAllText(); if (!string.Equals(baselineInputHtml, generatedHtml, StringComparison.Ordinal)) { throw new XunitException($"The baseline for {_baselineFileName} is out of date."); } var baselineOutputHtml = baselineOutputFile.ReadAllText(); var baselineInputText = SourceText.From(baselineInputHtml); var baselineOutputText = SourceText.From(baselineOutputHtml); var changes = SourceTextDiffer.GetMinimalTextChanges(baselineInputText, baselineOutputText, lineDiffOnly: false); var edits = changes.Select(c => c.AsTextEdit(baselineInputText)).ToArray(); response.Edits = edits; } return(response); }
/// <summary> /// Broadcasts the specified chat message and prefix to all players /// </summary> /// <param name="message"></param> /// <param name="prefix"></param> /// <param name="args"></param> public void Broadcast(string message, string prefix, params object[] args) { if (string.IsNullOrEmpty(message)) { return; } message = args.Length > 0 ? string.Format(Formatter.ToRoKAnd7DTD(message), args) : Formatter.ToRoKAnd7DTD(message); string formatted = prefix != null ? $"{prefix} {message}" : message; Server.BroadcastMessage(formatted); }
/// <inheritdoc/> public override void FormatBold(ToolbarButton button) { Formatter.SetSelection("**", "**"); }
/// <summary> /// Sends the specified message to the player /// </summary> /// <param name="message"></param> public void Message(string message) => Interface.Oxide.LogInfo(Formatter.ToPlaintext(message));
/// <inheritdoc/> public override void FormatItalics(ToolbarButton button) { Formatter.SetSelection("_", "_"); }
private static async Task <int> Main(string[] args) { // 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]; 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 void When_asserting_element_has_child_element_with_ns_but_it_does_not_it_should_fail_with_descriptive_message() { // Arrange var element = XElement.Parse( @"<parent> <child /> </parent>"); // Act Action act = () => element.Should().HaveElement(XName.Get("unknown", "http://www.example.com/2012/test"), "because we want to test the failure message"); // Assert string expectedMessage = string.Format("Expected XML element {0} to have child element \"{{http://www.example.com/2012/test}}unknown\"" + " because we want to test the failure message" + ", but no such child element was found.", Formatter.ToString(element)); act.Should().Throw <XunitException>().WithMessage(expectedMessage); }
/// <inheritdoc/> public override void FormatStrikethrough(ToolbarButton button) { Formatter.SetSelection("~~", "~~"); }
private void OutputString(int offset, string labelStr, string commentStr) { // This gets complicated. // // For Dci, L8String, and L16String, the entire string needs to fit in the // operand of one line. If it can't, we need to separate the length byte/word // or inverted character out, and just dump the rest as ASCII. Computing the // line length requires factoring delimiter character escapes. (NOTE: contrary // to the documentation, STR and STRL do include trailing hex characters in the // length calculation, so it's possible to escape delimiters.) // // For Reverse, we can span lines, but only if we emit the lines in // backward order. Also, Merlin doesn't allow hex to be embedded in a REV // operation, so we can't use REV if the string contains a delimiter. // // For aesthetic purposes, zero-length CString, L8String, and L16String // should be output as DFB/DW zeroes rather than an empty string -- makes // it easier to read. // // NOTE: we generally assume that the input is in the correct format, e.g. // the length byte in a StringL8 matches dfd.Length, and the high bits in DCI strings // have the right pattern. If not, we will generate bad output. This would need // to be scanned and corrected at a higher level. Anattrib attr = Project.GetAnattrib(offset); FormatDescriptor dfd = attr.DataDescriptor; Debug.Assert(dfd != null); Debug.Assert(dfd.IsString); Debug.Assert(dfd.Length > 0); // We can sort of do parts of C64 stuff, but it's probably more readable to just // output a commented blob than something where only the capital letters are readable. switch (dfd.FormatSubType) { case FormatDescriptor.SubType.Ascii: case FormatDescriptor.SubType.HighAscii: break; case FormatDescriptor.SubType.C64Petscii: case FormatDescriptor.SubType.C64Screen: default: OutputNoJoy(offset, dfd.Length, labelStr, commentStr); return; } Formatter formatter = SourceFormatter; byte[] data = Project.FileData; StringOpFormatter.ReverseMode revMode = StringOpFormatter.ReverseMode.Forward; int leadingBytes = 0; string opcodeStr; switch (dfd.FormatType) { case FormatDescriptor.Type.StringGeneric: opcodeStr = sDataOpNames.StrGeneric; break; case FormatDescriptor.Type.StringReverse: opcodeStr = sDataOpNames.StrReverse; revMode = StringOpFormatter.ReverseMode.LineReverse; break; case FormatDescriptor.Type.StringNullTerm: opcodeStr = sDataOpNames.StrGeneric; // no pseudo-op for this if (dfd.Length == 1) { // Empty string. Just output the length byte(s) or null terminator. GenerateShortSequence(offset, 1, out string opcode, out string operand); OutputLine(labelStr, opcode, operand, commentStr); return; } break; case FormatDescriptor.Type.StringL8: opcodeStr = sDataOpNames.StrLen8; leadingBytes = 1; break; case FormatDescriptor.Type.StringL16: opcodeStr = sDataOpNames.StrLen16; leadingBytes = 2; break; case FormatDescriptor.Type.StringDci: opcodeStr = sDataOpNames.StrDci; break; default: Debug.Assert(false); return; } // Merlin 32 uses single-quote for low ASCII, double-quote for high ASCII. CharEncoding.Convert charConv; char delim; if (dfd.FormatSubType == FormatDescriptor.SubType.HighAscii) { charConv = CharEncoding.ConvertHighAscii; delim = '"'; } else { charConv = CharEncoding.ConvertAscii; delim = '\''; } StringOpFormatter stropf = new StringOpFormatter(SourceFormatter, new Formatter.DelimiterDef(delim), StringOpFormatter.RawOutputStyle.DenseHex, MAX_OPERAND_LEN, charConv); if (dfd.FormatType == FormatDescriptor.Type.StringDci) { // DCI is awkward because the character encoding flips on the last byte. Rather // than clutter up StringOpFormatter for this rare item, we just accept low/high // throughout. stropf.CharConv = CharEncoding.ConvertLowAndHighAscii; } // Feed bytes in, skipping over the leading length bytes. stropf.FeedBytes(data, offset + leadingBytes, dfd.Length - leadingBytes, 0, revMode); Debug.Assert(stropf.Lines.Count > 0); // See if we need to do this over. bool redo = false; switch (dfd.FormatType) { case FormatDescriptor.Type.StringGeneric: case FormatDescriptor.Type.StringNullTerm: break; case FormatDescriptor.Type.StringReverse: if (stropf.HasEscapedText) { // can't include escaped characters in REV opcodeStr = sDataOpNames.StrGeneric; revMode = StringOpFormatter.ReverseMode.Forward; redo = true; } break; case FormatDescriptor.Type.StringL8: if (stropf.Lines.Count != 1) { // single-line only opcodeStr = sDataOpNames.StrGeneric; leadingBytes = 1; redo = true; } break; case FormatDescriptor.Type.StringL16: if (stropf.Lines.Count != 1) { // single-line only opcodeStr = sDataOpNames.StrGeneric; leadingBytes = 2; redo = true; } break; case FormatDescriptor.Type.StringDci: if (stropf.Lines.Count != 1) { // single-line only opcodeStr = sDataOpNames.StrGeneric; stropf.CharConv = charConv; redo = true; } break; default: Debug.Assert(false); return; } if (redo) { //Debug.WriteLine("REDO off=+" + offset.ToString("x6") + ": " + dfd.FormatType); // This time, instead of skipping over leading length bytes, we include them // explicitly. stropf.Reset(); stropf.FeedBytes(data, offset, dfd.Length, leadingBytes, revMode); } opcodeStr = formatter.FormatPseudoOp(opcodeStr); foreach (string str in stropf.Lines) { OutputLine(labelStr, opcodeStr, str, commentStr); labelStr = commentStr = string.Empty; // only show on first } }
public void Emit(string fnName, EmitFlags f, Formatter fmt, CodeFormatter w, TypeReferenceFormatter t) { bool emitStorage = (f & EmitFlags.ArgumentKind) == EmitFlags.ArgumentKind; if (ParametersValid) { if (emitStorage) { if (HasVoidReturn) { fmt.Write("void "); } else { w.WriteFormalArgumentType(ReturnValue !, emitStorage); fmt.Write(" "); } fmt.Write("{0}(", fnName); } else { if (HasVoidReturn) { fmt.Write("void {0}", fnName); } else { t.WriteDeclaration(ReturnValue !.DataType, fnName); //$TODO: won't work with fn's that return pointers to functions or arrays. } fmt.Write("("); } var sep = ""; if (Parameters != null) { IEnumerable <Identifier> parms = this.IsInstanceMetod ? Parameters.Skip(1) : Parameters; foreach (var p in parms) { fmt.Write(sep); sep = ", "; w.WriteFormalArgument(p, emitStorage, t); } if (this.IsVariadic) { fmt.Write(sep); if (sep.Length == 0) { fmt.Write(' '); } fmt.Write("..."); } } fmt.Write(")"); } else { fmt.WriteKeyword("define"); fmt.Write(" "); fmt.Write(fnName); } if ((f & EmitFlags.LowLevelInfo) == EmitFlags.LowLevelInfo) { fmt.WriteLine(); fmt.Write("// stackDelta: {0}; fpuStackDelta: {1}; fpuMaxParam: {2}", StackDelta, FpuStackDelta, FpuStackArgumentMax); fmt.WriteLine(); } }
/// <inheritdoc/> public override void FormatList(ToolbarButton button) { Formatter.SetList(() => "- ", button); }
/// <inheritdoc/> public override void FormatOrderedList(ToolbarButton button) { Formatter.SetList(Formatter.OrderedListIterate, button); }
public string GetSearchProgressText(int count) => Format(section => section?.SearchProgress, new { count = Formatter.ToFormattedString(count) });
public string GetNewVersionString(string version, DateTime date) => Format(translation => translation?.NewVersion, new { version, date = Formatter.ToFormattedDateString(date) });
public Task ListAttributes(CommandContext ctx) { return(ctx.RespondAsync(string.Join(" ", ctx.Command.CustomAttributes.Select(x => Formatter.InlineCode(x.GetType().ToString()))))); }