Files
goca/README.md
2026-07-27 16:14:41 +02:00

8.2 KiB

🧮 goca

A feature-rich, high-precision, scientific command-line calculator written in Go, powered by an Abstract Syntax Tree (AST) evaluator and arbitrary-precision decimal arithmetic.

Go Version License


Features

  • High-Precision Arithmetic: Uses arbitrary-precision decimal math (no floating-point rounding errors).
  • Unit Conversions: Supports Length, Mass, Time, Area, Temperature, Digital Storage, and Angle conversions natively.
  • Live Currency Exchange: Real-time currency conversion rates fetched automatically and cached.
  • IP & CIDR Utilities: Built-in network functions to parse IPs, calculate networks, broadcasts, netmasks, and address ranges.
  • User-Defined Variables & Functions: Persists variables and custom functions across sessions automatically.
  • Rich Scientific Math: Trigonometric (supporting deg/rad/grad), hyperbolic, and standard statistical/mathematical functions.
  • Interactive CLI: Autocompletion (TAB), history scroll, and syntax-colored output. Can also be used non-interactively via shell pipes.

🚀 Installation & Setup

Ensure you have Go installed.

  1. Clone and Navigate:

    git clone https://git.fhi.mpg.de/mike/goca.git
    cd goca
    
  2. Build the Binary:

    go build -o goca
    
  3. Install to Path (Optional):

    mv goca /usr/local/bin/
    

💡 Quick Start

Simply run goca to start the interactive shell:

$ ./goca
goca v1.0.15, type 'help' for examples.

goca> 5 + 3 * 2
= 11 (0xB, 0b1011)

goca> 100 USD to EUR
= 91.42 EUR

Or pipe expressions directly from your shell:

echo "10 mi to km" | ./goca

🌐 Web GUI & Server Mode

goca now features an interactive cyberpunk-styled web dashboard! Start the server by passing the -p or --port flag:

$ ./goca -p 8800
🌐 Go-Ca web server started on http://localhost:8800

Open your browser and navigate to http://localhost:8800 to access the console. The Web GUI supports:

  • Interactive Console: Runs calculations with ANSI terminal color rendering.
  • Command History: Navigate your previous queries using the ArrowUp and ArrowDown keys in the input box.
  • User Registry Panel: Displays your currently defined variables and custom functions in real-time. Click any item to insert it directly into the input line.
  • Quick Reference Guide: Direct access to mathematical, conversion, IP, and currency syntax templates.
  • State Management: Clear the server state (variables/functions) via the Reset State header action.

📡 Developer REST API

Integrate the calculator engine with other services via HTTP REST endpoints:

  • Evaluate: GET /api/calculate?q=<expression> - Returns { "output": "<result string>", "exit": <bool> }
  • List Variables: GET /api/variables - Returns a sorted JSON array of user-defined variables
  • List Functions: GET /api/functions - Returns a sorted JSON array of user-defined functions
  • Reset: POST /api/reset - Deletes all user-defined variables/functions

📘 Comprehensive Guide

🔢 Core Math & Number Systems

goca supports standard mathematical operations, bitwise logic, and various number systems:

  • Arithmetic: +, -, *, /, % (modulo), ** or pow(a, b)
  • Bitwise Operations: & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left Shift), >> (Right Shift)
  • Number Systems:
    • Hexadecimal: 0xFF
    • Binary: 0b1010
    • Octal: 0o77
  • Implicit Multiplication: 2(3 + 4) or 2km

📐 Scientific & Mathematical Functions

A rich suite of functions is built-in:

  • Trigonometry: sin(x), cos(x), tan(x) (supports suffixes, e.g., sin(90 deg) or sin(pi rad))
  • Inverse Trig: asin(x), acos(x), atan(x) (returns units, e.g., asin(1) to deg)
  • Hyperbolic: sinh(x), cosh(x), tanh(x)
  • General Math: sqrt(x), abs(x), exp(x), ln(x) (natural), log(x) (base 10), log2(x)
  • Rounding: ceil(x), floor(x), round(x)
  • Combinatorics & Stats: fact(x) (factorial), min(a, b, ...), max(a, b, ...), mod(a, b)
  • Conditionals: if(cond, true_val, false_val) (e.g., if(5 > 3, 10, 20))
  • Constants: PI and E

