A better C should just be like what Apple is doing for iBoot, or Microsoft with Checked C, by disabling what makes C unsafe while being mostly compatible.
Changing stuff like
- ptr = array into ptr = &array[0]
- num_value = enum_value into num_value = base_value(enum_value)
- char *str into cstring str
- char str[10] into a proper array without pointer decay (alternatively like cstring, a new array like type declaration)
If it is C like, while requiring major code rewrites, then it is just another attempt, regardless of how much valuable work has been put into it.
C++ got its adoption by having been born in the same place as C and UNIX, as C pre-processor with zero friction in C toolchain, hence why it was quickly adopted by C compiler vendors.
Any C replacement needs the same ease of transition, specially for domains that will never move beyond C, because reasons.
Introducing keywords in front of declarations is actually a required syntactical change to make the syntax context-free, i.e. to avoid having to carry around a symbol table during syntax parsing, as C requires. (Well, another method would be something like "declaredname :: type { impl }" but it requires more lookahead and it's a much more different syntax).
And all modern languages have added something like this. Personally I'm used to the C way and I like it for its terseness, but the modern approach allows for simplified parsers and better tooling.
In fact C started out like that just as well: There were only a constant number of keywords, like int, void, struct... that could introduce a declaration. But, with the advent of typedef (and C++ which automatically removes the need for the struct tag for all struct definitions) that changed, and in effect a symbol table is now required for parsing.
I agree there is a need for easy transition, but I think that ease mostly comes from being able to be compiled and linked in existing tool chains like this project does.
I wrote a C compiler as well, got as far as compiling a hello world and all the includes it needs on a standard Linux or MacOS system. My plan was to have a sort of strict option that would be enabled if you wanted to use the new features like modules and namespaces, and the strict option would error on problematic C code.
Anyway I stopped the project when Rust released their first version without garbage collection. It seems to me they solved all my concerns and they didn't even need to integrate C itself.
Illustrates why projects don't do this:
> If you're breaking backwards compatibility anyway, why not go all the way?
Rust usage, even with millions of dollars of marketing and eleven years of hype, is still almost a rounding error in terms of usage.
One tiny hobby language I use was changed to accept semicolons as an additional end-of-line, just to allow more easy copy-pasting of C code. It's surprising how portable C is in that sense too. If you're going C-style, probably best to stick C-style. (But I used fn in my own C-alike... who am I to judge?)
`num_value = enum_value`... that might actually happen. I haven't decided.
"`char str` into cstring str"... no? The whole story with strings haven't been 100% decided yet, but likely this will be: `char str` raw character string `char[]` a string slice, preferred over null terminating char*, and finally `String` which is a userland, dynamic string.
Something you can do with C3 is that you can convert as much or as little you want from C to C3. C3 is ABI compatible with C, so you can just compile using the C3 compiler for some files and then with GCC or Clang the C files. In fact I did this with vkQuake, converting a little bit of code into C3 and removing that from the .c files, then compiling the C3 code with c3c and the C code with Clang, then linking it together and it runs as if all had been written in C.
https://twitter.com/nuoji/status/1417212252843880451
Edit: And regarding `func` it's for easy parsing and greping for IDEs and editors.
I absolutely abhor modern C++ syntax, but there's one thing I think they deserve credit for. The C++ community is thinking deeply about first principles, consistency, composability, memory models and forward progress guarantees. I hope anyone looking to improve C learns from the longsuffering of the C++ world while avoiding many of their syntactical mistakes and evolutionary half-steps.
I really hope the C++ standards committee has a well funded legal purse. In 20 years when the lawsuits start coming from all the ex-programmers battling brain tumors they're going to need it.</s>
And RAII, that's just some syntax to make writing badly structured programs practical. Because it does the tedious parts of matching "parentheses", it allows you to use a lot of them, without consideration if you could refactor the program to get away with fewer of them.
RAII also comes at the cost of requiring or encouraging "features" like exceptions and all the good stuff like copy/move constructors and what not. All highly non-orthogonal language features that require lots and lots of special cases and extra boilerplate.
I kind of want to at least get hashmaps in before I go public.
Re C3, I think the README could do with more sample code? Not exactly "Hello World", but something to get you hyped about using it.
Things I like:
- macros! macros are fucking awesome. giv examples
- modules are just a straight win
- built-in dynamic arrays, yess.
- compile-time execution is kind of a precondition for macros. Hopefully the same system.
- I've always wanted to play with generic modules. `import foo!(int) as IntFoo;` It seems a logical extension.
- Result-based error handling for the win. Though it really depends on language support how straightforward this is; it can easily degenerate into very spammy error handling. Definitely would like to see examples of this.
- Built-in strings: hopefully UTF-8!
- No preprocessor. Heck yes, it's a crutch.
- Pre/postconditions are nice, but they make a lot of mess on inheritance.
- Immutability by default is definitely a win.
Things you should totally steal from my language: :)
- Format strings are just nice.
- Packages as a generalization of modules: a package is a folder in the same way a module is a file. Dependencies between packages must be explicitly stated. This makes the build system's dependency tracking actually meaningful by effectively doing away with the global search path. I wish more languages would do this.
- D recently acquired automatic C header file import. (Neat has this as a macro.) I cannot overstate how useful this is for hitting the ground running.
- I don't know if your macro implementation has quasiquoting (it's hard to tell from the examples) but if not: add it. This makes macros immensely more convenient.
Hopefully just bytes, which trivially allows storage of UTF-8.
> built-in dynamic arrays, yess.
Dynamic arrays are only few lines to implement. There are different ways to do them, and no matter how, there will always be some problematic aspects. Not sure why you would want to choose one particular implementation and elevate it to a higher status.
> No preprocessor. Heck yes, it's a crutch.
It's ugly and inexperienced users will write bugs using it, but it's also tremendously useful. You mentioned quasiquoting as an alternative, but I'm not positive that it works as a preprocessor replacement for a language that lacks the "homomiconity" of LISP. Are there examples that show it works?
Just having a default in the language is insanely useful. I can only appeal to experience here (with D, which has built-in arrays), but I never want to be without them again. This goes doubly for my language, where dynamic arrays are actually a bit involved due to the need for slices, refcounting and capacity tracking for the doubling strategy on append. Not something you want to reimplement everywhere.
> It's ugly and inexperienced users will write bugs using it, but it's also tremendously useful. You mentioned quasiquoting as an alternative, but I'm not positive that it works as a preprocessor replacement for a language that lacks the "homomiconity" of LISP. Are there examples that show it works?
As an example, something like
#define SQUARE(X) ({ typeof(X) x = X; x * x; })
could in a language with macros (and a better function macro syntax than I have at the moment :p) be rewritten as macro SQUARE(X) ({ typeof($X) x = $X; x * x; });
Which has the exact same effect, but does not suffer from the C preprocessor problems caused by string/token interpolation. Also, errors can be easily and cleanly attributed to the actual location they occur, because SQUARE's nature is a parse tree, not a token list.As for macros like `#define BEGIN {`, I consider it an advantage that they don't work. :)
> Hopefully just bytes, which trivially allows storage of UTF-8.
Yes, it trivially allows, but then you'd need to deal with utf8-errors all over the program at runtime. Any method for string would need to be written such a way, that deals with invalid utf8 byte sequences.
Unix and C is a living example of what happens when you think of a string as of a arbitrary sequence of bytes. It gives a lot of edge cases which a programmer must bear in his/her mind constantly, because these edge cases would choose the least expected moment to jump on you. And then you'd need, for example, to invent a way to output an arbitrary byte sequence into a place where only UTF8 is allowed. I, personally, hate it. Like arbitrary byte sequences as a file names, even when I know that no one uses non-utf8 file names, I need to write programs working with file names in such a way, that allows arbitrary byte sequences, and to devise some syntax to output arbitrary byte-sequence into a terminal. Or into a web-page.
I see no good reasons to replace strings with arbitrary byte-sequences. If you need arbitrary byte-sequences then you have another abstraction for your task: an array. Much more powerful, because it can be array of bytes, of uint16_t, or of int64_t, or of your own struct. Why to spoil an abstraction of string with an ability to deal with arbitrary byte sequences?
I don't know, maybe for interoperable type safe types to use across an ecosystem of libraries without wasting CPU cycles converting among them?
- A module isn't a file in C3 but that's a deep subject to get into.
- Automatic C header file import is something Zig is also touting as a feature. This was something I thought I would want early on. But as I worked myself through examples I find that it's hard to get right in all cases, which means that you'll run into cases where your language "almost" works. Plus now you actually tied your language not only to the C ABI, but the entire C standard (note how headers will for example contain static inline code that you will need to parse, or macros that define aliases of functions and builtins). That said a tool to automatically extract a "best effort" interface is planned.
- Regarding macros the difficulty has been to balance power with readability. So that is something which I am considering but still haven't quite embraced. Instead I have macros taking unevaluated expressions and you can in compile time get different things, e.g. `$offsetof("Foo", "a")` will give you the offset of the member `a` in the type `Foo`, but it's done through a special function rather than allowing straight up string interpolation. We'll see once the standard library work starts for real.
https://github.com/neat-lang/neat
Because Neat is self-hosted and frequently depends on syntax features added a few commits ago, building from fresh source can take up to half an hour. You also need a D compiler (for the initial bootstrap version), but that comes with gcc nowadays. If you wanna try that, just run `bootstrap.sh`. (You may have to patch it to use gdc, not ldc, but the commandline should be the same.) This takes a while because it has to build the compiler something like 60 times, each with the previous version.
Don't do that though! Gimme a ping and I'll slap a new release tag on it. The releases use the C backend to generate a C dump of the compiler, that can then be shipped and compiled on the target system.
Neat is more a D-like than a C-like, but it only breaks C syntax in areas where I think C straight up made the wrong call, like the inside-out type syntax.
Memory management uses automatic ref counting, with some optimizations to keep number of inc/dec manageable.
The thing I'm most proud of is the full-powered macro system, which is really more of a compile-time compiler plugin system.
Here's an example of using the C import macro to bind to a C library: https://github.com/Neat-Lang/neat/blob/master/demos/glfw.nt
Another good example of a macro would be listcomprehensions: https://github.com/Neat-Lang/neat/blob/master/src/neat/macro...
You can tell it's just compiler code that happens to be loaded at project compiletime.
You can see listcomprehensions at work in the sparkline demo: https://github.com/Neat-Lang/sparkline/blob/master/src/spark...
`compiler.$expr xxx` is itself a macro, that parses an expression `xxx` and returns an expression that creates a syntax tree that, when compiled, is equivalent to having written `xxx`. It's effectively the opposite of `eval`. In that expression, `$identifier` is expanded to a variable reference to "identifier".
So `ASTSymbol test = compiler.$expr $where && $test;` is equivalent to `ASTSymbol test = new ASTBinary("&&", where, test)`. (This shows its worth as expressions become more expansive.)
All in all, this lets you write `bool b = [all a == 5 for a in array]`, and it's exactly equivalent to a plain for loop. You can see the exact for loop at line 103 in that file. `({ })` is stolen from gcc; google "statement expression".
The one thing I'm still blocking on is hashmaps, once that's in I'll make a proper announcement post.
And, of course, documentation. :-)
It should compile fine on MacOS and Linux. There is CI for Windows but the readme is missing install instructions for Win. This might be helpful to get it up and running on Windows: https://gist.github.com/kvk1920/57e1851d106bed86ded8c3232895...
I am happy for all the feedback I can get, even if you just hate it completely :D
"Well, there's spam egg sausage and spam, that's not got much spam in it."
sorry, couldn't resist.
So far it seems a beautiful thing. Will take a deeper look and try to form an opinion. Great work!
But hey, hope that something interesting grows out of this. I quite like almost-C languages, but then again I also liked the Bourne Shell macros ;)
One of these days I have to write a Oberon-in-sheeps-brackets.
For an interesting "C++ that doesn't look like C" variant, consider SPECS (Conway/Werther;1996)[1].
[1]: https://users.monash.edu/~damian/papers/HTML/ModestProposal....
- "Failables" (which is somewhat like Result) offers an alternative to error handling which mostly mirrors how one commonly does it in C, but with conveniences. Since it works a bit different from all other error systems, I'd have to point to the docs for a summary. :(
- Semantic macros where the big win is that they are easier to read and write. (This is heavily inspired by the ASTEC macro system for C)
- Generic modules, which works similar to macro-based generics in C, but easier to read and work with.
- Subarrays (slices), yes they make a huge difference even though they're an obvious addition.
- A bunch of GCC extensions
- Optional design by contract
There are no objects, and certainly no dynamic OO system. There are no constructors and destructors or similar explicit code.
Calling C is straightforward, you just need to declare that it exists, like you would in C.
So `extern func int printf(char*, ...)` -> now you can do `printf("Hello %s\n", "World");` the opposite also works, so if you define a function `func void foo() @extname("c3_foo")` you can then call it from C as `c3_foo()` (or skip the `@extname` but you would have to call `my_module_foo()` instead due to namespacing.
No mandatory header files
New semantic macro system
Module based name spacing
Subarrays (slices) and dynamic arrays built in
Compile time reflection
Enhanced compile time execution
Generics based on generic modules
"Result"-based zero overhead error handling
Defer
Value methods
Associated enum data
Built in strings
No preprocessor
Undefined behaviour trapped on debug by default
Optional pre and post conditions
Associated enum data sounds like variant types. It has namespacing and it has generics. That alone is almost worth it to me (not that I'd use a language with no community.) If it had lambdas, that'd be the quadrivium for me.Apparently it has struct subtyping too.
That being said, if you're crazy enough to write a C replacement in the first place, then maybe you'll be crazy enough to incorporate my crazy suggestion for function specialization. In functional languages, given a function f(w,x,y,z) with many parameters, it's straightforward to define another function g(a,b) with fewer parameters as being equal to f(H,b,a,K), a more general function specialized by fixed constants for some of the parameters and arbitrary permutations of the others. I'd like to be able to express the transformation that takes a pointer to the general function f as input and returns a pointer to the specialized function g, such that the pointer to g can be used in the same context as any other pointer to a function of that arity and type defined the normal way. I'd like it to be possible in a library written be me operating on user-supplied pointers to functions not known in advance, I'd like to avoid workarounds such as global static variables or thread-specific storage, and I'd like you to convince me that your implementation of this feature is too simple to be wrong.
[1] "Some Were Meant for C" by Stephen Kell https://doi.org/10.1145/3133850.3133867
[2] "C Traps and Pitfalls" by Andrew Koenig
edit: typo
(looks at hello world: looks nothing like c)
I really like the idea of modules without the .h files littering every directory.
Headers have some really unbeatable advantages over module interfaces: the tooling is incomparable plus the header serves as the API documentation.
While modules are great, in practice you have interop problems and you still need a tool (if it is a binary file) to extract the interfacing API.
Modules are better from an elegance and clean-design PoV, but headers win on the practicality.
IMO they are the #1 reason C still has a lot of adoption, but not for good reasons: headers hinder interoperability. To interop with C you either need a C-compatible compiler (C++, Obj-C, and now D, Zig) or a human writing interop code by hand. Both things come with a hefty cost, and the first carries the danger of your language having to keep terrible features forever (the C part of C++).
Headers hinder the evolution of the language and the ecosystem.
Modules, on the other hand, enable interop easily, preventing lock-in.
But then all macros go to headers, even private ones. Also inline functions.
func void Point.add(Abc * p, int x)
...
i.e. a method with the first argument of a non-matching type. If it's not allowed, then why not use this ?The main motivation why it is nice to have it this way is that it's straightforward to understand what the type is when doing `&Point.add`. I have considered a `this` but it's not felt super important to have. Also, note that this is allowed: `Point *x = null; x.doSomething();` - this is made more obvious by taking the reference as an explicit parameter.
It's cool, though. Funny how we can get stuck with a language from the early 70s and we're still in the process of replacing it half a century later.
Maybe you don't mean to sound harsh but from their About page:
" It is an evolution of C enabling the same paradigms and retaining the same syntax as far as possible."
I don't think Zig has the same goal.
Also, they usefully compare the languages:
"In Zig but not in C3
Pervasive compile time execution.
Memory allocation failure is an error.
Zig's compile time execution is the build system.
Different syntax and behaviour compared to C.
Structs define namespace.
Async primitives built in.
In C3 but not in Zig Module system
Integrated build system
Built-in strings, maps, vararrays
Optional contracts
Familiar C syntax and behaviour
"I see that as a good thing. I’d much rather have a battle tested framework than everything being rewritten every 5 years in whatever is currently trendy simply because a new generation of developers are suffering from NIH (not invented here) syndrome.
I mean, yes C has its problems so I’m all for using safer languages, but just take a look at the mess that is front end web development and tell me that the alternative isn’t better.
I seriously hope languages like Rust do evolve into being much more than a fad. I’ve been in the industry a fair few years now and have seen languages fall in and out of favour (Pascal, Java, OCaml, Go, etc sure someone of them are still popular but nowhere near as much as when their respective hype machine was in town) and really what systems development really needs is another ‘C’ — as in a language that survives the next 50 years as a standard low level language that people can build solid operating systems from. Whatever language people want to code on top of that base is then fair game.
Zig is in many ways a more ambitious language. Not just in the language itself but in the tooling. Unlike C3 it has the ambition to "do things right" - often by doing things differently. Sometimes that pans out, but sometimes not. For example Zig adds a lot of UB "to be fast", but there's a particularly worrying intersection of (a) UB in overflow, (b) introduction of unsigned overflow and (c) implicit type widening which adds a lot of hidden UB / runtime aborts.
The simple example here is `a : i32 = b + c + d`. Even knowing that b, c and d fits in a short is not sufficient to guarantee this will not have UB. And even if we know that `b + c + d` does not trigger UB, we cannot guarantee that `b + d + c` does not have UB(!). The usual solution it to require explicit widening casts, but that solution seems hard for Zig due to relying on a lot of non-power-of-two types in the core language.
I guess also it's a matter of how much you think C sucks :D
I like C, and C3 is basically just trying to tweak a few things C can't change due to legacy reasons. It doesn't try to be a new "let's write everything from scratch because C is bad" kind of language, if you hate C then C3 isn't for you.