Skip to content

Commit

Permalink
Use an anonymous union in std::result
Browse files Browse the repository at this point in the history
  • Loading branch information
ashn-dot-dev committed Jul 17, 2023
1 parent d94fc90 commit 8bccfb1
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
18 changes: 8 additions & 10 deletions lib/std/std.sunder
Expand Up @@ -19,21 +19,24 @@ struct error_info {
# in the value state, indicating computation success, or the error state,
# indicating computation failure.
struct result[[T, E]] {
var _data: _result_union[[T, E]];
var _data: union {
var value: T;
var error: E;
};
var _is_value: bool;

# Initialize a result in the value state (success).
func init_value(value: T) result[[T, E]] {
return (:result[[T, E]]){
._data = (:_result_union[[T, E]]){._value = value},
._data = (:union { var value: T; var error: E; }){.value = value},
._is_value = true,
};
}

# Initialize a result in the error state (failure).
func init_error(error: E) result[[T, E]] {
return (:result[[T, E]]){
._data = (:_result_union[[T, E]]){._error = error},
._data = (:union { var value: T; var error: E; }){.error = error},
._is_value = false,
};
}
Expand All @@ -55,7 +58,7 @@ struct result[[T, E]] {
if not self.*._is_value {
std::panic("attempted to retrieve value from std::result in the error state");
}
return self.*._data._value;
return self.*._data.value;
}

# Returns the error associated with a result in the error state.
Expand All @@ -65,15 +68,10 @@ struct result[[T, E]] {
if self.*._is_value {
std::panic("attempted to retrieve error from std::result in the value state");
}
return self.*._data._error;
return self.*._data.error;
}
}

union _result_union[[T, E]] {
var _value: T;
var _error: E;
}

# Type representing a value that may not be present. An optional is either in
# the value state, indicating that the value is present, or the empty state,
# indicating that the value is absent.
Expand Down
4 changes: 2 additions & 2 deletions resolve.c
Expand Up @@ -5559,7 +5559,7 @@ resolve_type_struct(struct resolver* resolver, struct cst_type const* type)
}

struct symbol_table* const struct_symbols =
symbol_table_new(context()->global_symbol_table);
symbol_table_new(resolver->current_symbol_table);
sbuf_push(context()->chilling_symbol_tables, struct_symbols);
struct type* const resolved_type = type_new_struct(name, struct_symbols);
freeze(resolved_type);
Expand Down Expand Up @@ -5624,7 +5624,7 @@ resolve_type_union(struct resolver* resolver, struct cst_type const* type)
}

struct symbol_table* const union_symbols =
symbol_table_new(context()->global_symbol_table);
symbol_table_new(resolver->current_symbol_table);
sbuf_push(context()->chilling_symbol_tables, union_symbols);
struct type* const resolved_type = type_new_union(name, union_symbols);
freeze(resolved_type);
Expand Down

0 comments on commit 8bccfb1

Please sign in to comment.