💾 Variables & Custom Functions

Define and persist your own variables and functions:

  • Variables:
    • Assign: x = 5.5
    • Reference last output: ans or _ (e.g., ans * 2)
    • List variables: var
    • Delete variable: unset x (or unset * to clear all)
  • Custom Functions:
    • Define: f(x, y) = x * y + 2
    • Evaluate: f(3, 4) (yields 14)
    • List functions: funcs
    • Delete function: unset f

All custom variables and functions are saved to ~/.goca_variables.json and ~/.goca_functions.json respectively, making them available in future sessions.

🌐 IP & Subnet Calculations

goca includes a robust set of network utility functions:

  • Parse IP / CIDR: ip("192.168.1.1"), cidr("10.0.0.0/24")
  • Network Address: network(cidr("10.0.0.50/24")) (yields 10.0.0.0/24)
  • Broadcast Address: broadcast(cidr("10.0.0.50/24")) (yields 10.0.0.255)
  • Netmask: mask(cidr("10.0.0.50/24")) (yields 255.255.255.0)
  • Hosts Count: hosts(cidr("10.0.0.0/24")) (yields 254)
  • IP Range: range(cidr("10.0.0.0/24")) (returns string representation of start and end IPs)

📏 Unit Conversions

Convert measurements using the syntax: <value> <unit> to <unit> or <value> <unit> in <unit>.

Dimension Supported Units
Length km, m, dm, cm, mm, um, nm, mi (mile), nmi (nautical mile), ft (foot), in (inch), yd (yard)
Mass t (tonne), kg, g, mg, ct (carat), lb (pound), oz (ounce)
Time yr (year), wk (week), d (day), h (hour), min (minute), s, ms, us, ns
Digital Storage EB, PB, TB, GB, MB, KB, B (binary multiplier: 1024 base)
Area km2 (sq. kilometer), ha (hectare), acre, m2 (sq. meter), cm2, mm2
Temperature K (Kelvin), C (Celsius), F (Fahrenheit)
Angle rad, deg (degree), grad

Examples:

goca> 100 mi to km
= 160.9344 km

goca> 1 GB in MB
= 1024 MB

goca> 0 C to F
= 32.0000 °F

💱 Live Currency Exchange

goca fetches exchange rates daily from the Open Exchange Rates API and caches them locally at ~/.goca_rates.json.

  • Conversion: 100 USD to EUR or 10$ to €
  • Change Base Currency: base USD
  • List Supported Currency Codes: cur
  • View Exchange Rates: rates (shows core currencies relative to base)

🛠️ Commands Reference

The interactive shell supports the following commands:

  • help - Show help information.
  • units - List all supported measurement units.
  • rates - Show currency exchange rates relative to the base currency.
  • cur - List all supported currency codes.
  • var - List all user-defined variables.
  • funcs - List all user-defined functions.
  • unset <name> - Delete a variable or custom function (or unset * to clear all).
  • base <currency> - Change base currency.
  • clear - Clear the terminal screen.
  • exit or quit - Close the session.

📦 Project Architecture

  • cli.go - Command loop, line-completion, history, and user input handler.
  • units.go - Units registry and conversion metadata.
  • currency.go - Exchange rates fetcher, caching, and currency unit initialization.
  • evaluator.go - AST evaluator implementing all math, logic, IP, and unit conversion rules.
  • parser.go - Lexer and recursive descent parser.
  • ast.go - Abstract Syntax Tree structures for parsing expressions.
  • types.go - Core types used across parsing and evaluation.
  • main_test.go - Test suite covering math, variables, functions, and unit conversions.