Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix NRT warnings in Word converter #1010

Merged
merged 1 commit into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions tools/MarkdownConverter.Tests/MarkdownSpecFileListTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using MarkdownConverter.Spec;
using MarkdownConverter.Spec;
using Xunit;

namespace MarkdownConverter.Tests;
Expand All @@ -8,6 +8,6 @@ public class MarkdownSpecFileListTests
[Fact]
public void EmptyListTest()
{
Assert.Throws<ArgumentNullException>(() => MarkdownSpec.ReadFiles(null, new Reporter(TextWriter.Null)));
Assert.Throws<ArgumentNullException>(() => MarkdownSpec.ReadFiles(null!, new Reporter(TextWriter.Null)));
}
}
}
113 changes: 52 additions & 61 deletions tools/MarkdownConverter/Converter/MarkdownSourceConverter.cs

Large diffs are not rendered by default.

30 changes: 18 additions & 12 deletions tools/MarkdownConverter/Converter/MarkdownSpecConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ public static void ConvertToWord(MarkdownSpec spec, string templateFile, string
resultDoc.AddPart(part.OpenXmlPart, part.RelationshipId);
}

var body = resultDoc.MainDocumentPart.Document.Body;
var body = resultDoc.MainDocumentPart!.Document.Body!;

ReplaceTableOfContents(spec, body);

var context = new ConversionContext();
context.MaxBookmarkId.Value = 1 + body.Descendants<BookmarkStart>().Max(bookmark => int.Parse(bookmark.Id));
context.MaxBookmarkId.Value = 1 + body.Descendants<BookmarkStart>().Max(bookmark => int.Parse(bookmark.Id!));

foreach (var src in spec.Sources)
{
Expand Down Expand Up @@ -72,9 +72,12 @@ private static void ReplaceTableOfContents(MarkdownSpec spec, Body body)
}
}

