25 Commits

Author SHA1 Message Date
c952be1fe6 Command line arguments 2025-08-25 19:13:00 +10:00
1c5ca8d201 Simple file and request libraries 2025-08-25 18:29:45 +10:00
e56e6de911 Experimental external library support 2025-08-25 17:35:16 +10:00
38b17e7db5 Add library guide 2025-08-25 14:10:14 +10:00
e74e5ea548 Update syntax 2025-08-25 13:51:22 +10:00
f5140e3833 Delete docs/writing-a-program 2025-08-25 13:36:04 +10:00
c01dd470e1 Update docs/writing-a-program.md 2025-08-25 13:35:56 +10:00
16660c6a8d More reliable scoping 2025-08-25 13:35:22 +10:00
5bd8519517 External library support 2025-08-25 13:22:15 +10:00
2f706e2285 Update lines of code in readme 2025-08-25 11:29:43 +10:00
db99b9ac9f Fix getstrcharat error message 2025-08-25 11:22:02 +10:00
e906734aca Fix function jumping bug (I think) 2025-08-24 20:22:52 +10:00
8da5a2bf93 Experimental function jumping 2025-08-24 16:30:42 +10:00
e9600d8500 Scoping 2025-08-24 15:08:07 +10:00
1c0dfcc4b7 Fix not 2025-08-24 14:41:34 +10:00
f7f3972248 Function arguments, start of scoping 2025-08-22 13:52:26 +10:00
50d83aa228 "not" instruction 2025-08-21 11:05:32 +10:00
14758df1ab Example calculator 2025-08-21 08:43:22 +10:00
b19b4123d8 Parser string and character fix 2025-08-18 13:38:26 +10:00
28a9e389fa Basic function calling support 2025-08-18 09:36:35 +10:00
e4cc6b2f14 Fix critical bug, further functions 2025-08-15 11:35:58 +10:00
bb753e97d4 Return function 2025-08-13 18:31:54 +10:00
4cd4d9080d Function declarations 2025-08-13 09:40:03 +10:00
52eadaa9c3 Typerefs and functionrefs 2025-08-12 09:45:00 +10:00
db0c362efb Start work on functions 2025-08-11 14:57:45 +10:00
13 changed files with 1193 additions and 74 deletions

View File

@@ -8,7 +8,7 @@ Ground is an interpreter which processes and interprets Ground instructions. It
* **Simple syntax:** Ground doesn't have very many features, and that's intentional. It makes Ground easy to learn, and keeps it speedy. * **Simple syntax:** Ground doesn't have very many features, and that's intentional. It makes Ground easy to learn, and keeps it speedy.
* **Super speed:** Ground code is faster than Python and JavaScript, and nearly as fast as C++ and Rust, while still being interpreted. (Tested using tests/to1000.grnd) * **Super speed:** Ground code is faster than Python and JavaScript, and nearly as fast as C++ and Rust, while still being interpreted. (Tested using tests/to1000.grnd)
* **Tiny interpreter:** Ground contains 1154 lines of code (and 320 lines of comments) at the time of writing, and compiles in seconds. * **Tiny interpreter:** Ground contains 1482 lines of code (and 382 lines of comments) at the time of writing, and compiles in seconds.
* **Portable:** Ground's code only uses features from the C++ standard library, using features from C++17 and prior. * **Portable:** Ground's code only uses features from the C++ standard library, using features from C++17 and prior.
## How do I get started? ## How do I get started?

107
docs/demos/calc.grnd Executable file
View File

