Fix: Issue 256 "named member struct initialisers"

This commit is contained in:
sobaya 2019-07-30 13:02:48 +09:00
parent 4fea171d2f
commit ac61efe767
5 changed files with 31 additions and 1 deletions

View File

@ -23,6 +23,12 @@ struct BraceIndentInfo
uint beginIndentLevel;
}
struct StructInitializerInfo
{
size_t startLocation;
size_t endLocation;
}
/// AST information that is needed by the formatter.
struct ASTInformation
{
@ -53,6 +59,8 @@ struct ASTInformation
sort(sharedStaticConstructorDestructorLocations);
sort!((a,b) => a.endLocation < b.endLocation)
(indentInfoSortedByEndLocation);
sort!((a,b) => a.endLocation < b.endLocation)
(structInfoSortedByEndLocation);
sort(ufcsHintLocations);
ufcsHintLocations = ufcsHintLocations.uniq().array();
}
@ -118,6 +126,9 @@ struct ASTInformation
size_t[] ufcsHintLocations;
BraceIndentInfo[] indentInfoSortedByEndLocation;
/// Opening & closing braces of struct initializers
StructInitializerInfo[] structInfoSortedByEndLocation;
}
/// Collects information from the AST that is useful for the formatter
@ -272,6 +283,8 @@ final class FormatVisitor : ASTVisitor
{
astInformation.structInitStartLocations ~= structInitializer.startLocation;
astInformation.structInitEndLocations ~= structInitializer.endLocation;
astInformation.structInfoSortedByEndLocation ~=
StructInitializerInfo(structInitializer.startLocation, structInitializer.endLocation);
astInformation.indentInfoSortedByEndLocation ~=
BraceIndentInfo(structInitializer.startLocation, structInitializer.endLocation);

View File

@ -725,10 +725,14 @@ private:
void formatColon()
{
import dfmt.editorconfig : OptionalBoolean;
import std.algorithm : canFind;
immutable bool isCase = astInformation.caseEndLocations.canFindIndex(current.index);
immutable bool isAttribute = astInformation.attributeDeclarationLines.canFindIndex(
current.line);
immutable bool isStructInitializer = astInformation.structInfoSortedByEndLocation
.canFind!(st => st.startLocation < current.index && current.index < st.endLocation);
if (isCase || isAttribute)
{
writeToken();
@ -748,7 +752,9 @@ private:
|| peekBack2Is(tok!":", true)) && !(isBlockHeader(1) && !peekIs(tok!"if")))
{
writeToken();
if (!currentIs(tok!"{"))
if (isStructInitializer)
write(" ");
else if (!currentIs(tok!"{"))
newline();
}
else

View File

@ -0,0 +1,4 @@
void foo()
{
S s = {a: 3};
}

4
tests/issue0256.d Normal file
View File

@ -0,0 +1,4 @@
void foo()
{
S s = { a: 3 };
}

View File

@ -0,0 +1,3 @@
void foo() {
S s = {a: 3};
}