+static ast_expression *parser_builtin_mod(parser_t *parser) {
+ /*
+ * float __builtin_mod(float x, float y) {
+ * return x - y * floor(x / y);
+ * }
+ */
+ static ast_value *mod_func_val = NULL;
+ static ast_expression *mod_floor = NULL;
+
+ if (!mod_floor) {
+ if (!(mod_floor = parser_find_global(parser, "floor"))) {
+ parseerror(parser, "internal error: no suitable definition found for `floor` (required for % and __builtin_mod)");
+ return NULL;
+ }
+ }
+
+ if (!mod_func_val) {
+ ast_value *mod_args[2];
+ ast_function *mod_func = NULL;
+ ast_block *mod_body = ast_block_new (parser_ctx(parser));
+ ast_call *mod_call = ast_call_new (parser_ctx(parser), mod_floor);
+ mod_func_val = ast_value_new (parser_ctx(parser), "__builtin_mod", TYPE_FUNCTION);
+ mod_func_val->expression.next = (ast_expression*)ast_value_new(parser_ctx(parser), "<float>", TYPE_FLOAT);
+ mod_func = ast_function_new(parser_ctx(parser), "__builtin_mod", mod_func_val);
+ mod_args[0] = ast_value_new (parser_ctx(parser), "x", TYPE_FLOAT);
+ mod_args[1] = ast_value_new (parser_ctx(parser), "x", TYPE_FLOAT);
+
+ /* floor(x/y) */
+ vec_push(mod_call->params,
+ (ast_expression*)ast_binary_new(
+ parser_ctx(parser),
+ INSTR_DIV_F,
+ (ast_expression*)mod_args[0],
+ (ast_expression*)mod_args[1]
+ )
+ );
+
+ vec_push(mod_body->exprs,
+ (ast_expression*)ast_return_new(
+ parser_ctx(parser),
+ (ast_expression*)ast_binary_new(
+ parser_ctx(parser),
+ INSTR_SUB_F,
+ (ast_expression*)mod_args[0],
+ (ast_expression*)ast_binary_new(
+ parser_ctx(parser),
+ INSTR_MUL_F,
+ (ast_expression*)mod_args[1],
+ (ast_expression*)mod_call
+ )
+ )
+ )
+ );
+
+ vec_push(mod_func_val->expression.params, mod_args[0]);
+ vec_push(mod_func_val->expression.params, mod_args[1]);
+
+ vec_push(mod_func->blocks, mod_body);
+
+ vec_push(parser->functions, mod_func);
+ vec_push(parser->globals, (ast_expression*)mod_func_val);
+ }
+
+ return (ast_expression*)mod_func_val;
+}
+