Skip to content

compiler: extend cast syntax for initlists #301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

chqrlie
Copy link
Contributor

@chqrlie chqrlie commented Jun 23, 2025

  • parse compound cast expressions: depending on surrounding code, explicit casts can be more readable than implicit conversions as function arguments or return values.
  • add tests

@bvdberg
Copy link
Member

bvdberg commented Jun 24, 2025

We had 'compound literals' before this commit right? Only without the cast. The type was inferred from the LHS. Adding the cast only seems to make the code longer, or am I missing something?

@chqrlie
Copy link
Contributor Author

chqrlie commented Jun 24, 2025

We had 'compound literals' before this commit right? Only without the cast. The type was inferred from the LHS. Adding the cast only seems to make the code longer, or am I missing something?

Yes, this commit implements compound literals:

  • it is much simpler as an extension to the cast operator.
  • the type cannot always be inferred from the LHS, eg: if the LHS is a pointer or if there is no LHS.
  • it is sometimes more readable to spell the type explicitly for the next casual reader of the code.

@bvdberg
Copy link
Member

bvdberg commented Jun 24, 2025

What would happen with?

Expr e = (SubExpr){ 1, 2, 3 };

@chqrlie
Copy link
Contributor Author

chqrlie commented Jun 24, 2025

What would happen with?

Expr e = (SubExpr){ 1, 2, 3 };

This would be a constraint violation, but if we have implicit upcasts, this would work:

Expr* e = &(SubExpr){ 1, 2, 3 };

And if we allow structures to implicitly decay to pointers like arrays, the & would be optional too.
Note that this works at the global scope too.

A more interesting example:

i32* p = (i32[]){ 1, 2, 3, 4, 5, 6 };
fn i32 sum(i32* p, usize count) { ... }
sum((i32[]){ 1, 2, 3, 4, 5, 6 }, 6);

Or this one for string conversions:

fn char* toBinary(u64 val, char* dest, usize len) { ... }

// no need to name the temporary char buffer used for the conversion
// it remains in scope for the duration of the current block, which is exactly what we need for this purpose.
printf("%d in binary: %s\n", val, toBinary(val, (char[65]){}, 65));

* parse compound cast expressions: depending on surrounding code, explicit
  casts can be more readable than implicit conversions as function arguments
  or return values.
* add tests
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants