1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

fmt: keep comments after imports (#8483)

This commit is contained in:
Lukas Neubert 2021-02-01 14:45:08 +01:00 committed by GitHub
parent 44ec9e3ebc
commit 8755f40430
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 35 additions and 18 deletions

View File

@ -283,7 +283,8 @@ pub:
mod_pos token.Position
alias_pos token.Position
pub mut:
syms []ImportSymbol // the list of symbols in `import {symbol1, symbol2}`
syms []ImportSymbol // the list of symbols in `import {symbol1, symbol2}`
comments []Comment
}
// import symbol,for import {symbol} syntax

View File

@ -14,7 +14,7 @@ enum CommentsLevel {
// - has_nl: adds an newline at the end of the list of comments
// - inline: single-line comments will be on the same line as the last statement
// - iembed: a /* ... */ embedded comment; used in expressions; // comments the whole line
// - level: either .keep (don't indent), or .indent (increment indentation)
// - level: either .keep (don't indent), or .indent (increment indentation)
struct CommentsOptions {
has_nl bool = true
inline bool
@ -105,6 +105,34 @@ pub fn (mut f Fmt) comments_after_last_field(comments []ast.Comment) {
}
}
pub fn (mut f Fmt) import_comments(comments []ast.Comment, options CommentsOptions) {
if comments.len == 0 {
return
}
if options.inline {
mut i := 0
for i = f.out_imports.len - 1; i >= 0; i-- {
if !f.out_imports.buf[i].is_space() { // != `\n` {
break
}
}
f.out_imports.go_back(f.out_imports.len - i - 1)
}
for c in comments {
ctext := c.text.trim_left('\x01')
if ctext == '' {
continue
}
mut out_s := if options.inline { ' ' } else { '' }
out_s += '//'
if is_first_char_alphanumeric(ctext) {
out_s += ' '
}
out_s += ctext
f.out_imports.writeln(out_s)
}
}
fn is_first_char_alphanumeric(s string) bool {
return match s[0] {
`a`...`z`, `A`...`Z`, `0`...`9` { true }

View File

@ -22,7 +22,6 @@ pub mut:
table &table.Table
out_imports strings.Builder
out strings.Builder
out_save strings.Builder
indent int
empty_line bool
line_len int
@ -272,6 +271,7 @@ pub fn (mut f Fmt) imports(imports []ast.Import) {
}
already_imported[import_text] = true
f.out_imports.writeln(import_text)
f.import_comments(imp.comments, inline: true)
num_imports++
}
if num_imports > 0 {

View File

@ -1,6 +0,0 @@
import semver
// as semver
fn main() {
}

View File

@ -1,4 +0,0 @@
import semver// as semver
fn main() {
}

View File

@ -1,3 +1,5 @@
import semver // as sv
enum Abc {
a
b // after a value

View File

@ -1,5 +0,0 @@
import os
fn main() {
os.system('echo hi')
}

View File

@ -1907,6 +1907,7 @@ fn (mut p Parser) import_stmt() ast.Import {
return import_node
}
}
import_node.comments = p.eat_line_end_comments()
p.imports[mod_alias] = mod_name
// if mod_name !in p.table.imports {
p.table.imports << mod_name