vlang / v

Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. Supports automatic C => V translation. https://vlang.io
MIT License
35.76k stars 2.16k forks source link

fmt: group and order imports #9353

Closed Gladear closed 3 years ago

Gladear commented 3 years ago

Imports should be grouped by "type" (vlib, .vmodules, program modules) and ordered alphabetically, so they are easier to find in a big list of imports.

e.g.


import os
import time

import gg // once it is moved to an external module
import ui

import internal.mod1
import internet.mod2
atakanyenel commented 3 years ago

I could tackle this with:

// vlib/v/fmt/fmt.v
pub fn (mut f Fmt) imports(imports []ast.Import) {
    if f.did_imports || imports.len == 0 {
        return
    }
    mut sorted_imports:=imports.clone()
    sorted_imports.sort(a.mod<b.mod) // new lines
    f.did_imports = true
    mut import_formatted := false // also used this instead of an integer
    mut already_imported := map[string]bool{}

    for imp in sorted_imports {
...

This currently only works for sorting. One catch is that, this breaks

HEAVILY. So to introduce this to the codebase, there will be a large scale change in everyones forks.

JalonSolov commented 3 years ago

As V is still in Alpha status, large scale changes should be expected from time to time.

atakanyenel commented 3 years ago

The one concern I have is speed regression of fmt. clone and sort are expensive operations. Nevertheless, once imports are sorted in the first run, next runs can do a is_sorted operation(which is linear) and get rid of both clone and sort all together.


For grouping, the type of the import should come from ast, which currently doesn't have that kind of info in pub struct Import.

JalonSolov commented 3 years ago

"Make it work first, then optimize."

And you should never optimize without benchmarking, profiling, and considering use-cases. For example, there's really no need to even try to optimize some things because they are executed so seldom that it simply isn't worth the optimization effort.

serkonda7 commented 3 years ago

I think grouling is avlot more important than the alphabetical order, therefore I'm against an incomplete implementation.