Skip to content

Commit 9703410

Browse files
committed
vfmt: fix formatting of submodules with common prefixes (fix #15582)
1 parent 1915bf8 commit 9703410

File tree

2 files changed

+50
-4
lines changed

2 files changed

+50
-4
lines changed

vlib/v/ast/str.v

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,12 +164,42 @@ fn stringify_fn_after_name(node &FnDecl, mut f strings.Builder, t &Table, cur_mo
164164
}
165165
f.write_string(')')
166166
if node.return_type != void_type {
167-
mut rs := util.no_cur_mod(t.type_to_str(node.return_type), cur_mod)
168-
for mod, alias in m2a {
169-
rs = rs.replace(mod, alias)
167+
sreturn_type := util.no_cur_mod(t.type_to_str(node.return_type), cur_mod)
168+
short_sreturn_type := shorten_full_name_based_on_aliases(sreturn_type, m2a)
169+
f.write_string(' ' + short_sreturn_type)
170+
}
171+
}
172+
173+
struct StringifyModReplacement {
174+
mod string
175+
alias string
176+
weight int
177+
}
178+
179+
fn shorten_full_name_based_on_aliases(input string, m2a map[string]string) string {
180+
// Shorten the full names to their aliases, but replace the longer mods first, so that:
181+
// `import user.project`
182+
// `import user.project.routes`
183+
// will lead to replacing `user.project.routes` first to `routes`, NOT `user.project.routes` to `project.routes`.
184+
// Also take into account the nesting level, so `a.e.c.d` will be shortened before `a.xyz.b`, even though they are the same length.
185+
mut replacements := []StringifyModReplacement{cap: m2a.len}
186+
for mod, alias in m2a {
187+
if input.contains(mod) {
188+
replacements << StringifyModReplacement{
189+
mod: mod
190+
alias: alias
191+
weight: mod.count('.') * 100 + mod.len
192+
}
193+
}
194+
}
195+
mut res := input.clone()
196+
if replacements.len > 0 {
197+
replacements.sort(a.weight > b.weight)
198+
for r in replacements {
199+
res = res.replace(r.mod, r.alias)
170200
}
171-
f.write_string(' ' + rs)
172201
}
202+
return res
173203
}
174204

175205
// Expressions in string interpolations may have to be put in braces if they
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
module app
2+
3+
import user.project
4+
import user.project.routes
5+
6+
pub fn new_app() ?project.Application {
7+
return project.Application{
8+
data: get_router()!.route_name
9+
}
10+
}
11+
12+
fn get_router() ?routes.Router {
13+
return routes.Router{
14+
route_name: 'Root'
15+
}
16+
}

0 commit comments

Comments
 (0)