@@ -0,0 +1,107 @@
#!/usr/bin/env ground
@begin
stdout "Calculation: "
stdin &calc
getstrsize $calc &calcsize
set &counter 0
set &left ""
set &right ""
set &operator ' '
set &isRight false
## Preprocessing
# Loop to parse input
@loopstart
getstrcharat $calc $counter &char
# Remove any spaces (they're inconvenient)
equal $char ' ' &cond
if $cond %doneif
# Check for operators
# '+' operator
inequal '+' $char &cond
if $cond %minusOpCheck
set &operator $char
set &isRight true
jump %doneif
@minusOpCheck
# '-' operator
inequal '-' $char &cond
if $cond %multiplyOpCheck
set &operator $char
set &isRight true
jump %doneif
@multiplyOpCheck
# '*' operator
inequal '*' $char &cond
if $cond %divideOpCheck
set &operator $char
set &isRight true
jump %doneif
@divideOpCheck
# '/' operator
inequal '/' $char &cond
if $cond %endOpChecks
set &operator $char
set &isRight true
jump %doneif
@endOpChecks
if $isRight %isRight
add $left $char &left
jump %doneif
@isRight
add $right $char &right
@doneif
add 1 $counter &counter
inequal $counter $calcsize &cond
if $cond %loopstart
# End loop
## Computing
# Convert types
stod $left &left
stod $right &right
# Calculations
# Adding
inequal $operator '+' &cond
if $cond %subtract
add $left $right &result
stdlnout $result
jump %begin
# Subtracting
@subtract
inequal $operator '-' &cond
if $cond %multiply
subtract $left $right &result
stdlnout $result
jump %begin
# Multiplying
@multiply
inequal $operator '*' &cond
if $cond %divide
multiply $left $right &result
stdlnout $result
jump %begin
# Dividing
@divide
inequal $operator '/' &cond
if $cond %error
divide $left $right &result
stdlnout $result
jump %begin
@error
stdlnout "Uh oh something terribly terrible happened lmao"
jump %begin

21
docs/library-guide.md Normal file
View File

@@ -0,0 +1,21 @@
# Guide to Writing Libraries in Ground
Ground has a "use" keyword which allows you to import libraries written in Ground, executing the code, and importing functions for use. This makes building reproducable bits of code very easy.
This is a guide of best practices which should be followed.
## .grnd file extension
The Ground interpreter will automatically append ".grnd" when you use a library. If you write `use "myLibrary"` Ground will look for "myLibrary.grnd". This is a must-do.
## camelCase Function and File Names
For consistency, please use camelCase (with a lower case first letter) when naming functions and file names.
## Don't use spaces
It is impossible to use spaces in Ground function names. Please do not use spaces in file names, even though it will work.
## Use functions for most operations
Where possible, create functions to do everything needed with your library. You can include some code for initialisation, but don't do the entirety of your operations outside of your functions.

View File

@@ -50,6 +50,12 @@ Reference a list (a list reference) with an asterisk:
setlist *myList $value1 $value2 # and so on setlist *myList $value1 $value2 # and so on
``` ```
Add comments with a `#`:
```
# This is a comment
```
## Keywords ## Keywords
Note: &var can be replaced with any direct reference. $value can be replaced with a literal value or a value reference. %1 can be replaced with a line reference. Note: &var can be replaced with any direct reference. $value can be replaced with a literal value or a value reference. %1 can be replaced with a line reference.
@@ -188,6 +194,12 @@ Checks if two values are not equal. Outputs a boolean to a direct reference.
Usage: `inequal $value $value &var` Usage: `inequal $value $value &var`
#### not
Negates a boolean.
Usage: `not $value &var`
#### greater #### greater
Checks if the left value is greater than the right value. Outputs a boolean to a direct reference. Checks if the left value is greater than the right value. Outputs a boolean to a direct reference.
@@ -220,7 +232,7 @@ Converts any type to a string.
Usage: `tostring $value &var` Usage: `tostring $value &var`
### Functions and function specific features (ALL WORK IN PROGRESS) ### Functions and function specific features (Experimental, please report bugs!)
Some symbols specific to this category: Some symbols specific to this category:
@@ -232,7 +244,15 @@ Some symbols specific to this category:
Defines a function. All code between `fun` and `endfun` will be included in the function. Defines a function. All code between `fun` and `endfun` will be included in the function.
Usage: `fun !functionname -type &var -type &var -type &var # and so on...` Usage: `fun -type !functionname -type &var -type &var -type &var # and so on...`
Usage note: The first type specified before the function name must be the return type. The type displayed before all vars shows what type that variable must be.
#### return
Returns back to the main program (or other function that called this function). Also returns a value, which must be of the type defined when defining the function.
Usage: `return $value`
#### endfun #### endfun
@@ -252,20 +272,22 @@ Calls a function, with all the arguments in the argument list. The return value
Usage: `call !function &var Usage: `call !function &var
### Interacting with Libraries (ALL WORK IN PROGRESS) ### Interacting with Libraries
#### use #### use (Experimental, please report bugs!)
Attempts to import another Ground program. Gets inserted wherever the use statement is. Any code (including code outside function declarations) will be executed. Attempts to import another Ground program. Gets inserted wherever the use statement is. Any code (including code outside function declarations) will be executed.
Note: Ground will check the directory where the program is stored when trying to find imported programs. If that fails, it will check the directory set in the $GROUND_PATH environment variable set by your system. The '.grnd' extension is appended automatically. Note: Ground will check the directory where the program is being run from when trying to find imported programs. If that fails, it will check the directory set in the $GROUND_LIBS environment variable set by your system. The '.grnd' extension is appended automatically.
Usage: `use $stringvalue` Usage: `use $stringvalue`
#### extern #### extern (Experimental, please report bugs!)
Attempts to import a shared object library written for Ground. All functions in the external library will be usable with `call`. Attempts to import a shared object library written for Ground. All functions in the external library will be usable with `call`.
Note: Ground will check the directory where the program is stored when trying to find external programs. If that fails, it will check the directory set in the $GROUND_PATH environment variable set by your system. The '.so', '.dll', etc extension is appended automatically. Note: Ground will check the directory set in the $GROUND_LIBS environment variable set by your system. The '.so' (Linux), '.dylib' (macOS), or '.dll' (Windows) extension is appended automatically.
Usage: `extern $stringvalue` Documentation on how to do external libraries coming soon.
Usage: `extern $stringvalue`

