Skip to content

User-Defined Constant Functions #2222

Open
@Jetz72

Description

@Jetz72

Seeing as this idea didn't reveal any glaring flaws when I asked at #1296 (comment), I figured I'd make it into a full feature request and see what comes of it.

The suggestion is for users to be able to define their own constant getters, operators, and functions with a restricted set of language features, which can be run at compile time. Naturally, interacting with non-constant/final members of classes wouldn't be possible. Recursion and conditional iteration probably should be prevented too if you don't want to risk the compiler never halting.

It might look something like:

class Foo
{
	final int a;
	final int b;
	
	const Foo(this.a, this.b);
	
	const int withC(int c) => (c > 0) ? (a + c) : (b + c);
	
	const int get aPlusB => a + b;
	
	//Operators in particular would be nice, in order to help bridge the gap between system types and others.
	const Foo operator+ (Foo other) => Foo(a + other.a, b + other.b); 
	
	//Can use string interpolation on primitives if toString is off the table.
	static const int _computeB(int x) => "${(x * 180 + 374)}".length;
	
	//Being able to use helper methods in constructors is a good way to split complicated things out from initializer lists, so it'd be cool to be able to do it with constant objects.
	const Foo.fromX(int x) : this(x, _computeB(x)); 
}

class Bar
{
	const Foo data = Foo.fromX(23);
	const Foo otherData = data + Foo.fromX(3);
	
	static void processData() {
		const info = data.aPlusB + otherData.withC(-4); //All computed at compile time.
		print(info.toString())
	}
}

It'd be cool to have full code block bodies with local variables, if and switch statements, maaaaaybe for-each loops, whatever else that can be done without side effects... But I'm not sure how much complexity that'd add, and expressions alone would be make for a helpful addition to the language.

Could make for a partial solution to #2219 - if some of those members could be defined as constant then they wouldn't have to be directly included in the language spec. I imagine some of the more fundamental ones like List.operator[] will still need to be, though.

I'm sorta realizing the ramifications and potential complications of a feature like this as I type it up and I'm sure I don't have the complete picture, so I'd be glad to hear others' thoughts on it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhanced-constRequests or proposals about enhanced constant expressionsfeatureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions