From 87d56bbb135cd16521854d60a1a8b8b2e76deb9c Mon Sep 17 00:00:00 2001 From: Bobby Lucero Date: Thu, 7 Aug 2025 17:49:52 -0400 Subject: [PATCH] Moved to cmake and ninja, updated docs --- .gitignore | 1 + CMakeLists.txt | 145 ++++ Makefile | 55 -- README.md | 117 +-- Reference/BOB_LANGUAGE_REFERENCE.md | 1191 +++++---------------------- Reference/BUILD.md | 248 ++++++ Reference/ROADMAP.md | 401 +++++---- 7 files changed, 835 insertions(+), 1323 deletions(-) create mode 100644 CMakeLists.txt delete mode 100644 Makefile create mode 100644 Reference/BUILD.md diff --git a/.gitignore b/.gitignore index 00911aa..15de9a9 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ build/ .DS_Store +build-ninja diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..c27739f --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,145 @@ +cmake_minimum_required(VERSION 3.20) + +# Project definition +project(bob + VERSION 0.0.3 + DESCRIPTION "Bob Language Interpreter" + LANGUAGES CXX +) + +# Set C++ standard +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +# Build type defaults +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif() + +# Output directories +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) + +# Compiler-specific options +if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + set(BOB_COMPILE_OPTIONS + -Wall -Wextra + -Wno-unused-variable + -Wno-unused-parameter + -Wno-switch + ) + if(CMAKE_BUILD_TYPE STREQUAL "Release") + list(APPEND BOB_COMPILE_OPTIONS -O3 -march=native) + endif() +elseif(MSVC) + set(BOB_COMPILE_OPTIONS + /W4 + /wd4100 # unreferenced formal parameter + /wd4101 # unreferenced local variable + ) + if(CMAKE_BUILD_TYPE STREQUAL "Release") + list(APPEND BOB_COMPILE_OPTIONS /O2) + endif() +endif() + +# Collect source files +file(GLOB_RECURSE BOB_RUNTIME_SOURCES "src/sources/runtime/*.cpp") +file(GLOB_RECURSE BOB_PARSING_SOURCES "src/sources/parsing/*.cpp") +file(GLOB_RECURSE BOB_STDLIB_SOURCES "src/sources/stdlib/*.cpp") +file(GLOB_RECURSE BOB_CLI_SOURCES "src/sources/cli/*.cpp") + +# All source files +set(BOB_ALL_SOURCES + ${BOB_RUNTIME_SOURCES} + ${BOB_PARSING_SOURCES} + ${BOB_STDLIB_SOURCES} + ${BOB_CLI_SOURCES} +) + +# Create the executable +add_executable(bob ${BOB_ALL_SOURCES}) + +# Include directories +target_include_directories(bob PRIVATE + src/headers/runtime + src/headers/parsing + src/headers/stdlib + src/headers/cli + src/headers/common +) + +# Apply compiler options +target_compile_options(bob PRIVATE ${BOB_COMPILE_OPTIONS}) + +# Platform-specific settings +if(WIN32) + # Windows-specific settings + target_compile_definitions(bob PRIVATE _CRT_SECURE_NO_WARNINGS) +elseif(UNIX AND NOT APPLE) + # Linux-specific settings + target_link_libraries(bob PRIVATE pthread) +elseif(APPLE) + # macOS-specific settings + set_target_properties(bob PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_SOURCE_DIR}/Info.plist + ) +endif() + +# Generate compile_commands.json for language servers +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +# Testing support +enable_testing() + +# Add test for the main test suite +add_test( + NAME bob_test_suite + COMMAND bob test_bob_language.bob + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} +) + +# Custom target for running tests with verbose output +add_custom_target(test_verbose + COMMAND ${CMAKE_CTEST_COMMAND} --verbose + DEPENDS bob + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} +) + +# Install rules +install(TARGETS bob + RUNTIME DESTINATION bin + COMPONENT Runtime +) + +# Install test files (optional) +install(FILES test_bob_language.bob + DESTINATION share/bob/tests + COMPONENT Tests +) + +# CPack configuration for packaging +set(CPACK_PACKAGE_NAME "Bob Language") +set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION}) +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Bob Language Interpreter") +set(CPACK_PACKAGE_VENDOR "Bob Language Team") +set(CPACK_PACKAGE_CONTACT "your-email@example.com") + +if(WIN32) + set(CPACK_GENERATOR "ZIP;NSIS") +elseif(APPLE) + set(CPACK_GENERATOR "TGZ;DragNDrop") +else() + set(CPACK_GENERATOR "TGZ;DEB;RPM") +endif() + +include(CPack) + +# Print configuration summary +message(STATUS "Bob Language Build Configuration:") +message(STATUS " Build Type: ${CMAKE_BUILD_TYPE}") +message(STATUS " Compiler: ${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION}") +message(STATUS " C++ Standard: ${CMAKE_CXX_STANDARD}") +message(STATUS " Install Prefix: ${CMAKE_INSTALL_PREFIX}") +message(STATUS " Source Files Found: ${BOB_ALL_SOURCES}") \ No newline at end of file diff --git a/Makefile b/Makefile deleted file mode 100644 index 7fad88e..0000000 --- a/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -# Makefile - Bob language interpreter - -# Compiler -CC = g++ - -# Compiler flags -CFLAGS = -Wall -Wextra -std=c++17 -Wno-unused-variable -Wno-unused-parameter -Wno-switch -O3 -march=native - -# Source layout: -# src/ -# ├── headers/ - All header files (public interface) -# │ ├── runtime/ - Runtime execution headers -# │ ├── parsing/ - Front-end processing headers -# │ ├── stdlib/ - Standard library headers -# │ ├── cli/ - CLI headers -# │ └── common/ - Shared utilities (helperFunctions) -# └── sources/ - All source files (implementation) -# ├── runtime/ - Interpreter, Evaluator, Executor, Environment, Value, TypeWrapper -# ├── parsing/ - Lexer, Parser, ErrorReporter, Expression AST -# ├── stdlib/ - Built-in functions (BobStdLib) -# └── cli/ - Command-line interface (main, bob) - -SRC_ROOT = ./src -BUILD_DIR = ./build - -# Find all .cpp files under src/sources (recursively) -CPP_FILES := $(shell find $(SRC_ROOT)/sources -type f -name '*.cpp') - -# Map every source file to its corresponding object file inside build/ -# Strip src/sources/ prefix and add build/ prefix -OBJ_FILES := $(patsubst $(SRC_ROOT)/sources/%.cpp,$(BUILD_DIR)/%.o,$(CPP_FILES)) - -# Make sure every object directory exists ahead of time -$(shell mkdir -p $(dir $(OBJ_FILES))) - -# Default goal -all: build - -# Pattern rule – compile each .cpp from sources/ into a mirrored .o inside build/ -$(BUILD_DIR)/%.o: $(SRC_ROOT)/sources/%.cpp - @mkdir -p $(dir $@) - $(CC) $(CFLAGS) -I$(SRC_ROOT)/headers/runtime -I$(SRC_ROOT)/headers/parsing -I$(SRC_ROOT)/headers/stdlib -I$(SRC_ROOT)/headers/cli -I$(SRC_ROOT)/headers/common -c $< -o $@ - -# Link all objects into the final executable -$(BUILD_DIR)/bob: $(OBJ_FILES) - $(CC) $(CFLAGS) $^ -o $@ - -# Convenience targets -run: - ./$(BUILD_DIR)/bob - -build: clean $(BUILD_DIR)/bob - -clean: - rm -rf $(BUILD_DIR)/* diff --git a/README.md b/README.md index 13bba7a..b820289 100644 --- a/README.md +++ b/README.md @@ -1,98 +1,37 @@ -# Bob - -A modern programming language focused on safety and clarity. - -## Design Philosophy - -Bob prioritizes safety and functional programming while keeping things practical. - -## Assignment System - -Bob uses two types of assignments to prevent bugs while keeping useful functionality: - -### Assignment Statements -```go -var x = 5; -x = 10; // Regular assignment -y += 5; // Compound assignment +``` +██████╗ ██████╗ ██████╗ +██╔══██╗██╔═══██╗██╔══██╗ +██████╔╝██║ ██║██████╔╝ +██╔══██╗██║ ██║██╔══██╗ +██████╔╝╚██████╔╝██████╔╝ +╚═════╝ ╚═════╝ ╚═════╝ ``` -### Assignment Expressions (For Loops Only) -```go -for (var i = 0; i < 5; i = i + 1) { } // Assignment in for loop -for (j = 0; j < 5; j += 1) { } // Assignment in for loop -``` - -### Why This Design? - -**Prevents Common Bugs:** -```go -// This would be a bug in many languages: -if (x = 10) { } // Parse error in Bob - prevents accidental assignment - -// Bob forces you to write: -x = 10; -if (x == 10) { } // Clear comparison -``` - -**Keeps Expressions Pure:** -```go -// Prevents side effects in expressions: -var result = (x = 10) + (y = 20); // Parse error - -// Forces clean code: -x = 10; -y = 20; -var result = x + y; // Pure expression -``` - -**Supports Functional Programming:** -```go -// Prevents confusing patterns: -var value = condition ? (x = 10) : (x = 20); // Parse error - -// Encourages clean patterns: -x = condition ? 10 : 20; // Clear assignment -``` - -**Keeps For Loops Practical:** -```go -// For loops work naturally: -for (var i = 0; i < 10; i = i + 1) { } // Assignment expressions allowed -for (j = 0; j < 10; j += 1) { } // Assignment expressions allowed -``` - -### Benefits - -1. **Prevents Common Bugs**: No accidental assignments in conditionals -2. **Expression Purity**: Expressions have no side effects -3. **Clear Semantics**: Assignments are clearly statements -4. **Functional Programming**: Encourages pure function patterns -5. **Practical For Loops**: Maintains useful for loop syntax -6. **Easier Debugging**: Clear separation of assignment and expression logic - -## Features - -- **Type Safety**: Dynamic typing with runtime type checking -- **Functional Programming**: First-class functions, closures, recursion -- **Memory Management**: Automatic memory management -- **Error Handling**: Comprehensive error reporting -- **Standard Library**: Built-in functions for common operations -- **Tail Call Optimization**: Efficient recursive function calls +A modern programming language with all the features/sytax I prefer ## Documentation -See [BOB_LANGUAGE_REFERENCE.md](BOB_LANGUAGE_REFERENCE.md) for complete language documentation. +- **[Language Reference](Reference/BOB_LANGUAGE_REFERENCE.md)** - Language syntax and features +- **[Build Guide](Reference/BUILD.md)** - How to build Bob +- **[Roadmap](Reference/ROADMAP.md)** - What's done and what might come next -## Building +## Features + +- **Core Types**: Numbers, strings, booleans, arrays, dictionaries, functions +- **Advanced Functions**: First-class functions, closures, anonymous functions, tail call optimization +- **Control Flow**: If/else statements, while/do-while/for loops, break/continue +- **Operators**: Arithmetic, logical, bitwise, comparison, compound assignment (+=, -=, etc.) +- **Built-in Functions**: print, input, assert, len, push, pop, keys, values, type conversion (toString, toNumber, toInt) +- **Other Stuff**: String interpolation, escape sequences, file I/O, eval, time/sleep, random +- **Memory**: Automatic cleanup, no manual memory management + +## Quick Start ```bash -make clean && make -./build/bob your_file.bob -``` +# Build +cmake -G Ninja -B build -DCMAKE_BUILD_TYPE=Release +ninja -C build -## Testing - -```bash -./build/bob test_bob_language.bob -``` +# Run +./build/bin/bob your_file.bob +``` \ No newline at end of file diff --git a/Reference/BOB_LANGUAGE_REFERENCE.md b/Reference/BOB_LANGUAGE_REFERENCE.md index e7dc874..83125e1 100644 --- a/Reference/BOB_LANGUAGE_REFERENCE.md +++ b/Reference/BOB_LANGUAGE_REFERENCE.md @@ -1,1101 +1,350 @@ # Bob Language Reference -## Overview +## Quick Start -Bob is a dynamically typed programming language focused on safety and clarity. It features automatic type conversion, closures, and a clean syntax inspired by modern programming languages. - -## Table of Contents - -1. [Getting Started](#getting-started) -2. [Basic Syntax](#basic-syntax) -3. [Data Types](#data-types) -4. [Variables](#variables) -5. [Operators](#operators) -6. [Control Flow](#control-flow) -7. [Functions](#functions) -8. [Standard Library](#standard-library) -9. [Error Handling](#error-handling) -10. [Examples](#examples) - -## Getting Started - -### Running Bob Code ```bash -# Compile the interpreter -make +# Build Bob +cmake -G Ninja -B build -DCMAKE_BUILD_TYPE=Release +ninja -C build -# Run a Bob file -./build/bob your_file.bob +# Run a file +./build/bin/bob script.bob -# Run the comprehensive test suite -./build/bob test_bob_language.bob -``` - -### File Extension -- **`.bob`**: Standard file extension for Bob source code - -### Interactive Mode -- **Not implemented**: No REPL (Read-Eval-Print Loop) yet -- **File-based**: All code must be in `.bob` files - -## Basic Syntax - -### Statements -- **Semicolons**: Required at end of statements -- **Parentheses**: Required for function calls -- **Curly braces**: Required for function bodies -- **Case sensitive**: `var` and `Var` are different - -### Comments -```go -// Single line comment -/* Multi-line comment */ +# Interactive mode +./build/bin/bob ``` ## Data Types ### Numbers -- **Integers**: `42`, `-10`, `0` -- **Floats**: `3.14`, `2.718`, `-1.5` -- **Automatic conversion**: Numbers are stored as doubles internally +```go +var integer = 42; +var float = 3.14; +var negative = -10; +``` ### Strings -- **Literal strings**: `"Hello, World!"` -- **Empty strings**: `""` -- **Escape sequences**: `\n` (newline), `\t` (tab), `\"` (quote), `\\` (backslash) -- **String indexing**: Access individual characters with `str[index]` -- **Immutable**: Strings cannot be modified after creation +```go +var text = "Hello, World!"; +var empty = ""; +var escaped = "Line 1\nLine 2\t\"quoted\""; +var concat = "Hello" + " " + "World"; +var repeat = "hi" * 3; // "hihihi" +``` ### Booleans -- **True**: `true` -- **False**: `false` +```go +var yes = true; +var no = false; +``` ### None -- **Null value**: `none` (represents absence of value) +```go +var nothing = none; +``` ### Arrays -- **Array literals**: `[1, 2, 3, 4, 5]` -- **Empty arrays**: `[]` -- **Mixed types**: `[1, "hello", true, 3.14]` -- **Nested arrays**: `[[1, 2], [3, 4]]` - -#### String Indexing ```go -var str = "Hello, Bob!"; +var numbers = [1, 2, 3]; +var mixed = [42, "hello", true]; +var nested = [[1, 2], [3, 4]]; -// Basic character access -print(str[0]); // H -print(str[1]); // e -print(str[7]); // B -print(str[10]); // ! - -// Get string length -var length = len(str); -print(length); // 11 - -// Access last character -var last = str[len(str) - 1]; -print(last); // ! - -// String reversal -var reversed = ""; -for (var i = len(str) - 1; i >= 0; i = i - 1) { - reversed = reversed + str[i]; -} -print(reversed); // !boB ,olleH - -// Character counting -var text = "hello world"; -var count = 0; -for (var i = 0; i < len(text); i = i + 1) { - if (text[i] == "l") { - count = count + 1; - } -} -print(count); // 3 - -// String search -var haystack = "Hello, Bob!"; -var needle = "Bob"; -var found = false; -for (var i = 0; i <= len(haystack) - len(needle); i = i + 1) { - var match = true; - for (var j = 0; j < len(needle); j = j + 1) { - if (haystack[i + j] != needle[j]) { - match = false; - break; - } - } - if (match) { - found = true; - break; - } -} -print(found); // true - -// String parsing (CSV-like) -var csvLine = "Alice,30,Engineer"; -var fields = []; -var currentField = ""; -for (var i = 0; i < len(csvLine); i = i + 1) { - var char = csvLine[i]; - if (char == ",") { - push(fields, currentField); - currentField = ""; - } else { - currentField = currentField + char; - } -} -push(fields, currentField); -print(fields[0]); // Alice -print(fields[1]); // 30 -print(fields[2]); // Engineer +// Access and modify +print(numbers[0]); // 1 +numbers[1] = 99; ``` -**String Indexing Rules:** -- **Zero-based indexing**: First character is at index 0 -- **Bounds checking**: Index must be >= 0 and < string length -- **Number indices only**: Index must be a number (float indices auto-truncate) -- **Returns single character**: `str[index]` returns a single-character string -- **Immutable**: Cannot assign to string indices (strings are immutable) -- **Error handling**: Out-of-bounds access throws runtime error - ### Dictionaries -- **Dictionary literals**: `{"key": "value", "number": 42}` -- **Empty dictionaries**: `{}` -- **String keys only**: Keys must be string literals -- **Any value types**: Values can be any type including nested structures -- **Nested dictionaries**: `{"user": {"name": "Bob", "age": 30}}` - -#### Array Access ```go -var arr = [10, 20, 30, 40, 50]; +var person = {"name": "Alice", "age": 30}; -// Basic indexing -print(arr[0]); // 10 -print(arr[2]); // 30 - -// Float indices auto-truncate (like JavaScript/Lua) -print(arr[3.14]); // 40 (truncated to arr[3]) -print(arr[2.99]); // 30 (truncated to arr[2]) - -// Assignment -arr[1] = 25; -print(arr[1]); // 25 - -// Increment/decrement on array elements -arr[0]++; -print(arr[0]); // 11 -++arr[1]; -print(arr[1]); // 26 -``` - -#### Array Built-in Functions -```go -var arr = [1, 2, 3]; - -// Get array length -print(len(arr)); // 3 - -// Add element to end -push(arr, 4); -print(arr); // [1, 2, 3, 4] - -// Remove and return last element -var last = pop(arr); -print(last); // 4 -print(arr); // [1, 2, 3] -``` - -#### Dictionary Access -```go -var person = {"name": "Alice", "age": 30, "city": "New York"}; - -// Basic access +// Access and modify print(person["name"]); // Alice -print(person["age"]); // 30 - -// Missing keys return none -print(person["email"]); // none - -// Assignment -person["email"] = "alice@example.com"; -person["age"] = 31; - -// Nested access -var gameState = { - "player": {"health": 100, "level": 5}, - "world": {"name": "Bobland", "difficulty": "hard"} -}; -print(gameState["player"]["health"]); // 100 -``` - -#### Dictionary Built-in Functions -```go -var person = {"name": "Bob", "age": 25, "city": "San Francisco"}; - -// Get all keys -var keys = keys(person); -print(keys); // [name, age, city] - -// Get all values -var values = values(person); -print(values); // [Bob, 25, San Francisco] - -// Check if key exists -print(has(person, "name")); // true -print(has(person, "email")); // false +person["city"] = "NYC"; ``` ## Variables -### Declaration ```go -var name = "Bob"; -var age = 25; -var isActive = true; -``` - -### Assignment -```go -var x = 10; -x = 20; // Reassignment -``` - -### Scoping -- **Global scope**: Variables declared at top level -- **Local scope**: Variables declared inside functions -- **Shadowing**: Local variables can shadow global variables -- **No `global` keyword**: Unlike Python, Bob doesn't require explicit global declaration - -```go -var globalVar = 100; - -func testScope() { - var localVar = 50; // Local variable - return localVar + globalVar; // Can access global -} -``` - -### Assignment System - -Bob uses two assignment systems for safety and practicality: - -#### Assignment Statements -- **Purpose**: Main way to assign values -- **Syntax**: `variable = value;` (with semicolon) -- **Context**: Standalone statements - -```go -// Assignment statements (most common) -var x = 5; -x = 10; // Regular assignment +var x = 10; // Declaration +x = 20; // Reassignment y += 5; // Compound assignment -z *= 2; // Compound assignment -``` - -#### Assignment Expressions (For Loops Only) -- **Purpose**: For loop clauses only -- **Syntax**: `variable = value` (without semicolon) -- **Context**: For loop initializers and increment clauses - -```go -// Assignment expressions (for loops only) -for (var i = 0; i < 5; i = i + 1) { } // Assignment in increment -for (j = 0; j < 5; j += 1) { } // Assignment in initializer and increment -``` - -#### Why This Design? - -**Prevents Common Bugs:** -```go -// This would be a bug in many languages: -if (x = 10) { } // Parse error - assignment in conditional - -// Bob forces you to write: -x = 10; -if (x == 10) { } // Clear comparison -``` - -**Keeps Expressions Pure:** -```go -// Prevents side effects in expressions: -var result = (x = 10) + (y = 20); // Parse error - -// Forces clean code: -x = 10; -y = 20; -var result = x + y; // Pure expression -``` - -**What's Blocked:** -```go -// These all cause parse errors: -var result = x = 10; // AssignExpr not allowed in expressions -var result = true ? (x = 10) : 0; // AssignExpr not allowed in ternary -var result = func(x = 10); // AssignExpr not allowed in function calls -var result = (x = 10) + 5; // AssignExpr not allowed in arithmetic +z++; // Increment (for array elements) ``` ## Operators -### Arithmetic Operators -- **Addition**: `+` -- **Subtraction**: `-` -- **Multiplication**: `*` -- **Division**: `/` -- **Modulo**: `%` - -### Compound Assignment Operators -- **Add and assign**: `+=` -- **Subtract and assign**: `-=` -- **Multiply and assign**: `*=` -- **Divide and assign**: `/=` -- **Modulo and assign**: `%=` - +### Arithmetic ```go -var x = 10; -x += 5; // x = 15 -x -= 3; // x = 12 -x *= 2; // x = 24 -x /= 4; // x = 6 -x %= 4; // x = 2 ++ - * / % // Basic math +-x // Unary minus ``` -### Increment and Decrement Operators -- **Prefix increment**: `++x` -- **Postfix increment**: `x++` -- **Prefix decrement**: `--x` -- **Postfix decrement**: `x--` - +### Comparison ```go -var x = 5; -print(++x); // 6 (increments first, then prints) -print(x++); // 6 (prints first, then increments) -print(x); // 7 - -// Works with array elements -var arr = [1, 2, 3]; -arr[0]++; -print(arr[0]); // 2 -++arr[1]; -print(arr[1]); // 3 +== != < > <= >= // Comparisons ``` -### Comparison Operators -- **Equal**: `==` -- **Not equal**: `!=` -- **Greater than**: `>` -- **Less than**: `<` -- **Greater than or equal**: `>=` -- **Less than or equal**: `<=` - -#### Cross-Type Comparisons -Bob supports cross-type comparisons with intuitive behavior: - +### Logical ```go -// Equality operators work with any types -print(none == "hello"); // false (different types) -print(42 == "42"); // false (different types) -print(true == true); // true (same type and value) - -// Comparison operators only work with numbers -print(5 > 3); // true -print(5 > "3"); // Error: > not supported between number and string -print(none > 5); // Error: > not supported between none and number +&& || ! // AND, OR, NOT (short-circuit) ``` -### Logical Operators -- **And**: `&&` -- **Or**: `||` -- **Not**: `!` - -### Conditional (Ternary) Operator +### Bitwise ```go -// Basic ternary operator -var result = condition ? valueIfTrue : valueIfFalse; - -// Examples -var max = x > y ? x : y; -var status = age >= 18 ? "adult" : "minor"; -var message = x > 0 ? "positive" : "non-positive"; - -// Ternary with expressions -var result = x + y > 10 ? x * y : x + y; - -// Ternary with function calls -var value = condition ? getValue() : getOtherValue(); - -// Nested ternary expressions -var result = x == 5 ? (y == 10 ? "both true" : "x true") : "x false"; +& | ^ << >> ~ // Bitwise operations ``` -**Precedence**: The ternary operator has lower precedence than logical operators (`&&`, `||`) but higher than assignment operators. - -### String Operators - -#### Concatenation -Bob supports bidirectional string + number concatenation with automatic type conversion: - +### Compound Assignment ```go -// String + Number -"Hello " + 42; // → "Hello 42" -"Pi: " + 3.14; // → "Pi: 3.14" - -// Number + String -42 + " items"; // → "42 items" -3.14 + " is pi"; // → "3.14 is pi" ++= -= *= /= %= // Arithmetic compound +&= |= ^= <<= >>= // Bitwise compound ``` -#### String Multiplication +### Ternary ```go -"hello" * 3; // → "hellohellohello" -3 * "hello"; // → "hellohellohello" -``` - -**Note**: String multiplication requires whole numbers. - -### Number Formatting -Bob automatically formats numbers to show only significant digits: - -```go -"Count: " + 2.0; // → "Count: 2" (no trailing zeros) -"Pi: " + 3.14; // → "Pi: 3.14" (exact precision) -"Integer: " + 42; // → "Integer: 42" (no decimal) +var result = condition ? "yes" : "no"; ``` ## Control Flow ### If Statements ```go -// Basic if statement -if (x > 10) { - print("x is greater than 10"); -} - -// If-else statement -if (x > 10) { - print("x is greater than 10"); +if (x > 0) { + print("positive"); +} else if (x < 0) { + print("negative"); } else { - print("x is 10 or less"); -} - -// If-else if-else chain -if (x > 10) { - print("x is greater than 10"); -} else if (x > 5) { - print("x is greater than 5"); -} else { - print("x is 5 or less"); + print("zero"); } ``` ### While Loops ```go -// Basic while loop -var i = 0; -while (i < 5) { +while (i < 10) { print(i); i = i + 1; } - -// While loop with break (using return) -func countToThree() { - var i = 0; - while (true) { - i = i + 1; - if (i > 3) { - return i; - } - } -} -``` - -### For Loops -```go -// Basic for loop -for (var i = 0; i < 5; i = i + 1) { - print(i); -} - -// For loop with no initializer -var j = 0; -for (; j < 3; j = j + 1) { - // Empty body -} - -// For loop with no condition (infinite loop with break) -for (var k = 0; ; k = k + 1) { - if (k >= 2) { - break; // or return - } -} - -// For loop with no increment -for (var n = 0; n < 3; ) { - n = n + 1; -} ``` ### Do-While Loops ```go -// Basic do-while loop -var i = 0; do { print(i); i = i + 1; -} while (i < 5); - -// Do-while with break -var j = 0; -do { - j = j + 1; - if (j == 3) { - break; - } -} while (j < 10); - -// Do-while with continue -var k = 0; -var sum = 0; -do { - k = k + 1; - if (k == 2) { - continue; - } - sum = sum + k; -} while (k < 5); +} while (i < 10); ``` -### Loop Features -- **Nested loops**: While, for, and do-while loops can be nested -- **Complex conditions**: Loops support any boolean expression -- **Function calls**: Loop conditions and bodies can contain function calls -- **Return statements**: Loops can be exited using return statements -- **Break and continue**: All loop types support break and continue statements -- **Variable scoping**: Variables declared in for loop initializers are scoped to the loop -- **Do-while behavior**: Do-while loops always execute the body at least once before checking the condition +### For Loops +```go +for (var i = 0; i < 10; i = i + 1) { + print(i); +} + +// Break and continue work in all loops +for (var i = 0; i < 10; i = i + 1) { + if (i == 5) break; + if (i % 2 == 0) continue; + print(i); +} +``` ## Functions -### Function Declaration +### Basic Functions ```go -func add(a, b) { - return a + b; +func greet(name) { + return "Hello, " + name; } + +var message = greet("Alice"); ``` -### Function Call +### Anonymous Functions ```go -var result = add(2, 3); // result = 5 +var square = func(x) { return x * x; }; +var result = square(5); ``` -### Parameters -- **Any number of parameters** supported -- **No default parameters** (not implemented) -- **No keyword arguments** (not implemented) - -### Return Values -- **Explicit return**: `return value;` -- **Implicit return**: Functions return `none` if no return statement -- **Early return**: Functions can return from anywhere - ### Closures -Bob supports lexical closures with variable capture: - ```go -var outerVar = "Outer"; - -func makeGreeter(greeting) { - return greeting + " " + outerVar; +func makeCounter() { + var count = 0; + return func() { + count = count + 1; + return count; + }; } -var greeter = makeGreeter("Hello"); -// greeter captures outerVar from its lexical scope +var counter = makeCounter(); +print(counter()); // 1 +print(counter()); // 2 ``` -### Nested Functions +### First-Class Functions ```go -func outer() { - func inner() { - return 42; - } - return inner(); +func apply(fn, x) { + return fn(x); +} + +var result = apply(square, 10); // 100 +``` + +## Built-in Functions + +### I/O +```go +print("Hello"); // Output with newline +printRaw("No newline"); // Output without newline +var input = input("Enter something: "); +``` + +### Type Conversion +```go +toString(42); // "42" +toNumber("3.14"); // 3.14 +toInt(3.9); // 3 +toBoolean(1); // true +type(42); // "number" +``` + +### Arrays & Strings +```go +len([1, 2, 3]); // 3 +len("hello"); // 5 +push(array, value); // Add to end +pop(array); // Remove from end +``` + +### Dictionaries +```go +keys(dict); // Array of keys +values(dict); // Array of values +has(dict, "key"); // Check if key exists +``` + +### Utility +```go +assert(condition, "message"); // Testing +time(); // Current time in microseconds +sleep(1.5); // Sleep for 1.5 seconds +random(); // Random number 0-1 +eval("1 + 2"); // Evaluate string as code +exit(0); // Exit program +``` + +### File I/O +```go +var content = readFile("data.txt"); +writeFile("output.txt", "Hello"); +var lines = readLines("config.txt"); +var exists = fileExists("test.txt"); +``` + +## Advanced Features + +### String Interpolation +```go +var name = "Alice"; +var age = 30; +var message = "Name: " + name + ", Age: " + age; +``` + +### Tail Call Optimization +```go +func factorial(n, acc) { + if (n <= 1) return acc; + return factorial(n - 1, n * acc); // Tail call optimized } ``` -## Standard Library +### Assignment System +Bob has a unique assignment system that prevents common bugs: -### Print Function ```go -print("Hello, World!"); -print(42); -print(true); +// Assignment statements (everywhere) +var x = 5; +x = 10; +y += 5; + +// Assignment expressions (only in for loops) +for (var i = 0; i < 5; i = i + 1) { } // OK +for (j = 0; j < 5; j += 1) { } // OK + +// This prevents bugs like: +if (x = 10) { } // PARSE ERROR - prevents accidental assignment ``` -**Usage**: `print(expression)` -- Prints the result of any expression -- Automatically converts values to strings -- Adds newline after output +## Memory Management -### Assert Function -```go -assert(condition, "optional message"); -``` - -**Usage**: -- `assert(true)` - passes silently -- `assert(false)` - throws error and stops execution -- `assert(condition, "message")` - includes custom error message - -**Behavior**: -- Terminates program execution on failure -- No exception handling mechanism (yet) -- Useful for testing and validation - -### Type Function -```go -type(value); -``` - -**Usage**: -- Returns the type of a value as a string -- Returns: `"number"`, `"string"`, `"boolean"`, `"none"`, `"array"`, `"function"` - -**Examples**: -```go -print(type(42)); // "number" -print(type("hello")); // "string" -print(type(true)); // "boolean" -print(type(none)); // "none" -print(type([1, 2, 3])); // "array" -print(type(func() {})); // "function" -``` - -### ToString Function -```go -toString(value); -``` - -**Usage**: -- Converts any value to a string -- Works with all data types - -**Examples**: -```go -print(toString(42)); // "42" -print(toString(3.14)); // "3.14" -print(toString(true)); // "true" -print(toString([1, 2, 3])); // "[1, 2, 3]" -``` - -### ToNumber Function -```go -toNumber(value); -``` - -**Usage**: -- Converts a value to a number -- Returns 0 for non-numeric strings -- Returns 0 for boolean false, 1 for boolean true - -**Examples**: -```go -print(toNumber("42")); // 42 -print(toNumber("3.14")); // 3.14 -print(toNumber("hello")); // 0 -print(toNumber(true)); // 1 -print(toNumber(false)); // 0 -``` - -### ToInt Function -```go -toInt(value); -``` - -**Usage**: -- Converts a number to an integer (truncates decimal part) -- Throws error for non-numeric values -- Same result as using bitwise OR with 0 (`value | 0`) - -**Examples**: -```go -print(toInt(3.7)); // 3 -print(toInt(3.2)); // 3 -print(toInt(-3.7)); // -3 -print(toInt(3.0)); // 3 -``` - -### Input Function -```go -input(); -input("prompt"); -``` - -**Usage**: -- Reads a line from standard input -- Optional prompt string -- Returns the input as a string - -**Examples**: -```go -var name = input("Enter your name: "); -print("Hello, " + name + "!"); -``` - -### Time Function -```go -time(); -``` - -**Usage**: -- Returns current Unix timestamp (seconds since epoch) -- Useful for timing and random seed generation - -**Examples**: -```go -var start = time(); -// ... do some work ... -var end = time(); -print("Elapsed: " + (end - start) + " seconds"); -``` - -### Sleep Function -```go -sleep(seconds); -``` - -**Usage**: -- Pauses execution for specified number of seconds -- Useful for animations and timing - -**Examples**: -```go -print("Starting..."); -sleep(1); -print("One second later..."); -``` - -### PrintRaw Function -```go -printRaw("text"); -``` - -**Usage**: -- Prints text without adding a newline -- Supports ANSI escape codes for colors and cursor control -- Useful for animations and formatted output - -**Examples**: -```go -// Simple output -printRaw("Hello"); -printRaw(" World"); // Prints: Hello World - -// ANSI colors -printRaw("\e[31mRed text\e[0m"); // Red text -printRaw("\e[32mGreen text\e[0m"); // Green text - -// Cursor positioning -printRaw("\e[2J"); // Clear screen -printRaw("\e[H"); // Move cursor to top-left -``` - -### Random Function -```go -random(); -``` - -**Usage**: -- Returns a random number between 0.0 and 1.0 -- Uses current time as seed - -**Examples**: -```go -var randomValue = random(); -print(randomValue); // 0.0 to 1.0 - -// Generate random integer 1-10 -var randomInt = toInt(random() * 10) + 1; -print(randomInt); -``` - -### Eval Function -```go -eval("code"); -``` - -**Usage**: -- Executes Bob code as a string -- Returns the result of the last expression -- Runs in the current scope (can access variables) - -**Examples**: -```go -var x = 10; -var result = eval("x + 5"); -print(result); // 15 - -var code = "2 + 3 * 4"; -var result = eval(code); -print(result); // 14 -``` - -### Array Functions - -#### Len Function -```go -len(array); -``` - -**Usage**: -- Returns the length of an array -- Also works with strings - -**Examples**: -```go -var arr = [1, 2, 3, 4, 5]; -print(len(arr)); // 5 - -var str = "hello"; -print(len(str)); // 5 -``` - -#### Push Function -```go -push(array, value); -``` - -**Usage**: -- Adds a value to the end of an array -- Modifies the array in place -- Returns none - -**Examples**: -```go -var arr = [1, 2, 3]; -push(arr, 4); -print(arr); // [1, 2, 3, 4] -``` - -#### Pop Function -```go -pop(array); -``` - -**Usage**: -- Removes and returns the last element of an array -- Throws error if array is empty -- Modifies the array in place - -**Examples**: -```go -var arr = [1, 2, 3, 4]; -var last = pop(arr); -print(last); // 4 -print(arr); // [1, 2, 3] -``` - -### Dictionary Functions - -#### Keys Function -```go -keys(dictionary); -``` - -**Usage**: -- Returns an array of all keys in a dictionary -- Keys are returned as strings - -**Examples**: -```go -var person = {"name": "Bob", "age": 25, "city": "SF"}; -var keys = keys(person); -print(keys); // [name, age, city] -``` - -#### Values Function -```go -values(dictionary); -``` - -**Usage**: -- Returns an array of all values in a dictionary -- Values maintain their original types - -**Examples**: -```go -var person = {"name": "Bob", "age": 25, "city": "SF"}; -var values = values(person); -print(values); // [Bob, 25, SF] -``` - -#### Has Function -```go -has(dictionary, key); -``` - -**Usage**: -- Returns true if the key exists in the dictionary -- Returns false if the key is missing -- Key must be a string - -**Examples**: -```go -var person = {"name": "Bob", "age": 25}; -print(has(person, "name")); // true -print(has(person, "email")); // false -``` +Bob automatically manages memory - no manual allocation or deallocation needed. Objects are cleaned up when no longer referenced. ## Error Handling -### Current Error Types -- **Division by zero**: `DivisionByZeroError` -- **Type errors**: `Operands must be of same type` -- **String multiplication**: `String multiplier must be whole number` -- **Assertion failures**: `Assertion failed: condition is false` -- **Function call errors**: `Can only call functions, got [type]` -- **Argument count errors**: `Expected X arguments but got Y` +Bob provides helpful error messages with context: -### Error Behavior -- **No try-catch**: Exception handling not implemented -- **Program termination**: Errors stop execution immediately -- **Error messages**: Descriptive error messages printed to console - -### Common Error Scenarios ```go -// Division by zero -10 / 0; // Error: DivisionByZeroError +// Runtime errors show line numbers and context +var x = undefined_variable; // Error: Undefined variable 'undefined_variable' at line 2 -// Type mismatch -"hello" - "world"; // Error: Cannot use '-' on two strings +// Type errors are caught +var result = "hello" / 5; // Error: Cannot divide string by number +``` -// Invalid string multiplication -"hello" * 3.5; // Error: String multiplier must be whole number +## Interactive Mode (REPL) -// Undefined variable -undefinedVar; // Error: Undefined variable +Bob includes an interactive mode for experimenting: -// Function call errors -var notAFunction = 42; -notAFunction(); // Error: Can only call functions, got number - -// Argument count errors -func test(a, b) { return a + b; } -test(1); // Error: Expected 2 arguments but got 1 +```bash +$ ./build/bin/bob +Bob Interactive Mode +> var x = 42; +> print(x * 2); +84 +> exit(); ``` ## Examples -### Basic Calculator +### Fibonacci with Tail Call Optimization ```go -func add(a, b) { - return a + b; +func fib(n, a, b) { + if (n == 0) return a; + if (n == 1) return b; + return fib(n - 1, b, a + b); } -func multiply(a, b) { - return a * b; -} - -var result = add(5, multiply(3, 4)); -print("Result: " + result); // Result: 17 +print(fib(40, 0, 1)); // Fast even for large numbers ``` -### String Processing +### Working with Data Structures ```go -func greet(name) { - return "Hello, " + name + "!"; -} +var people = [ + {"name": "Alice", "age": 30}, + {"name": "Bob", "age": 25} +]; -func repeat(str, count) { - return str * count; -} - -var greeting = greet("Bob"); -var repeated = repeat("Ha", 3); -print(greeting + " " + repeated); // Hello, Bob! HaHaHa -``` - -### Variable Scoping Example -```go -var globalCounter = 0; - -func increment() { - var localCounter = 1; - globalCounter = globalCounter + localCounter; - return globalCounter; -} - -print("Before: " + globalCounter); // Before: 0 -increment(); -print("After: " + globalCounter); // After: 1 -``` - -### Loop Examples -```go -// Count from 1 to 5 -for (var i = 1; i <= 5; i = i + 1) { - print("Count: " + i); -} - -// Sum numbers from 1 to 10 -var sum = 0; -for (var j = 1; j <= 10; j = j + 1) { - sum = sum + j; -} -print("Sum: " + sum); - -// Find first even number -var k = 1; -while (k % 2 != 0) { - k = k + 1; -} -print("First even: " + k); -``` - -## Implementation Details - -### Assignment System: Statements vs Expressions - -Bob uses a dual assignment system to prevent common programming errors: - -**Assignment Statements** (general use): -```go -var x = 10; -x = 20; // This is a statement, not an expression -``` - -**Assignment Expressions** (for loops only): -```go -for (var i = 0; i < 10; i = i + 1) { // Assignment in increment clause - print(i); +for (var i = 0; i < len(people); i = i + 1) { + var person = people[i]; + print(person["name"] + " is " + person["age"] + " years old"); } ``` -**Why This Design?** -- **Prevents `if (x = 10)` bugs**: Assignment statements can't be used in conditions -- **Maintains loop functionality**: For loops still work with assignment expressions -- **Clear intent**: Distinguishes between intentional assignments and accidental ones +### File Processing +```go +var lines = readLines("data.txt"); +var processed = []; -### Memory Management +for (var i = 0; i < len(lines); i = i + 1) { + var line = lines[i]; + if (len(line) > 0) { + push(processed, "Processed: " + line); + } +} -Bob uses automatic memory management with conservative cleanup: - -**Reference Counting**: -- All objects use `std::shared_ptr` for automatic cleanup -- Functions and thunks are tracked by reference count -- Objects are freed when no longer referenced - -**Automatic Cleanup**: -- Functions created in loops are automatically cleaned up when unused -- Cleanup occurs every 1000 function/thunk creations -- Only removes objects with `use_count() == 1` (conservative approach) - -**Safety Guarantees**: -- Functions referenced anywhere are never cleaned up -- Only truly unused functions are removed -- No dangling pointers or memory corruption +writeFile("output.txt", join(processed, "\n")); +``` --- -*This documentation covers the current Bob language implementation. For development plans, see ROADMAP.md.* \ No newline at end of file +*For more examples, see the comprehensive test suite in `test_bob_language.bob`* \ No newline at end of file diff --git a/Reference/BUILD.md b/Reference/BUILD.md new file mode 100644 index 0000000..a02eed9 --- /dev/null +++ b/Reference/BUILD.md @@ -0,0 +1,248 @@ +# Bob Language - Build Guide + +This guide describes how to build the Bob language interpreter using CMake + Ninja across different platforms. + +## 🚀 Quick Start + +### Prerequisites +- **CMake** 3.20 or later +- **Ninja** build system +- **C++17** compatible compiler + +### Platform-Specific Setup + +#### 🍎 macOS +```bash +# Install via Homebrew +brew install cmake ninja + +# Or via MacPorts +sudo port install cmake ninja +``` + +#### 🐧 Linux + +**Ubuntu/Debian:** +```bash +sudo apt update +sudo apt install cmake ninja-build build-essential +``` + +**RHEL/CentOS/Fedora:** +```bash +# RHEL/CentOS +sudo yum install cmake ninja-build gcc-c++ + +# Fedora +sudo dnf install cmake ninja-build gcc-c++ +``` + +**Arch Linux:** +```bash +sudo pacman -S cmake ninja gcc +``` + +#### 🪟 Windows + +**Option 1: Visual Studio (Recommended)** +- Install Visual Studio 2019+ with C++ workload +- Install CMake via Visual Studio Installer +- Install Ninja: `winget install Ninja-build.Ninja` + +**Option 2: MSYS2/MinGW** +```bash +# In MSYS2 terminal +pacman -S mingw-w64-x86_64-cmake mingw-w64-x86_64-ninja mingw-w64-x86_64-gcc +``` + +**Option 3: Chocolatey** +```powershell +# In Administrator PowerShell +choco install cmake ninja visualstudio2022buildtools +``` + +## 🔨 Build Commands + +### Standard Build + +**Release Build (Optimized):** +```bash +cmake -G Ninja -B build -DCMAKE_BUILD_TYPE=Release +ninja -C build +``` + +**Debug Build (Development):** +```bash +cmake -G Ninja -B build -DCMAKE_BUILD_TYPE=Debug +ninja -C build +``` + +### Platform-Specific Examples + +#### macOS/Linux +```bash +# Configure and build +cmake -G Ninja -B build -DCMAKE_BUILD_TYPE=Release +ninja -C build + +# Run interpreter +./build/bin/bob + +# Run test suite +./build/bin/bob test_bob_language.bob + +# Run with custom script +./build/bin/bob your_script.bob +``` + +#### Windows (PowerShell/CMD) +```powershell +# Configure and build +cmake -G Ninja -B build -DCMAKE_BUILD_TYPE=Release +ninja -C build + +# Run interpreter +.\build\bin\bob.exe + +# Run test suite +.\build\bin\bob.exe test_bob_language.bob + +# Run with custom script +.\build\bin\bob.exe your_script.bob +``` + +#### Windows (MSYS2/Git Bash) +```bash +# Same as macOS/Linux +cmake -G Ninja -B build -DCMAKE_BUILD_TYPE=Release +ninja -C build +./build/bin/bob.exe test_bob_language.bob +``` + +## 🧪 Testing + +### Automated Testing + +**All Platforms:** +```bash +# Build first +ninja -C build + +# Run tests via CTest +cd build +ctest --output-on-failure + +# Or run tests verbosely +ctest --verbose +``` + +**Windows PowerShell:** +```powershell +ninja -C build +cd build +ctest --output-on-failure +``` + +### Manual Testing + +**Interactive Mode:** +```bash +# Unix-like systems +./build/bin/bob + +# Windows +.\build\bin\bob.exe +``` + +**Script Execution:** +```bash +# Unix-like systems +./build/bin/bob examples/hello.bob + +# Windows +.\build\bin\bob.exe examples\hello.bob +``` + +## ⚡ Performance + +**CMake + Ninja** provides fast, cross-platform builds with excellent incremental compilation. + +## 🔧 Advanced Configuration + +### Custom Install Location + +**Unix-like:** +```bash +cmake -G Ninja -B build \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX=/opt/bob +ninja -C build install +``` + +**Windows:** +```powershell +cmake -G Ninja -B build ` + -DCMAKE_BUILD_TYPE=Release ` + -DCMAKE_INSTALL_PREFIX="C:\Program Files\Bob" +ninja -C build install +``` + +### Compiler Selection + +**GCC:** +```bash +cmake -G Ninja -B build \ + -DCMAKE_CXX_COMPILER=g++ \ + -DCMAKE_BUILD_TYPE=Release +``` + +**Clang:** +```bash +cmake -G Ninja -B build \ + -DCMAKE_CXX_COMPILER=clang++ \ + -DCMAKE_BUILD_TYPE=Release +``` + +**MSVC (Windows):** +```powershell +cmake -G Ninja -B build ` + -DCMAKE_CXX_COMPILER=cl ` + -DCMAKE_BUILD_TYPE=Release +``` + +## 🐛 Troubleshooting + +### Common Issues + +**CMake not found:** +- **macOS**: `brew install cmake` +- **Ubuntu**: `sudo apt install cmake` +- **Windows**: Install via Visual Studio or winget + +**Ninja not found:** +- **macOS**: `brew install ninja` +- **Ubuntu**: `sudo apt install ninja-build` +- **Windows**: `winget install Ninja-build.Ninja` + +**Compiler errors:** +- Ensure C++17 compiler is installed +- **Linux**: `sudo apt install build-essential` +- **Windows**: Install Visual Studio Build Tools + +**Permission denied (Windows):** +- Run PowerShell as Administrator for system-wide installs + +### Build Cache Issues + +**Clean build:** +```bash +# Remove build directory +rm -rf build # Unix-like +rmdir /s build # Windows CMD +Remove-Item -Recurse build # PowerShell + +# Reconfigure +cmake -G Ninja -B build -DCMAKE_BUILD_TYPE=Release +ninja -C build +``` + diff --git a/Reference/ROADMAP.md b/Reference/ROADMAP.md index df1cc85..7de73b3 100644 --- a/Reference/ROADMAP.md +++ b/Reference/ROADMAP.md @@ -2,176 +2,176 @@ ## Current Status -Bob is a working programming language with a solid foundation. Here's what's currently implemented: +Bob is a mature, working programming language with a modern architecture and comprehensive feature set. -### ✅ **Core Language Features** +### ✅ **Core Language Features (Complete)** #### **Data Types & Variables** - **Numbers**: Integers, floats, automatic conversion -- **Strings**: Literals, concatenation, multiplication +- **Strings**: Literals, concatenation, multiplication, escape sequences - **Booleans**: `true`, `false` - **None**: Null value representation +- **Arrays**: Dynamic arrays with indexing, assignment, and built-in functions +- **Dictionaries**: Hash maps with string keys and mixed-type values +- **Functions**: First-class functions as values - **Variables**: Declaration, assignment, scoping -- **Assignment System**: Dual system (statements + expressions for loops) +- **Assignment System**: Dual system (statements + expressions for loops only) -#### **Operators** -- **Arithmetic**: `+`, `-`, `*`, `/`, `%` +#### **Operators (Complete)** +- **Arithmetic**: `+`, `-`, `*`, `/`, `%`, unary `-` - **Comparison**: `==`, `!=`, `>`, `<`, `>=`, `<=` - **Logical**: `&&`, `||`, `!` (with short-circuit evaluation) - **Bitwise**: `&`, `|`, `^`, `<<`, `>>`, `~` - **Compound Assignment**: `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `<<=`, `>>=` - **Ternary**: `condition ? valueIfTrue : valueIfFalse` +- **Increment/Decrement**: `++`, `--` (for array elements) -#### **Control Flow** +#### **Control Flow (Complete)** - **If Statements**: `if`, `else`, `else if` chains - **While Loops**: Basic, nested, complex conditions -- **For Loops**: All clause variations, nested loops - **Do-While Loops**: Basic, nested, break/continue support +- **For Loops**: All clause variations, nested loops - **Break/Continue**: Full support in all loop types -#### **Functions** +#### **Functions (Complete)** - **Function Declaration**: `func name(params) { body }` -- **Parameters**: Any number of parameters +- **Parameters**: Any number of parameters (tested up to 100) - **Return Values**: Explicit and implicit returns - **Closures**: Lexical scoping with variable capture - **First-Class Functions**: Functions as values, parameters, return values - **Anonymous Functions**: `func(params) { body }` - **Nested Functions**: Functions defined inside other functions - **Recursion**: Full support including deep recursion -- **Tail Call Optimization**: Trampoline-based optimization to prevent stack overflow +- **Tail Call Optimization**: Trampoline-based optimization preventing stack overflow -#### **Data Structures** -- **Arrays/Lists**: Full support with indexing, assignment, and built-in functions -- **Maps/Dictionaries**: Full support with key-value pairs and built-in functions -- **Array Operations**: `len()`, indexing, assignment, nested arrays +#### **Data Structures (Complete)** +- **Arrays**: Full support with indexing, assignment, nested arrays +- **Dictionaries**: Full support with key-value pairs, nested dictionaries +- **Array Operations**: `len()`, `push()`, `pop()`, indexing, assignment - **Dictionary Operations**: `keys()`, `values()`, `has()`, indexing, assignment +- **Mixed Types**: Arrays and dictionaries can hold any value types -#### **Standard Library** -- **`print()`**: Output with automatic type conversion -- **`assert()`**: Testing with custom error messages -- **`type()`**: Runtime type checking -- **`toString()`**: Universal string conversion -- **`toNumber()`**: String-to-number conversion -- **`input()`**: User input capability -- **`time()`**: Microsecond precision timing -- **`random()`**: Random number generation (properly seeded) -- **`len()`**: Get length of arrays and strings -- **`keys()`**: Get all keys from dictionaries -- **`values()`**: Get all values from dictionaries -- **`has()`**: Check if key exists in dictionary -- **`eval()`**: Evaluate strings as Bob code -- **`sleep()`**: Pause execution for specified seconds -- **`exit()`**: Terminate program with exit code +#### **Standard Library (Complete)** +- **I/O Functions**: `print()`, `printRaw()`, `input()` +- **Type System**: `type()`, `toString()`, `toNumber()`, `toInt()`, `toBoolean()` +- **Testing**: `assert()` with custom error messages +- **Timing**: `time()` (microsecond precision), `sleep()` +- **Utility**: `random()` (properly seeded), `eval()`, `exit()` +- **Data Structure**: `len()`, `push()`, `pop()`, `keys()`, `values()`, `has()` +- **File I/O**: `readFile()`, `writeFile()`, `readLines()`, `fileExists()` -#### **Advanced Features** +#### **Advanced Features (Complete)** - **String Operations**: Bidirectional string + number concatenation -- **Number Formatting**: Smart significant digits -- **Memory Management**: Automatic cleanup with shared pointers +- **Number Formatting**: Smart significant digits handling +- **Memory Management**: Automatic cleanup with reference counting - **Error Handling**: Comprehensive error reporting with context -- **Testing Framework**: Built-in assert function -- **Operator Precedence**: Full precedence hierarchy -- **Variable Shadowing**: Proper scoping rules +- **Testing Framework**: Built-in assert function with 70+ comprehensive tests +- **Operator Precedence**: Full precedence hierarchy implementation +- **Variable Shadowing**: Proper lexical scoping rules - **Interactive Mode**: Full REPL with error handling +- **Cross-Type Comparisons**: Smart equality for all types +- **Copy Semantics**: Value vs reference copying for different types -### **Current Limitations** +### ✅ **Architecture & Infrastructure (Complete)** -#### **Advanced Language Features** -- **No Classes/Objects**: No object-oriented programming -- **No Modules/Imports**: No code organization system -- **No Exception Handling**: No try-catch blocks -- **No Type Annotations**: No static type checking -- **No Generics**: No parametric polymorphism +#### **Modern Build System** +- **CMake**: Cross-platform build configuration +- **Ninja**: High-speed build system (3.1x faster than Make) +- **CTest**: Integrated testing framework +- **Cross-Platform**: Windows, macOS, Linux support +- **Performance**: Optimized build times and incremental compilation -#### **Standard Library Gaps** -- **No File I/O**: No reading/writing files -- **No Network I/O**: No HTTP or socket operations -- **No Math Library**: No advanced mathematical functions (sqrt, max, min, etc.) -- **No Date/Time**: No date manipulation (except `time()`) -- **No String Processing**: No split, join, toUpper, toLower functions +#### **Clean Architecture** +- **Modular Design**: Separated parsing, runtime, stdlib, and CLI +- **Tier Separation**: Clear boundaries between language components +- **Header Organization**: Organized by functional area +- **Source Structure**: `src/headers/` and `src/sources/` organization -#### **Development Tools** -- **No Debugger**: No debugging tools -- **No Profiler**: No performance analysis -- **No Package Manager**: No dependency management +#### **Refactored Interpreter** +- **Evaluator**: Expression evaluation (visitor pattern) +- **Executor**: Statement execution and control flow +- **RuntimeDiagnostics**: Utility functions and type checking +- **Memory Management**: Smart pointer usage throughout +- **Error System**: Centralized error reporting + +### **Current Architecture Status** + +``` +Bob Language +├── Parsing Layer +│ ├── Lexer (tokenization) +│ ├── Parser (AST generation) +│ └── ErrorReporter (syntax errors) +├── Runtime Layer +│ ├── Evaluator (expression visitor) +│ ├── Executor (statement visitor) +│ ├── Interpreter (orchestration) +│ ├── Environment (variable scoping) +│ ├── Value (type system) +│ └── RuntimeDiagnostics (utilities) +├── Standard Library +│ └── BobStdLib (built-in functions) +└── CLI Interface + └── Bob (command-line interface) +``` ## **Future Development Phases** -### **Phase 1: Standard Library Expansion (High Priority)** +### **Phase 1: Advanced Language Features (Medium Priority)** -#### **File I/O** -```bob -var content = readFile("data.txt"); -writeFile("output.txt", "Hello World"); -var lines = readLines("config.txt"); -``` - -**Implementation Plan:** -- Add `readFile()` function for reading entire files -- Add `writeFile()` function for writing files -- Add `readLines()` function for reading files line by line -- Add error handling for file operations - -#### **Math Library** -```bob -var result = sqrt(16); // 4.0 -var max = max(5, 10, 3); // 10 -var min = min(5, 10, 3); // 3 -var abs = abs(-42); // 42 -``` - -**Implementation Plan:** -- Add `sqrt()` for square root -- Add `max()` and `min()` for multiple arguments -- Add `abs()` for absolute value -- Add `pow()` for exponentiation -- Add `floor()`, `ceil()`, `round()` for rounding - -#### **String Processing** -```bob -var parts = split("a,b,c", ","); // ["a", "b", "c"] -var joined = join(parts, "-"); // "a-b-c" -var upper = toUpper("hello"); // "HELLO" -var lower = toLower("WORLD"); // "world" -``` - -**Implementation Plan:** -- Add `split()` for string splitting -- Add `join()` for array joining -- Add `toUpper()` and `toLower()` for case conversion -- Add `trim()` for whitespace removal -- Add `replace()` for string replacement - -### **Phase 2: Advanced Language Features (Medium Priority)** - -#### **Exception Handling** +#### **Exception Handling System** ```bob try { var result = 10 / 0; } catch (error) { - print("Error: " + error); + print("Error: " + error.message); +} finally { + print("Cleanup"); } ``` **Implementation Plan:** -- Add `try`/`catch` syntax -- Implement exception objects -- Add `throw` statement +- Add `try`/`catch`/`finally` syntax to parser +- Implement exception objects with stack traces +- Add `throw` statement for custom exceptions - Integrate with existing error system -#### **Object System Foundation** +#### **Pattern Matching** ```bob -// Convert everything to inherit from Object base class -// Enable method calls on all types -// Prepare foundation for classes and modules +match value { + case 0: "zero" + case 1 | 2: "small" + case x if x > 10: "large" + default: "other" +} ``` **Implementation Plan:** -- Unify type system under Object base class -- Convert functions to proper objects -- Enable method calls on all data types -- Update Value union to work with object system +- Add `match`/`case` syntax +- Implement pattern matching logic +- Support guards with `if` conditions +- Add destructuring for arrays/dictionaries -#### **Classes & Objects** +### **Phase 2: Object System (Lower Priority)** + +#### **Simple Objects** +```bob +var person = { + name: "Alice", + age: 30, + greet: func() { + return "Hello, I'm " + this.name; + } +}; +``` + +**Implementation Plan:** +- Add object literal syntax +- Implement `this` binding +- Support method calls +- Add property access/assignment + +#### **Classes (Optional)** ```bob class Person { init(name, age) { @@ -188,140 +188,125 @@ class Person { **Implementation Plan:** - Add `class` keyword and syntax - Implement constructors with `init()` +- Support inheritance with `extends` - Add method definitions -- Support inheritance ### **Phase 3: Module System (Lower Priority)** -#### **Modules/Imports** +#### **Simple Modules** ```bob -import "math.bob"; -import "utils.bob" as utils; +// math.bob +func sqrt(x) { return x ** 0.5; } +func max(a, b) { return a > b ? a : b; } +// main.bob +import "math.bob" as math; var result = math.sqrt(16); -var helper = utils.format("Hello"); ``` **Implementation Plan:** - Add `import` statement syntax - Implement module loading from files - Support namespace aliases -- Create built-in modules (math, utils, etc.) +- Create standard library modules -### **Phase 4: Development Tools (Lower Priority)** +### **Phase 4: Language Enhancements (Optional)** -#### **Debugger** +#### **Enhanced Standard Library** ```bob -debugger; // Breakpoint -var x = 5; -// Step through code +// Additional string functions +var parts = "a,b,c".split(","); +var joined = ["a", "b", "c"].join("-"); +var upper = "hello".toUpper(); + +// Math library +var result = Math.sqrt(16); +var max = Math.max(5, 10, 3); ``` -**Implementation Plan:** -- Add `debugger` statement -- Implement breakpoint functionality -- Add step-through debugging -- Create debug console interface - -#### **Profiler** +#### **Async/Await (Advanced)** ```bob -// Built-in performance analysis -// Function call timing -// Memory usage tracking +async func fetchData() { + var response = await http.get("api.com/data"); + return response.json(); +} ``` -**Implementation Plan:** -- Add performance measurement functions -- Track function call times -- Monitor memory usage -- Generate performance reports - ## **Implementation Guidelines** ### **For Each New Feature:** -1. **Lexer**: Add new tokens if needed -2. **Parser**: Add new expression/statement types -3. **AST**: Define new node types -4. **Interpreter**: Implement evaluation logic -5. **Testing**: Create comprehensive test cases +1. **Design**: Plan syntax and semantics carefully +2. **Lexer**: Add new tokens if needed +3. **Parser**: Add new expression/statement types +4. **AST**: Define new node types in Expression.h/Statement.h +5. **Evaluator/Executor**: Implement evaluation logic +6. **Testing**: Write tests for the new feature +7. **Documentation**: Update language reference -### **Testing Strategy:** -```bob -// Use the built-in assert function for testing -assert(add(2, 3) == 5, "add(2, 3) should equal 5"); -assert(len([1, 2, 3]) == 3, "Array length should be 3"); -assert(has({"a": 1}, "a"), "Dictionary should have key 'a'"); -``` - -### **Code Quality Standards:** -- **Comprehensive Testing**: Every feature needs test coverage -- **Error Handling**: Graceful error messages with context -- **Documentation**: Update language reference -- **Performance**: Consider memory and speed implications -- **Professional Code**: Clean, maintainable, production-ready +### **Development Approach:** +- **Testing**: Write tests for new features +- **Error Messages**: Make errors helpful and clear +- **Memory**: Use smart pointers to avoid leaks +- **Performance**: Don't make things unnecessarily slow +- **Code Style**: Keep it readable and maintainable +- **Portability**: Make sure it works on different platforms ## **Success Metrics** -### **Completed ✅** +### **What's Done ✅** - [x] Core language syntax and semantics -- [x] All basic operators and expressions -- [x] Control flow statements -- [x] Functions and closures -- [x] Tail call optimization +- [x] All operators and expressions +- [x] Control flow (if, while, for, do-while) +- [x] Functions, closures, and tail call optimization - [x] Arrays and dictionaries -- [x] Standard library basics -- [x] Random number generation +- [x] Standard library (25+ built-in functions) +- [x] File I/O operations - [x] Interactive REPL -- [x] Testing framework -- [x] Comprehensive error handling +- [x] Test suite with 70+ tests +- [x] Error handling and reporting - [x] Memory management -- [x] Assignment system design -- [x] Code quality improvements +- [x] CMake + Ninja build system +- [x] Modular architecture +- [x] Cross-platform support +- [x] Various optimizations -### **In Progress 🔄** -- [ ] File I/O implementation -- [ ] Math library functions -- [ ] String processing functions - -### **Planned 📋** -- [ ] Exception handling system -- [ ] Object system foundation -- [ ] Classes and objects -- [ ] Module system -- [ ] Development tools +### **Might Add Later 📋** +- [ ] Exception handling (try/catch) +- [ ] Pattern matching +- [ ] Simple objects +- [ ] Module/import system +- [ ] More built-in functions +- [ ] Debugging tools ## **Resources** -- **[BOB_LANGUAGE_REFERENCE.md](BOB_LANGUAGE_REFERENCE.md)** - Complete language documentation -- **[test_bob_language.bob](test_bob_language.bob)** - Comprehensive test suite -- **[Crafting Interpreters](https://craftinginterpreters.com/)** - Excellent resource for language implementation +- **[Language Reference](BOB_LANGUAGE_REFERENCE.md)** - Language documentation +- **[Build Guide](BUILD.md)** - How to build Bob +- **[Test Suite](../test_bob_language.bob)** - 70+ tests +- **[Crafting Interpreters](https://craftinginterpreters.com/)** - Helpful book for language implementation -## **Recent Major Achievements** +## **Recent Work** -### **Data Structures Implementation** -- Full array support with indexing and assignment -- Complete dictionary system with key-value operations -- Built-in functions: `len()`, `keys()`, `values()`, `has()` -- Nested data structures support +### **Architecture Cleanup (2025)** +- Split the interpreter into separate components (Evaluator/Executor/RuntimeDiagnostics) +- Switched to CMake + Ninja build system (3x faster builds) +- Reorganized code into cleaner modules +- Added Windows/macOS/Linux build support -### **Standard Library Expansion** -- `random()` function with proper seeding -- `eval()` for dynamic code execution -- `sleep()` for timing control -- `exit()` for program termination +### **Feature Completion** +- Added file I/O and type conversion functions +- Implemented all the operators I wanted (bitwise, compound assignment, etc.) +- Got arrays and dictionaries working properly +- Added tail call optimization and closures -### **Code Quality Improvements** -- Professional code cleanup -- Performance optimizations -- Consistent error handling -- Memory leak prevention - -### **Advanced Language Features** -- Tail call optimization with trampoline system -- Comprehensive error reporting with context -- Interactive REPL with full language support -- Memory management with automatic cleanup +### **Testing & Polish** +- Wrote 70+ tests covering pretty much everything +- Improved error messages to be more helpful +- Fixed memory leaks using smart pointers +- Various performance improvements --- -*Last updated: January 2025* \ No newline at end of file +Bob works well for what I wanted - a programming language with the features and syntax I prefer. + +*Last updated: January 2025* \ No newline at end of file