Skip to content
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
89 changes: 89 additions & 0 deletions CodeBlocker.Test/TemplateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1552,6 +1552,95 @@ public void ASourceFileWithAnEmptyExpressionBodyWritesNothing()
Assert.AreEqual(string.Empty, codeBlocker.ToString());
}

[TestMethod]
public void ANullMethodParameterIsRefusedBeforeTheClassIsWritten()
{
MethodTemplate method = new() { Name = "M", Type = "void", BodyFactory = _ => { } };
method.Parameters.Add(null!);
ClassTemplate type = new() { Name = "C", Members = { method } };

using CodeBlocker codeBlocker = CodeBlocker.Create(CodeBlocker.DefaultIndentString, NewLines.Lf);

InvalidOperationException exception =
Assert.ThrowsExactly<InvalidOperationException>(() => codeBlocker.AddClass(type));
Assert.Contains("'M'", exception.Message);
Assert.Contains("Parameters", exception.Message);
Assert.AreEqual(string.Empty, codeBlocker.ToString());
}

[TestMethod]
public void ANullPositionalParameterIsRefusedBeforeTheRecordIsWritten()
{
ClassTemplate record = new() { Name = "R", Kind = TypeKind.Record };
record.PositionalParameters.Add(null!);

using CodeBlocker codeBlocker = CodeBlocker.Create(CodeBlocker.DefaultIndentString, NewLines.Lf);

InvalidOperationException exception =
Assert.ThrowsExactly<InvalidOperationException>(() => codeBlocker.AddClass(record));
Assert.Contains("'R'", exception.Message);
Assert.Contains("PositionalParameters", exception.Message);
Assert.AreEqual(string.Empty, codeBlocker.ToString());
}

[TestMethod]
public void ANullConstructorParameterIsRefusedBeforeTheClassIsWritten()
{
ConstructorTemplate constructor = new() { Name = "C" };
constructor.Parameters.Add(null!);
ClassTemplate type = new() { Name = "C", Members = { constructor } };

using CodeBlocker codeBlocker = CodeBlocker.Create(CodeBlocker.DefaultIndentString, NewLines.Lf);

Assert.ThrowsExactly<InvalidOperationException>(() => codeBlocker.AddClass(type));
Assert.AreEqual(string.Empty, codeBlocker.ToString());
}

[TestMethod]
public void ANullOperatorParameterIsRefusedBeforeTheOperatorIsWritten()
{
OperatorTemplate op = new() { Type = "Money", Symbol = "-", Keywords = { "public", "static" } };
op.Parameters.Add(null!);

using CodeBlocker codeBlocker = CodeBlocker.Create(CodeBlocker.DefaultIndentString, NewLines.Lf);
codeBlocker.WriteLine("int a;");

Assert.ThrowsExactly<InvalidOperationException>(() => op.WriteTo(codeBlocker));
Assert.AreEqual("int a;\n", codeBlocker.ToString());
}

[TestMethod]
public void ANullMethodParameterIsRefusedWhenTheMethodIsWrittenOnItsOwn()
{
MethodTemplate method = new() { Name = "M", Type = "void", BodyFactory = _ => { } };
method.Parameters.Add(null!);

using CodeBlocker codeBlocker = CodeBlocker.Create(CodeBlocker.DefaultIndentString, NewLines.Lf);
codeBlocker.WriteLine("int a;");

Assert.ThrowsExactly<InvalidOperationException>(() => method.WriteTo(codeBlocker));
Assert.AreEqual("int a;\n", codeBlocker.ToString());
}

[TestMethod]
public void ANullMemberOrNestedClassIsRefusedWithTheTypeNamed()
{
ClassTemplate withNullMember = new() { Name = "A" };
withNullMember.Members.Add(null!);
ClassTemplate withNullNested = new() { Name = "B" };
withNullNested.NestedClasses.Add(null!);

using CodeBlocker codeBlocker = CodeBlocker.Create(CodeBlocker.DefaultIndentString, NewLines.Lf);

InvalidOperationException memberException =
Assert.ThrowsExactly<InvalidOperationException>(() => codeBlocker.AddClass(withNullMember));
Assert.Contains("'A'", memberException.Message);
InvalidOperationException nestedException =
Assert.ThrowsExactly<InvalidOperationException>(() => codeBlocker.AddClass(withNullNested));
Assert.Contains("'B'", nestedException.Message);
Assert.AreEqual(string.Empty, codeBlocker.ToString());
}

