fmt: align the custom values of the enum fields (#19331)

This commit is contained in:
yuyi 2023-09-12 19:44:38 +08:00 committed by GitHub
parent c98e00c01f
commit 55ca8d8d8e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
47 changed files with 1342 additions and 1322 deletions

View file

@ -876,7 +876,7 @@ pub fn (mut f Fmt) comptime_for(node ast.ComptimeFor) {
f.writeln('}') f.writeln('}')
} }
struct ConstAlignInfo { struct ValAlignInfo {
mut: mut:
max int max int
last_idx int last_idx int
@ -896,10 +896,10 @@ pub fn (mut f Fmt) const_decl(node ast.ConstDecl) {
f.inside_const = false f.inside_const = false
} }
f.write('const ') f.write('const ')
mut align_infos := []ConstAlignInfo{} mut align_infos := []ValAlignInfo{}
if node.is_block { if node.is_block {
f.writeln('(') f.writeln('(')
mut info := ConstAlignInfo{} mut info := ValAlignInfo{}
for i, field in node.fields { for i, field in node.fields {
if field.name.len > info.max { if field.name.len > info.max {
info.max = field.name.len info.max = field.name.len
@ -907,14 +907,14 @@ pub fn (mut f Fmt) const_decl(node ast.ConstDecl) {
if !expr_is_single_line(field.expr) { if !expr_is_single_line(field.expr) {
info.last_idx = i info.last_idx = i
align_infos << info align_infos << info
info = ConstAlignInfo{} info = ValAlignInfo{}
} }
} }
info.last_idx = node.fields.len info.last_idx = node.fields.len
align_infos << info align_infos << info
f.indent++ f.indent++
} else { } else {
align_infos << ConstAlignInfo{0, 1} align_infos << ValAlignInfo{0, 1}
} }
mut prev_field := if node.fields.len > 0 { mut prev_field := if node.fields.len > 0 {
ast.Node(node.fields[0]) ast.Node(node.fields[0])
@ -1002,9 +1002,29 @@ pub fn (mut f Fmt) enum_decl(node ast.EnumDecl) {
} }
f.writeln('enum ${name} {') f.writeln('enum ${name} {')
f.comments(node.comments, same_line: true, level: .indent) f.comments(node.comments, same_line: true, level: .indent)
for field in node.fields { mut align_infos := []ValAlignInfo{}
mut info := ValAlignInfo{}
for i, field in node.fields {
if field.name.len > info.max {
info.max = field.name.len
}
if !expr_is_single_line(field.expr) {
info.last_idx = i
align_infos << info
info = ValAlignInfo{}
}
}
info.last_idx = node.fields.len
align_infos << info
mut align_idx := 0
for i, field in node.fields {
if i > align_infos[align_idx].last_idx {
align_idx++
}
f.write('\t${field.name}') f.write('\t${field.name}')
if field.has_expr { if field.has_expr {
f.write(strings.repeat(` `, align_infos[align_idx].max - field.name.len))
f.write(' = ') f.write(' = ')
f.expr(field.expr) f.expr(field.expr)
} }