RC Standard Library

The RC language standard library is organized into modular categories for easy maintenance and extensibility.

Structure

src/stdlib/
├── stdlib.h              # Main registration header
├── stdlib.c              # Registers all stdlib modules
├── string/               # String manipulation functions
│   ├── string_stdlib.h
│   └── string_stdlib.c
├── math/                 # Mathematical functions
│   ├── math_stdlib.h
│   └── math_stdlib.c
├── io/                   # Input/Output operations
│   ├── file_stdlib.h
│   ├── file_stdlib.c     # File I/O functions
│   ├── socket_stdlib.h
│   └── socket_stdlib.c   # Network socket functions
├── async/                # Asynchronous operations
│   ├── async_stdlib.h
│   └── async_stdlib.c    # Async I/O and coroutines
└── constants/            # System constants
    ├── constants_stdlib.h
    └── constants_stdlib.c

Available Functions

String Functions (string/)

  • strlen(str) - Get string length
  • strpos(haystack, needle) - Find substring position
  • substr(str, start, length) - Extract substring
  • upper(str) - Convert to uppercase
  • lower(str) - Convert to lowercase
  • strip(str) - Trim whitespace
  • replace(str, old, new) - Replace substring
  • startswith(str, prefix) - Check if starts with prefix
  • endswith(str, suffix) - Check if ends with suffix

Math Functions (math/)

  • sqrt(x) - Square root
  • pow(base, exp) - Power function
  • sin(x), cos(x), tan(x) - Trigonometric functions
  • abs(x) - Absolute value
  • floor(x), ceil(x) - Rounding functions
  • int_to_double(x) - Convert int to double
  • double_to_int(x) - Convert double to int
  • double_add(a, b), double_sub(a, b), double_mul(a, b), double_div(a, b) - Double arithmetic

File I/O Functions (io/file_stdlib.c)

  • fopen(filename, mode) - Open file
  • fclose(file) - Close file
  • fread(file, addr, size) - Read from file
  • fwrite(file, buf, size) - Write to file
  • fgets(file, max_size) - Read line from file
  • fputs(file, str) - Write string to file
  • feof(file) - Check end of file
  • ftell(file) - Get file position
  • fseek(file, offset, whence) - Seek in file
  • fremove(filename) - Delete file
  • frename(oldname, newname) - Rename file

Socket Functions (io/socket_stdlib.c)

  • socket(domain, type, protocol) - Create socket
  • bind(sockfd, port) - Bind socket to port
  • listen(sockfd, backlog) - Listen for connections
  • accept(sockfd) - Accept connection
  • recv(sockfd, addr, len, flags) - Receive data
  • send(sockfd, buf, len, flags) - Send data
  • close(fd) - Close file descriptor

Async Functions (async/)

  • async_fread(file, addr, size) - Async file read
  • async_fwrite(file, buf, size) - Async file write
  • async_recv(sockfd, addr, len, flags) - Async socket receive
  • async_send(sockfd, buf, len, flags) - Async socket send
  • async_wait(id) - Wait for async operation
  • async_poll(id) - Poll async operation status
  • async_result(id) - Get async operation result
  • await(coroutine_id) - Await coroutine completion
  • gather(coro1, coro2, ...) - Wait for multiple coroutines

Constants (constants/)

  • AF_INET() - IPv4 address family
  • SOCK_STREAM() - TCP socket type
  • SEEK_SET() - Seek from beginning
  • SEEK_CUR() - Seek from current position
  • SEEK_END() - Seek from end

Adding New Functions

1. Add to Existing Category

To add a new function to an existing category (e.g., a new math function):

  1. Open the appropriate category file: src/stdlib/math/math_stdlib.c
  2. Add your function implementation:
long native_my_function(long *args, int argc) {
    if (!args || argc < 1) {
        return 0;
    }
    // Your implementation here
    return result;
}
  1. Register it in the category's registration function:
void register_math_stdlib() {
    // ... existing registrations ...
    register_native_func("my_function", native_my_function);
}
  1. Rebuild: make clean && make

2. Add New Category

To add a new category (e.g., datetime):

  1. Create directory: mkdir -p src/stdlib/datetime
  2. Create header file: src/stdlib/datetime/datetime_stdlib.h
#ifndef DATETIME_STDLIB_H
#define DATETIME_STDLIB_H

void register_datetime_stdlib();

#endif
  1. Create implementation: src/stdlib/datetime/datetime_stdlib.c
#include <time.h>
#include "../../types.h"
#include "datetime_stdlib.h"

extern void register_native_func(char *name, NativeFunc func);

long native_time(long *args, int argc) {
    return (long)time(NULL);
}

void register_datetime_stdlib() {
    register_native_func("time", native_time);
}
  1. Add to src/stdlib/stdlib.c:
#include "datetime/datetime_stdlib.h"

void register_stdlib() {
    // ... existing registrations ...
    register_datetime_stdlib();
}
  1. Add to Makefile SOURCES:
SOURCES = ... \
          $(SRC_DIR)/stdlib/datetime/datetime_stdlib.c
  1. Create build directory in Makefile dirs target:
dirs:
    # ... existing directories ...
    @mkdir -p $(BUILD_DIR)/stdlib/datetime
  1. Rebuild: make clean && make

Function Signature

All native functions must follow this signature:

long native_function_name(long *args, int argc)

Where:

  • args - Array of long arguments passed from RC code
  • argc - Number of arguments
  • Returns a long value

Best Practices

  1. Always validate arguments (check argc and args pointer)
  2. Use appropriate error handling
  3. Document your functions with comments
  4. Test your functions thoroughly
  5. Keep functions focused and single-purpose
  6. Use the string pool for string allocations (str_pool)
  7. Check bounds when accessing memory array
  8. Follow the existing code style

Testing

After making changes:

  1. Build: make clean && make
  2. Run all tests: make test
  3. Run specific category tests (e.g., make run-math-test)

Architecture Notes

  • All stdlib modules are automatically registered when register_stdlib() is called from src/native_functions.c
  • The registration happens during interpreter initialization in src/main.c
  • Native functions are stored in the global native_funcs array
  • Function lookup is performed by name during parsing
..
async
constants
eval
io
math
string
README.md
stdlib.c
stdlib.h