Andrew wants to ban tabs again?

This is not a compelling argument IMO.

There are two ways that one can think about the semantic value of “zig-like” multi-line string literals:

  1. Take everything after the \\ until the beginning of the next line. Take all such results until you reach a non-whitespace/comment token. Concatenate them, then remove the terminating line ending, if any.
  2. Take everything after the \\ until just before the next line ending. Take all such results until you reach a non-whitespace/comment token. Join them with \n as a separator.

What you are describing is #1, but notice that #2 is:

  • Slightly cognitively simpler (no special case for the last line)
  • A better experience for Windows users (no need for every repo to have a .gitattributes with *.zig text eol=lf)
  • How zig currently operates:

If you make this source file with CRLF line endings:

pub fn main() void {
    std.debug.print("{q}", .{
        \\asdf
        \\
    });
}

You’ll get as output:

"asdf\n"

But I also don’t think comparing “LF vs CRLF” and “spaces vs tabs” is particularly helpful. The former is mostly a matter of operating system defaults, while the latter is mostly a matter of personal preference. So even if we want to enforce a very strict style in zig, we should be lenient about things that a user doesn’t control (at least without doing a bunch of extra work).

Personally, I don’t use tabs, so I won’t care much if they’re disallowed, but I feel like making them a compile error is probably a bridge too far. Consider users trying out zig for the first time. How many users who are used to tabs will stop using the language before they understand how awesome it is, just because they’re used to using tabs and don’t want to change? Are the advantages of enforcing a no-tabs policy at the compiler level worth losing those users? I agree with a couple of the other posters here; the way to go is just having zig fmt change tabs to spaces, but not having the compiler complain if they’re present.

12 Likes

Uh good point, you could strip CR alongside the LF, I hadn’t thought about it.

I think that would mean that the package manager either needs to do much more work to make the package contents have a consistent hash, or you would have different package contents with different hashes based on how you have created the source files.

I think having source code be more towards being normalized (even if not fully), instead of arbitrary switching back and forth between having CRLF endings or just LF, is a good thing.

And personally I just think that tools which can’t work with LF endings and require or forcefully add CRLF need to be made irrelevant thrown to the trash pile (or patched if you really care).

No, the zig package manager does not need to do any line ending conversion, even when using git+https:// urls for dependencies, so there is no issue with hashes. As I mentioned, zig already works using the behavior I mentioned, and it does not have a problem with dependency hashes.

But a default install of Git for Windows will convert LF to CRLF for all text files when checking out, and back to LF when committing (at least last time I checked). That is where the leniency becomes useful.

2 Likes

I feel that way about software that isn’t able to handle something as simple as crlf. It’s also why on ever git install I have on every system I use, both Windows, Linux and FreeBSD is to disable the stupid feature of converting line endings when uploading and downloading. All the options that are not just don’t touch are bad.
But I guess we are all moving away from the original topic which was tabs.

1 Like

Zig’s multiline string literals already allow and ignore CR before LF, and have for a long time (since 0.8 according to the langref).

Or, more pedantically, the line endings in the source text are not included in the multiline string literal in the first place; the content of a multiline string literal line is the verbatim data between \\ and the end of the line (LF, CRLF or end-of-file), and the content of a multiline string literal is the concatenated content of a sequence of multiline string literal lines, using LF as the joiner.

