#Compile time option for parsing

1 messages · Page 1 of 1 (latest)

faint charm
#

I want to have a better API for my comptime parsing. The only way I have right now is to have a separate method for comptime, and then passing undefined into where the allocator would go, and try to communicate to the parsing function that the allocator shouldn't be used.

pub const Mode = enum(u1) {
  compile_time,
  run_time,
};

fn parseImpl(comptime mode: Mode, allocator: Allocator, ...) Parsed {
  ...
}

pub fn parseComptime(...) Parsed {
  return parseImpl(.compile_time, undefined, ...);
}

pub fn parseRuntime(allocator: Allocator, ...) Parsed {
  return parseImpl(.run_time, allocator, ...);
}

I was wondering if there was a way to have compile time union tags, but potential runtime data, so like:

pub const ParseMode = union(enum(u1)) {
  compile_time: void,
  run_time: std.mem.Allocator,
};

in which case I wouldn't have to use undefined:

fn parseImpl(mode: Mode, ...) Parsed {
  ...
}

pub fn parseComptime(...) Parsed {
  return parseImpl(.compile_time, ...);
}

pub fn parseRuntime(allocator: Allocator, ...) Parsed {
  return parseImpl(.{ .run_time = allocator }, ...);
}

this doesn't work, as mode is not compile time known, so the compile time logic will be analysed for runtime. what's the best way to handle this situation?

wicked token
#

there was a discussion about this some time back... an option that was brought up was to split the union into two arguments, the tag being the first, and comptime known, the other being the satellite value, of type that depends on the tag:

pub fn parseImpl(comptime tag: std.meta.Tag(ParseMode), satellite: std.meta.TagPayload(tag), …) …

not sure if that's the best way to attain your use case though

faint charm
#

that kinda works but I don't know if it's much better than what I have

#

is it worth submitting "comptime union tags" as a proposal?

wicked token
#

I don't think it'll be accepted - it requires a value to be partially comptime, which, I believe, will require a big rework of the existing system...

how about getting an anytype argument, then switching on its type, expecting it to either be ComptimeMode (an empty struct), or RuntimeMode (having an allocator field).

error if the type provided is none of those.

faint charm
#

hm not a bad idea

#

thanks

#

will leave it open in case anyone has any more ideas

bitter rock
wicked token