vfmt: process imports and module name

pull/3779/head
Alexey 2020-02-19 00:35:14 +03:00 committed by GitHub
parent aaf3ced750
commit 200d3e6446
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 49 additions and 3 deletions

View File

@ -26,10 +26,9 @@ pub fn fmt(file ast.File, table &table.Table) string {
mut f := Fmt{ mut f := Fmt{
out: strings.new_builder(1000) out: strings.new_builder(1000)
table: table table: table
indent: -1 indent: 0
} }
f.stmts(file.stmts) return f.process(file)
return f.out.str().trim_space() + '\n'
} }
pub fn (f mut Fmt) write(s string) { pub fn (f mut Fmt) write(s string) {
@ -49,6 +48,45 @@ pub fn (f mut Fmt) writeln(s string) {
f.empty_line = true f.empty_line = true
} }
fn (f mut Fmt) process(file ast.File) string {
f.mod(file.mod)
f.imports(file.imports)
for stmt in file.stmts {
f.stmt(stmt)
}
return f.out.str().trim_space() + '\n'
}
fn (f mut Fmt) mod(mod ast.Module) {
if mod.name != 'main' {
f.writeln('module ${mod.name}\n')
}
}
fn (f mut Fmt) imports(imports []ast.Import) {
if imports.len == 1 {
imp_stmt_str := f.imp_stmt_str(imports[0])
f.writeln('import ${imp_stmt_str}\n')
} else if imports.len > 1 {
f.writeln('import (')
f.indent++
for imp in imports {
f.writeln(f.imp_stmt_str(imp))
}
f.indent--
f.writeln(')\n')
}
}
fn (f Fmt) imp_stmt_str(imp ast.Import) string {
imp_alias_suffix := if imp.alias != imp.mod {
' as ${imp.alias}'
} else {
''
}
return '${imp.mod}${imp_alias_suffix}'
}
fn (f mut Fmt) stmts(stmts []ast.Stmt) { fn (f mut Fmt) stmts(stmts []ast.Stmt) {
f.indent++ f.indent++
for stmt in stmts { for stmt in stmts {

View File

@ -0,0 +1,4 @@
import (
filepath
os
)

View File

@ -0,0 +1,2 @@
import filepath
import os

View File

@ -0,0 +1 @@
import os

View File

@ -0,0 +1 @@
import os