This design actually makes Zig’s multiline literals a bit more robust than “heredoc string literals” in some other languages (like @"/""" in C# to name one example) since the line endings of the source text are effectively ignored. So even if you’re collaborating with someone on Windows with bungled Git core.autocrlf settings, you can both remain certain that you get the same bit-by-bit identical string output.

This is the relevant state from std.zig.tokenizer. Note that the index is not incremented when encountering \n, \r\n or EOF, which means that the line endings are not included in the token.

.multiline_string_literal_line => {
    self.index += 1;
    switch (self.buffer[self.index]) {
        0 => if (self.index != self.buffer.len) {
            continue :state .invalid;
        },
        '\n' => {},
        '\r' => if (self.buffer[self.index + 1] != '\n') {
            continue :state .invalid;
        },
        0x01...0x09, 0x0b...0x0c, 0x0e...0x1f, 0x7f => continue :state .invalid,
        else => continue :state .multiline_string_literal_line,
    }
},

And this is the relevant part from AstGen (slice[2..] is for skipping the leading \\):

fn strLitNodeAsString(astgen: *AstGen, node: Ast.Node.Index) !IndexSlice {
    const tree = astgen.tree;

    const start, const end = tree.nodeData(node).token_and_token;

    const gpa = astgen.gpa;
    const string_bytes = &astgen.string_bytes;
    const str_index = string_bytes.items.len;

    // First line: do not append a newline.
    var tok_i = start;
    {
        const slice = tree.tokenSlice(tok_i);
        const line_bytes = slice[2..];
        try string_bytes.appendSlice(gpa, line_bytes);
        tok_i += 1;
    }
    // Following lines: each line prepends a newline.
    while (tok_i <= end) : (tok_i += 1) {
        const slice = tree.tokenSlice(tok_i);
        const line_bytes = slice[2..];
        try string_bytes.ensureUnusedCapacity(gpa, line_bytes.len + 1);
        string_bytes.appendAssumeCapacity('\n');
        string_bytes.appendSliceAssumeCapacity(line_bytes);
    }
    const len = string_bytes.items.len - str_index;
    try string_bytes.append(gpa, 0);
    return IndexSlice{
        .index = @fromBackingInt(@intCast(str_index)),
        .len = @intCast(len),
    };
}
9 Likes

Nope, that was on purpose because Go’s creators (Robert Griesemer, Rob Pike and Ken Thompson) prefer tabs because it let’s people chose visual indentation.

7 Likes

Has anyone already built a zig fmt that uses tabs for indent and spaces for alignment? That feels like a pre-requisite for any change here.

2 Likes

I have one hard stance in tabs vs spaces - that debates about it are a waste of everyone’s time. But I do feel like having a compiler tooling enforced resolution to the debate does not sit right with me. Sure, nobody forces anyone to use zig fmt, it’s not a prerequisite for compiling, but I’m just not sure it’s the right thing to do in my opinion. I think that software should serve the user, and software which is used to build software should serve the builder, and as long as the builder is not actively using screwdrivers to hammer nails, it seems counterproductive to impose restrictions on the color of hammer they use

10 Likes

If the primary reason for this whole debate is that tabs let you change their width, then that problem seems solvable in IDEs for spaces too. It’s already been created in tools like stretchy-spaces.

Perhaps the productive outcome of this debate is to make that functionality more wide-spread, as it’s not just a zig thing, it would help accessibility for so much more code.

1 Like

Yes, there are IDE plugins or option for making spaces visually and functionally behave like tabs, but that doesn’t help when you are not using an IDE.
For small test files, I frequently use my system editor. Or in the rare occasion when I’m using ssh I may only have a terminal with nano available.

Also I honestly don’t understand this solution of “just use these editor plugin to make them behave exactly like tabs”. Why not just use tabs directly instead of inventing new tools to make spaces behave like tabs?

13 Likes

When will we stop trying to force our stylistic preferences that mean nothing onto everybody? Compiler should compile code and not check if your function name is smth it agrees with

4 Likes

The nice thing about tabs is that they are language-agnostic[1]. When used in the tabs for indentation+spaces for alignment paradigm, you could stretch them however you want without ever risking displaying the code in any way other than intended, without the editor having to understand the language’s grammar and/or some extra heuristics to understand which spaces are for indentation and which are for alignment.

I personally like tabs for indentation and spaces for alignment (I even use a custom Helix patch to support it in some very basic way), but don’t use them in Zig simply because zig fmt “enforces” spaces.


  1. That is, as long as the language does not forbid them. ↩︎

3 Likes

I haven’t so far seen any formatter, no matter which paradigm they follow, which preserves alignment for leading whitespace.
Mostly because no matter if you use spaces of tabs, the formatter has to use heuristics when it comes to figuring out what was aligned and what was just sloppily indented.

For example go with this:

fn funWithBits(
     a: i16, // sloppy 5 space indentation
) u16 {
    const i: u16 = @bitCast(a);
    return ((i & 0xF000) >> 12) // alignment looking also like sloppy 5 space indentation
         | ((i & 0x0F00) >> 4)
         | ((i & 0x00F0) << 4)
         | ((i & 0x000F) << 12);
}

Alignment which isn’t leading whitespace is pretty easy. You just need to count.
But for leading whitespace… yeah, good look.

Honestly, I’m against everyone having it’s own formatting, I much prefer the authoritarian approach, I’d even be fine with zig refusing to compile non formatted code to be honest. That’s one of the thing I actually dislike the most about C/C++ is how garbage the ecosystem is because of that, every library has it’s own convention, it’s own formatting rules, it’s own .clangd-format and it’s absolutely a waste of everyone’s time.

At the end of the day, code is a tool, we use to make things, anything that improves the efficiency of making more things per unit of time is a win in my book. Therefore, having to adapt to 30 different formatting style, and NameCasing in order to reuse an ecosystem, is suboptimal at best. The perk of Zig is wherever you look the code is always formatted the same, and if someone doesn’t use zig fmt, I’ll personally make a point of not using the lib, or forking it and format it.

Same for the tab vs space, I think it’s fine to argue, and share opinion, but one thing we should be grateful for is the authoritative formatting, it saves time, and make sharing, reusing, reviewing code, that much easier.

19 Likes

Bit of a rant, but here is my 2 cents on this matter.

I would not enforce any formatting or naming convention in the compiler. These kinds of enforcements do have some benefits, but people should have the freedom to use whatever naming convention or formatting they want.

A closed source software does not have to care about its formatting, it just needs to be consistent (or not, who cares, as long as it works for the person/team). Why do I need to conform to someone elses subjective conventions? Why can’t I format my code the way that I think it makes sense? Sure, I might get used to it and not think about it after some point, but why do I even have to get used to it? Who cares? Why does the compiler have to go through my code, painfully check the formatting and conventions? A compilers job is simple, take my code and turn it into machine code. Nothing more, nothing less.

Open source software should follow the convention, just so it is easier for everyone to hop in and work on it. I don’t think it should be enforced though, again, why is my compiler checking my formatting and not compiling? Even in C or C++, if the code is written in a reasonable manner, it is readable. There are many examples for this, just let people use whatever formatting and convention they want.

7 Likes

I align pretty close to this position. I don’t feel strongly about the tabs vs. spaces debate, I can adapt to use either. While I do think it is a bit odd for a compiler to enforce it, to me it isn’t something even worth bike-shedding over.

As for formatting, I totally agree, I like when there is a One True Way for code to be formatted, though this is easy to say for Zig, which I pretty much agree 100% with its formatting choices. It is all great until you are using language like Go who keeps reformatting your 1 + 2 * 3 to 1+2*3, then I can understand the frustration some feel over formatting choices I know personally think is the “correct” way.

2 Likes

I’m all for freedom, but this is a kind of freedom, that benefits one person, and put the burden on everyone else, at least in collaborative spaces. Nobody cares about anyone formatting preferences, and in fact, nobody should have to care.

There are 2 kinds of formatting, the one which could probably be quantified as beneficial, spaces between operators, brackets, indentation, spacing and new lines, those are universal, I’m sure it would be easy to find studies that talk about the benefits associated with that (not just for code, but for text in general) and how it improves the accessibility for people with dyslexia and stuff.

And the kind that doesn’t matter, like which kind of casing to use for what, and prefixing with _foo or worse m_Foo (ewwwwwww) or doing pub fn my_function instead of pub fn MyFunCtion I understand everyone has their preferences I do too, but for the sake of the users, the debate shouldn’t exist, it should be one way, one formatting, and honestly I’d be down for the compiler to enforce it, and this would become a tooling issue, before any compilation, just format the code, and when editing it, format it back to whatever is it you like.

2 Likes

I also see 2 kinds of formatting, but in a slightly different way. The first is formatting that it is generally agreed to be better, for example having equal spaces on both sides of an operator (so not 1+ 2) and having no trailing whitespace on non-empty lines. I believe these things should be enforced in the compiler, because it does not make anyone unhappy and can catch some space typos.

The other is formatting where people do not agree which version is better. This category includes tabs vs spaces, casing, but also whether to do if (condition) break or with break on its own line with braces.
For this, there is zig fmt to make a decision, even though some people will not like it. In my opinion, the compiler should allow both ways, because enforcing one way will always make some people unhappy.
In a collaborative project, I am fine with following the conventions, even if I have to do m_Foo (ewwwwwww). But for my own projects, I like to write code that I find the most beautiful. For me, this includes writing it in Zig and using snake_case. So if the compiler would forbid snake_case, I would find my code a bit less nice. Having a consistent formatting in the ecosystem is nice, but I find it more important to let people write code in their favorite way.

4 Likes

That is quite a strong remark.
It sounds like all pianists have to play that Beethoven sonata at exactly mm 132, we are not allowed to breathe no more than 30 times a minute, have cereal for breakfast and go to sleep before midnight.
Code formatting is 100% free in my view.

6 Likes