[TestMethod]
public void AnInvalidMemberOfANestedClassLeavesTheOuterClassUnwritten()
{
Expand Down
12 changes: 11 additions & 1 deletion CodeBlocker/Templates/ClassTemplate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ public class ClassTemplate : TemplateBase
/// <see cref="Kind"/>, or the kind of a nested type, is not a known kind. Nothing is written.
/// </exception>
/// <exception cref="InvalidOperationException">
/// A member, or a member of a nested type, would be refused when written. Nothing is written.
/// A member, or a member of a nested type, would be refused when written, or
/// <see cref="Members"/>, <see cref="NestedClasses"/> or <see cref="PositionalParameters"/> holds a
/// <see langword="null"/> entry. Nothing is written.
/// </exception>
public override void WriteTo(CodeBlocker codeBlocker)
{
Expand Down Expand Up @@ -107,6 +109,14 @@ internal override void Validate(CodeBlocker codeBlocker)
base.Validate(codeBlocker);
_ = TypeKindKeywords.For(Kind);

// Null entries are refused here rather than found while writing: a null member or nested
// type would throw a bare NullReferenceException, and a null positional parameter would
// throw after "record R" is already written.
string owner = $"Type '{Name}'";
TemplateRendering.EnsureNoNullEntries(Members, nameof(Members), owner);
TemplateRendering.EnsureNoNullEntries(NestedClasses, nameof(NestedClasses), owner);
TemplateRendering.EnsureNoNullEntries(PositionalParameters, nameof(PositionalParameters), owner);

foreach (MemberTemplate member in Members)
{
member.Validate(codeBlocker);
Expand Down
11 changes: 11 additions & 0 deletions CodeBlocker/Templates/ConstructorTemplate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,27 @@ public class ConstructorTemplate : MemberTemplate
/// </summary>
/// <param name="codeBlocker">The <see cref="CodeBlocker"/> to write to.</param>
/// <exception cref="ArgumentNullException"><paramref name="codeBlocker"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">
/// <see cref="Parameters"/> holds a <see langword="null"/> entry. Nothing is written.
/// </exception>
public override void WriteTo(CodeBlocker codeBlocker)
{
Ensure.NotNull(codeBlocker);

Validate(codeBlocker);
base.WriteTo(codeBlocker);
TemplateRendering.WriteParameterList(codeBlocker, Parameters);
WriteInitialiserTo(codeBlocker);
TemplateRendering.WriteBody(codeBlocker, BodyFactory);
}

/// <inheritdoc/>
internal override void Validate(CodeBlocker codeBlocker)
{
base.Validate(codeBlocker);
TemplateRendering.EnsureNoNullEntries(Parameters, nameof(Parameters), $"Constructor '{Name}'");
}

private void WriteInitialiserTo(CodeBlocker codeBlocker)
{
List<string> arguments = TemplateRendering.NonBlank(BaseParameters);
Expand Down
11 changes: 11 additions & 0 deletions CodeBlocker/Templates/MethodTemplate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,25 @@ public class MethodTemplate : MemberTemplate
/// </summary>
/// <param name="codeBlocker">The <see cref="CodeBlocker"/> to write to.</param>
/// <exception cref="ArgumentNullException"><paramref name="codeBlocker"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">
/// <see cref="Parameters"/> holds a <see langword="null"/> entry. Nothing is written.
/// </exception>
public override void WriteTo(CodeBlocker codeBlocker)
{
Ensure.NotNull(codeBlocker);

Validate(codeBlocker);
base.WriteTo(codeBlocker);
TemplateRendering.WriteTypeParameterList(codeBlocker, TypeParameters);
TemplateRendering.WriteParameterList(codeBlocker, Parameters);
TemplateRendering.WriteConstraints(codeBlocker, Constraints);
TemplateRendering.WriteBody(codeBlocker, BodyFactory);
}

/// <inheritdoc/>
internal override void Validate(CodeBlocker codeBlocker)
{
base.Validate(codeBlocker);
TemplateRendering.EnsureNoNullEntries(Parameters, nameof(Parameters), $"Method '{Name}'");
}
}
11 changes: 7 additions & 4 deletions CodeBlocker/Templates/OperatorTemplate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,16 @@ public class OperatorTemplate : MemberTemplate
/// <param name="codeBlocker">The <see cref="CodeBlocker"/> to write to.</param>
/// <exception cref="ArgumentNullException"><paramref name="codeBlocker"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">
/// <see cref="Kind"/> is not an <see cref="OperatorKind"/> value. Nothing is written.
/// <see cref="Kind"/> is not an <see cref="OperatorKind"/> value, or <see cref="Parameters"/>
/// holds a <see langword="null"/> entry. Nothing is written.
/// </exception>
public override void WriteTo(CodeBlocker codeBlocker)
{
Ensure.NotNull(codeBlocker);

// Worked out before anything is written, so an unknown kind cannot leave a half-written
// declaration behind.
// Checked before anything is written, so an unknown kind or a null parameter cannot leave a
// half-written declaration behind.
Validate(codeBlocker);
string signature = Signature;

// Not through the MemberTemplate implementation: an operator's signature is its symbol and
Expand All @@ -83,7 +85,8 @@ public override void WriteTo(CodeBlocker codeBlocker)
internal override void Validate(CodeBlocker codeBlocker)
{
base.Validate(codeBlocker);
_ = Signature;
string signature = Signature;
TemplateRendering.EnsureNoNullEntries(Parameters, nameof(Parameters), $"Operator '{signature}'");
}

private string Signature => Kind switch
Expand Down
18 changes: 18 additions & 0 deletions CodeBlocker/Templates/TemplateRendering.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,24 @@ private static bool IsLoneSurrogate(string value, int index)
return false;
}

/// <summary>
/// Throws if a template's collection holds a <see langword="null"/> entry, which would otherwise
/// only be found partway through writing the declaration that lists it.
/// </summary>
/// <typeparam name="T">The entry type.</typeparam>
/// <param name="entries">The collection to check.</param>
/// <param name="collectionName">The collection's property name, for the message.</param>
/// <param name="owner">The template that holds the collection, for the message.</param>
/// <exception cref="InvalidOperationException">An entry is <see langword="null"/>.</exception>
internal static void EnsureNoNullEntries<T>(IEnumerable<T?> entries, string collectionName, string owner)
where T : class
{
if (entries.Any(entry => entry is null))
{
throw new InvalidOperationException($"{owner} has a null entry in {collectionName}.");
}
}

/// <summary>
/// Drops the <see langword="null"/>, empty and whitespace entries from a list of verbatim
/// fragments, so that a generator can pass <c>condition ? "IFoo" : ""</c> without the blank
Expand Down
Loading