Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
add.cpp
Go to the documentation of this file.
1/*
2 * This file is part of the Fun programming language.
3 * https://fun-lang.xyz/
4 *
5 * Copyright 2026 Johannes Findeisen <you@hanez.org>
6 * Licensed under the terms of the Apache-2.0 license.
7 * https://opensource.org/license/apache-2-0
8 */
9
10/**
11 * @file add.cpp
12 * @brief Fun VM C++ opcode snippet: add two 64-bit integers (cpp_add).
13 *
14 * This opcode is compiled and linked only when the CMake option
15 * `-DFUN_WITH_CPP=ON` is enabled. It demonstrates how to implement a
16 * VM opcode in C++ while exposing a C ABI symbol for the VM dispatcher.
17 *
18 * Stack behavior:
19 * - Pops: b:int64, a:int64
20 * - Pushes: (a + b):int64
21 *
22 * Error handling and type conversions (e.g., from other numeric types to
23 * int64) are delegated to the VM helpers `vm_pop_i64` and `vm_push_i64`.
24 */
25
26#include <cstdint>
27
28extern "C" {
29#include "vm.h" // C header; provides VM, vm_pop_i64, vm_push_i64
30}
31
32/**
33 * @brief Add two 64-bit integers from the VM stack and push the sum.
34 *
35 * Pops two values from the VM stack using `vm_pop_i64`, adds them as
36 * 64-bit signed integers, and pushes the result via `vm_push_i64`.
37 *
38 * Stack effect:
39 * - Input: [..., a:int64, b:int64]
40 * - Output: [..., (a+b):int64]
41 *
42 * @param vm Pointer to the VM instance. Must not be NULL.
43 * @return 0 on success. Any stack underflow or conversion errors are
44 * handled by the VM helpers; non-zero may be used by future
45 * implementations to indicate a runtime error.
46 */
47extern "C" int fun_op_cpp_add(VM *vm) {
48 int64_t a = vm_pop_i64(vm);
49 int64_t b = vm_pop_i64(vm);
50 vm_push_i64(vm, a + b);
51 return 0; // success
52}
Value a
Definition add.c:37
int fun_op_cpp_add(VM *vm)
Add two 64-bit integers from the VM stack and push the sum.
Definition add.cpp:47
uint32_t b
Definition band.c:32
The Fun virtual machine state.
Definition vm.h:110
void vm_push_i64(VM *vm, int64_t v)
Push a 64-bit integer as a VM int Value (C ABI helper).
Definition vm.c:621
int64_t vm_pop_i64(VM *vm)
Pop a numeric Value and convert it to a 64-bit integer (C ABI helper).
Definition vm.c:598
Core virtual machine data structures and public VM API.