25
docs/writing-a-program.md Normal file
View File

@@ -0,0 +1,25 @@
## Writing programs with Ground (WORK IN PROGRESS GUIDE)
Ground is a very easy language to learn. In this guide, you will learn how to write a simple calculator in Ground, as well as best practices (which there aren't many of, since Ground is so simple).
Note: This assumes you've read and understand the syntax.md document in this folder.
### Let's start!
Open a new file with the `.grnd` extension. Should look something like this:
```
```
(Real empty in that file.)
Let's add some code! Create a label for the start, since we'll loop back once we've calculated, and ask for the user's input:
```
@start
stdout "Calculation: "
stdin &calc
```
At the calc variable, we have whatever the user typed in. This should look something like `9+10`, `1 / 3` or who knows what else. But first we should organise this data. Let's create a loop to iterate through this input, and a counter to keep moving forward:

43
extlibs/file.cpp Normal file
View File

@@ -0,0 +1,43 @@
#include "ground_lib.h"
#include <fstream>
#include <filesystem>
GroundValue readFile(GroundValue* args, int arg_count) {
VALIDATE_ARGS_1(GROUND_STRING);
std::ifstream ffile(GET_STRING(args[0]));
std::string tmp;
std::string out;
while (std::getline(ffile, tmp)) {
out += tmp + "\n";
}
return ground_string_val(out);
}
GroundValue writeFile(GroundValue* args, int arg_count) {
VALIDATE_ARGS_2(GROUND_STRING, GROUND_STRING);
std::ofstream file(GET_STRING(args[0]));
if (file.good()) {
file << GET_STRING(args[1]);
} else {
std::cout << "File isn't good for writing in" << std::endl;
return GROUND_BOOL_VAL(false);
}
return GROUND_BOOL_VAL(true);
}
GROUND_LIBRARY_INTERFACE()
GROUND_LIBRARY_INIT()
REGISTER_GROUND_FUNCTION(readFile);
REGISTER_GROUND_FUNCTION(writeFile);
GROUND_LIBRARY_INIT_END()
GROUND_LIBRARY_CLEANUP()
GROUND_LIBRARY_CLEANUP_END()

193
extlibs/ground_lib.h Normal file
View File

@@ -0,0 +1,193 @@
#ifndef GROUND_LIB_H
#define GROUND_LIB_H
#include <cstring>
#include <string>
#include <vector>
#include <iostream>
// Ground types - must match the interpreter
typedef enum {
GROUND_INT,
GROUND_DOUBLE,
GROUND_BOOL,
GROUND_STRING,
GROUND_CHAR
} GroundType;
typedef struct {
GroundType type;
union {
int int_val;
double double_val;
int bool_val;
char* string_val;
char char_val;
} data;
} GroundValue;
// Helper macros for creating GroundValue objects
#define GROUND_INT_VAL(x) ({ GroundValue v; v.type = GROUND_INT; v.data.int_val = (x); v; })
#define GROUND_DOUBLE_VAL(x) ({ GroundValue v; v.type = GROUND_DOUBLE; v.data.double_val = (x); v; })
#define GROUND_BOOL_VAL(x) ({ GroundValue v; v.type = GROUND_BOOL; v.data.bool_val = (x) ? 1 : 0; v; })
#define GROUND_CHAR_VAL(x) ({ GroundValue v; v.type = GROUND_CHAR; v.data.char_val = (x); v; })
// Helper function for creating string values
inline GroundValue ground_string_val(const std::string& str) {
GroundValue v;
v.type = GROUND_STRING;
char* result_str = new char[str.length() + 1];
std::strcpy(result_str, str.c_str());
v.data.string_val = result_str;
return v;
}
// Helper function for creating string values from C strings
inline GroundValue ground_cstring_val(const char* str) {
GroundValue v;
v.type = GROUND_STRING;
if (str) {
size_t len = std::strlen(str);
char* result_str = new char[len + 1];
std::strcpy(result_str, str);
v.data.string_val = result_str;
} else {
v.data.string_val = nullptr;
}
return v;
}
// Helper macros for type checking
#define IS_INT(v) ((v).type == GROUND_INT)
#define IS_DOUBLE(v) ((v).type == GROUND_DOUBLE)
#define IS_BOOL(v) ((v).type == GROUND_BOOL)
#define IS_STRING(v) ((v).type == GROUND_STRING)
#define IS_CHAR(v) ((v).type == GROUND_CHAR)
// Helper macros for extracting values
#define GET_INT(v) ((v).data.int_val)
#define GET_DOUBLE(v) ((v).data.double_val)
#define GET_BOOL(v) ((v).data.bool_val != 0)
#define GET_STRING(v) ((v).data.string_val)
#define GET_CHAR(v) ((v).data.char_val)
// Helper macros for argument validation
#define REQUIRE_ARGS(count) \
if (arg_count < (count)) { \
std::cerr << "Error: Expected at least " << (count) << " arguments, got " << arg_count << std::endl; \
return GROUND_BOOL_VAL(false); \
}
#define REQUIRE_TYPE(arg_index, expected_type) \
if (args[arg_index].type != expected_type) { \
std::cerr << "Error: Argument " << (arg_index + 1) << " must be of type " << #expected_type << std::endl; \
return GROUND_BOOL_VAL(false); \
}
// Convenience macro for checking both arg count and types
#define VALIDATE_ARGS_1(type1) \
REQUIRE_ARGS(1); \
REQUIRE_TYPE(0, type1);
#define VALIDATE_ARGS_2(type1, type2) \
REQUIRE_ARGS(2); \
REQUIRE_TYPE(0, type1); \
REQUIRE_TYPE(1, type2);
#define VALIDATE_ARGS_3(type1, type2, type3) \
REQUIRE_ARGS(3); \
REQUIRE_TYPE(0, type1); \
REQUIRE_TYPE(1, type2); \
REQUIRE_TYPE(2, type3);
// Function registration helpers
class GroundLibrary {
private:
std::vector<std::string> function_names;
std::vector<void*> function_pointers;
public:
void register_function(const std::string& name, void* ptr) {
function_names.push_back(name);
function_pointers.push_back(ptr);
}
const char** get_function_names() {
static std::vector<const char*> names;
names.clear();
for (const auto& name : function_names) {
names.push_back(name.c_str());
}
names.push_back(nullptr); // Null terminator
return names.data();
}
void* get_function(const char* name) {
for (size_t i = 0; i < function_names.size(); i++) {
if (function_names[i] == name) {
return function_pointers[i];
}
}
return nullptr;
}
};
// Global library instance
extern GroundLibrary ground_lib_registry;
// Macro to register functions easily
#define REGISTER_GROUND_FUNCTION(func_name) \
ground_lib_registry.register_function(#func_name, (void*)func_name)
// Macro to define the library interface
#define GROUND_LIBRARY_INTERFACE() \
GroundLibrary ground_lib_registry; \
extern "C" { \
const char** ground_get_functions() { \
return ground_lib_registry.get_function_names(); \
} \
void* ground_get_function(const char* name) { \
return ground_lib_registry.get_function(name); \
} \
}
// Optional initialization macro
#define GROUND_LIBRARY_INIT() \
extern "C" { \
void ground_lib_init() {
#define GROUND_LIBRARY_INIT_END() \
} \
}
// Optional cleanup macro
#define GROUND_LIBRARY_CLEANUP() \
extern "C" { \
void ground_lib_cleanup() {
#define GROUND_LIBRARY_CLEANUP_END() \
} \
}
// Utility function to print GroundValue for debugging
inline void debug_print_ground_value(const GroundValue& v) {
switch (v.type) {
case GROUND_INT:
std::cout << "INT: " << v.data.int_val << std::endl;
break;
case GROUND_DOUBLE:
std::cout << "DOUBLE: " << v.data.double_val << std::endl;
break;
case GROUND_BOOL:
std::cout << "BOOL: " << (v.data.bool_val ? "true" : "false") << std::endl;
break;
case GROUND_STRING:
std::cout << "STRING: " << (v.data.string_val ? v.data.string_val : "(null)") << std::endl;
break;
case GROUND_CHAR:
std::cout << "CHAR: '" << v.data.char_val << "'" << std::endl;
break;
}
}
#endif // GROUND_LIB_H

45
extlibs/request.cpp Normal file
View File

@@ -0,0 +1,45 @@
#include "ground_lib.h"
#include <cpr/cpr.h>
#include <cpr/interface.h>
#include <fstream>
GroundValue simpleRequest(GroundValue* args, int arg_count) {
VALIDATE_ARGS_1(GROUND_STRING);
cpr::Response r = cpr::Get(cpr::Url(GET_STRING(args[0])));
if (!(r.status_code >= 200 && r.status_code < 300)) {
return ground_string_val("Error code " + std::to_string(r.status_code));
}
return ground_string_val(r.text);
}
GroundValue saveContents(GroundValue* args, int arg_count) {
VALIDATE_ARGS_2(GROUND_STRING, GROUND_STRING);
std::ofstream file(GET_STRING(args[1]), std::ios::binary);
if (file.good()) {
cpr::Response r = cpr::Download(file, cpr::Url{GET_STRING(args[0])});
if (r.status_code >= 200 && r.status_code < 300) {
return GROUND_BOOL_VAL(false);
}
} else {
return GROUND_BOOL_VAL(false);
}
return GROUND_BOOL_VAL(true);
}
GROUND_LIBRARY_INTERFACE()
GROUND_LIBRARY_INIT()
REGISTER_GROUND_FUNCTION(simpleRequest);
REGISTER_GROUND_FUNCTION(saveContents);
GROUND_LIBRARY_INIT_END()
GROUND_LIBRARY_CLEANUP()
GROUND_LIBRARY_CLEANUP_END()

File diff suppressed because it is too large Load Diff

12
tests/args.grnd Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/env ground
stdlnout "Program args: "
getlistsize *args &argsSize
set &counter 0
@loopstart
equal $counter $argsSize &bool
if $bool %end
getlistat *args $counter &item
stdlnout $item
add 1 $counter &counter
jump %loopstart
@end

19
tests/functions.grnd Normal file
View File

@@ -0,0 +1,19 @@
fun -bool !jumpy
stdlnout "This is the jumpy function"
set &counter 0
jump %inloop
@jumpback
stdlnout "Yay I jumped!"
@inloop
add 1 $counter &counter
inequal 10 $counter &out
stdout "Condition is"
stdlnout $out
if $out %jumpback
stdlnout "Finished"
return true
endfun
call !jumpy &tmp
stdlnout "I called a function"

3
tests/use/library.grnd Normal file
View File

@@ -0,0 +1,3 @@
fun -string !dingus
return "Hello from the library"
endfun

5
tests/use/use.grnd Normal file
View File

@@ -0,0 +1,5 @@
use "library"
call !dingus &var
stdlnout $var