private static bool FindToc(Body body, out int ifirst, out int iLast, out string instr, out Paragraph secBreak)
private static bool FindToc(Body body, out int ifirst, out int iLast, out string? instr, out Paragraph? secBreak)
{
ifirst = -1; iLast = -1; instr = null; secBreak = null;
ifirst = -1;
iLast = -1;
instr = null;
secBreak = null;

for (int i = 0; i < body.ChildElements.Count; i++)
{
Expand All @@ -86,23 +89,25 @@ private static bool FindToc(Body body, out int ifirst, out int iLast, out string

// The TOC might be a simple field
var sf = p.OfType<SimpleField>().FirstOrDefault();
if (sf != null && sf.Instruction.Value.Contains("TOC"))
if (sf?.Instruction?.Value?.Contains("TOC") == true)
{
if (ifirst != -1)
{
throw new Exception("Found start of TOC and then another simple TOC");
}

ifirst = i; iLast = i; instr = sf.Instruction.Value;
ifirst = i;
iLast = i;
instr = sf.Instruction.Value;
break;
}

// or it might be a complex field
var runElements = (from r in p.OfType<Run>() from e in r select e).ToList();
var f1 = runElements.FindIndex(f => f is FieldChar && (f as FieldChar).FieldCharType.Value == FieldCharValues.Begin);
var f2 = runElements.FindIndex(f => f is FieldCode && (f as FieldCode).Text.Contains("TOC"));
var f3 = runElements.FindIndex(f => f is FieldChar && (f as FieldChar).FieldCharType.Value == FieldCharValues.Separate);
var f4 = runElements.FindIndex(f => f is FieldChar && (f as FieldChar).FieldCharType.Value == FieldCharValues.End);
var f1 = runElements.FindIndex(f => f is FieldChar fc && fc.FieldCharType?.Value == FieldCharValues.Begin);
var f2 = runElements.FindIndex(f => f is FieldCode fc && fc.Text.Contains("TOC"));
var f3 = runElements.FindIndex(f => f is FieldChar fc && fc.FieldCharType?.Value == FieldCharValues.Separate);
var f4 = runElements.FindIndex(f => f is FieldChar fc && fc.FieldCharType?.Value == FieldCharValues.End);

if (f1 != -1 && f2 != -1 && f3 != -1 && f2 > f1 && f3 > f2)
{
Expand All @@ -111,7 +116,8 @@ private static bool FindToc(Body body, out int ifirst, out int iLast, out string
throw new Exception("Found start of TOC and then another start of TOC");
}

ifirst = i; instr = (runElements[f2] as FieldCode).Text;
ifirst = i;
instr = ((FieldCode) runElements[f2]).Text;
}
if (f4 != -1 && f4 > f1 && f4 > f2 && f4 > f3)
{
Expand Down Expand Up @@ -141,7 +147,7 @@ private static bool FindToc(Body body, out int ifirst, out int iLast, out string
continue;
}

var sp = p.ParagraphProperties.OfType<SectionProperties>().FirstOrDefault();
var sp = p.ParagraphProperties?.OfType<SectionProperties>().FirstOrDefault();
if (sp == null)
{
continue;
Expand Down
2 changes: 1 addition & 1 deletion tools/MarkdownConverter/OptionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ namespace MarkdownConverter;

internal static class OptionExtensions
{
public static T Option<T>(this FSharpOption<T> o) where T : class
public static T? Option<T>(this FSharpOption<T> o) where T : class
{
if (FSharpOption<T>.GetTag(o) == FSharpOption<T>.Tags.None)
{
Expand Down
10 changes: 6 additions & 4 deletions tools/MarkdownConverter/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ static int Main(string[] args)
else
{
// Windows command-shell doesn't do globbing, so we have to do it ourselves
string dir = Path.GetDirectoryName(arg), filename = Path.GetFileName(arg);
string dir = Path.GetDirectoryName(arg) ?? throw new ArgumentException($"'{arg}' is a root directory");
string filename = Path.GetFileName(arg);
if (dir.Contains("*") || dir.Contains("?"))
{
Console.Error.WriteLine("Can't match wildcard directory names");
Expand All @@ -55,7 +56,8 @@ static int Main(string[] args)
}

var imdfiles = new List<string>();
string idocxfile = null, odocfile = null;
string? idocxfile = null;
string? odocfile = null;
foreach (var ifile in ifiles)
{
var name = Path.GetFileName(ifile);
Expand Down Expand Up @@ -126,7 +128,7 @@ static int Main(string[] args)
Console.WriteLine($"Writing '{Path.GetFileName(odocfile2)}'");
try
{
MarkdownSpecConverter.ConvertToWord(md, idocxfile, odocfile2, reporter);
MarkdownSpecConverter.ConvertToWord(md, idocxfile!, odocfile2, reporter);
}
catch (Exception ex)
{
Expand All @@ -142,4 +144,4 @@ static int Main(string[] args)
Console.WriteLine($"Warnings: {reporter.Warnings}");
return reporter.Errors == 0 ? 0 : 1;
}
}
}
7 changes: 5 additions & 2 deletions tools/MarkdownConverter/Spec/MarkdownSpec.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,12 @@ private MarkdownSpec(IEnumerable<Tuple<string, MarkdownDocument>> sources, Repor
}
}

public static MarkdownSpec ReadFiles(IEnumerable<string> files, Reporter reporter, Func<string, TextReader> readerProvider = null)
public static MarkdownSpec ReadFiles(IEnumerable<string> files, Reporter reporter, Func<string, TextReader>? readerProvider = null)
{
if (files is null) throw new ArgumentNullException(nameof(files));
if (files is null)
{
throw new ArgumentNullException(nameof(files));
}

readerProvider ??= File.OpenText;

Expand Down
16 changes: 8 additions & 8 deletions tools/MarkdownConverter/Spec/Reporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ public class Reporter
/// <summary>
/// The parent reporter, if any. (This is to allow a complete error/warning count to be kept.)
/// </summary>
private readonly Reporter parent;
private readonly Reporter? parent;

public int Errors { get; private set; }
public int Warnings { get; private set; }

public SourceLocation Location { get; set; } = new SourceLocation(null, null, null, null);

private Reporter(Reporter parent, TextWriter writer, string filename)
private Reporter(Reporter? parent, TextWriter writer, string? filename)
{
this.parent = parent;
this.writer = writer;
Expand All @@ -38,33 +38,33 @@ public Reporter(TextWriter writer) : this(null, writer, null)

public Reporter WithFileName(string filename) => new Reporter(this, writer, filename);

public string CurrentFile => Location.File;
public string? CurrentFile => Location.File;

public SectionRef CurrentSection
public SectionRef? CurrentSection
{
get => Location.Section;
set => Location = new SourceLocation(CurrentFile, value, CurrentParagraph, null);
}

public MarkdownParagraph CurrentParagraph
public MarkdownParagraph? CurrentParagraph
{
get => Location.Paragraph;
set => Location = new SourceLocation(CurrentFile, CurrentSection, value, null);
}

public MarkdownSpan CurrentSpan
public MarkdownSpan? CurrentSpan
{
get => Location.Span;
set => Location = new SourceLocation(CurrentFile, CurrentSection, CurrentParagraph, value);
}

public void Error(string code, string msg, SourceLocation loc = null)
public void Error(string code, string msg, SourceLocation? loc = null)
{
IncrementErrors();
Report(code, "ERROR", msg, loc?.Description ?? Location.Description);
}

public void Warning(string code, string msg, SourceLocation loc = null)
public void Warning(string code, string msg, SourceLocation? loc = null)
{
IncrementWarnings();
Report(code, "WARNING", msg, loc?.Description ?? Location.Description);
Expand Down
6 changes: 3 additions & 3 deletions tools/MarkdownConverter/Spec/SectionRef.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public class SectionRef
/// <summary>
/// Section number, e.g. 10.1.2, or A.3 or null for sections without a number (e.g. Foreword).
/// </summary>
public string Number { get; }
public string? Number { get; }

/// <summary>
/// Section title, e.g. "10.1.2 Goto Statement"
Expand Down Expand Up @@ -43,9 +43,9 @@ public SectionRef(MarkdownParagraph.Heading mdh, string filename, string bookmar
{
Level = mdh.size;
var spans = mdh.body;
if (spans.Length == 1 && spans.First().IsLiteral)
if (spans.Length == 1 && spans.First() is MarkdownSpan.Literal literal)
{
Title = MarkdownUtilities.UnescapeLiteral(spans.First() as MarkdownSpan.Literal).Trim();
Title = MarkdownUtilities.UnescapeLiteral(literal).Trim();
if (char.IsDigit(Title[0]) || (Title[0] >= 'A' && Title[0] <= 'D' && Title[1] == '.'))
{
var titleParts = Title.Split(new[] { ' ' }, 2);
Expand Down
18 changes: 10 additions & 8 deletions tools/MarkdownConverter/Spec/SourceLocation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ namespace MarkdownConverter.Spec;

public class SourceLocation
{
public string File { get; }
public SectionRef Section { get; }
public MarkdownParagraph Paragraph { get; }
public MarkdownSpan Span { get; }
public string _loc; // generated lazily.
public string? File { get; }
public SectionRef? Section { get; }
public MarkdownParagraph? Paragraph { get; }
public MarkdownSpan? Span { get; }
public string? _loc; // generated lazily.

public SourceLocation(string file, SectionRef section, MarkdownParagraph paragraph, MarkdownSpan span)
public SourceLocation(string? file, SectionRef? section, MarkdownParagraph? paragraph, MarkdownSpan? span)
{
File = file;
Section = section;
Expand Down Expand Up @@ -42,19 +42,21 @@ public string Description
}
else
{
// TODO: Revisit all of the null-forgiving operator usage here at some point.

// Note: we now use the F# Markdown support for ranges, rather than finding text directly.
// This produces slightly weaker diagnostics than before, but it avoids an awful lot of fiddly fuzzy text matching code.

// TODO: Revisit SectionRef.Loc, possibly just exposing the paragraph directly.
var maybeRange = GetRange(Span);
var maybeRange = GetRange(Span!);
if (maybeRange != null)
{
var range = maybeRange.Value;
_loc = $"{File}({range.StartLine},{range.StartColumn},{range.EndLine},{range.EndColumn})";
}
else
{
maybeRange = GetRange(Paragraph) ?? GetRange(Section.Loc.Paragraph);
maybeRange = GetRange(Paragraph!) ?? GetRange(Section!.Loc.Paragraph!);
if (maybeRange == null)
{
// We don't have any line or column information. Just report the filename.
Expand Down
19 changes: 0 additions & 19 deletions tools/MarkdownConverter/Spec/StringLengthComparer.cs

This file was deleted.

Loading