Skip to content
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

Reference to field's type in initializer shouldn't result in invalid access errors #26445

Open
bradcray opened this issue Dec 20, 2024 · 1 comment

Comments

@bradcray
Copy link
Member

bradcray commented Dec 20, 2024

Today, we don't permit references to fields within an init() rouitne before they're initialized, to avoid read-before-init errors. However, the current error-checking also prevents us from referring to the types of such fields (even when they have no runtime type information), which seems too strict. As an example (ATO):

record R {
  var x: int;

  proc init(y: x.type) {
    writeln(x.type:string);
    this.x = y;
  }
}

var myR = new R(y=42);
writeln(myR);

The two references to x.type before x is initialized generate warnings:

code.chpl:4: In initializer:
code.chpl:5: error: field "x" used before it is initialized
code.chpl:4: error: invalid access of class member in initializer argument list

but it seems like they shouldn't.

@mppf
Copy link
Member

mppf commented Jan 2, 2025

There are two reasons that fixing this issue might be more complicated than it appears at first.

  1. (As you mentioned) We have runtime types. If x was an array, x.type would be a runtime type (referring to the domain) and it would refer to uninitialized memory / be an error if x isn't initialized yet. That means that any improvement along these lines would not apply to all fields; it could only apply to fields that don't have a runtime type.
  2. When working with a generic class/record, the proc init constructs the type of the result. E.g. if we had record R { var x; } then proc R.init() { x = 1; } is setting the type of x to be int. In such cases, IMO the field can't be used before it is initialized, because the type of it isn't established yet.

The result is that IMO it's not clear if it's better to leave things as-is (where the rules are more universally applied) or to add some exceptions to make simple-enough cases like this work (as this issue proposes).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants