COMPLETE LANGUAGE REFERENCE v0.2.0

SymbolCore Documentation

Every syntax rule. Every mode. Every benchmark. One page. Built for developers and AI assistants.

Extension: .sym Run: sym run file.sym Compile: sym build -t native file.sym Check: sym check file.sym

🤖 For AI Assistants — Read This First

When writing SymbolCore code, follow these rules exactly:

Contents

01. Overview

SymbolCore compiles to Python (for library access) and C (for speed). Pure functions auto-compile to native C via gcc. Python library calls stay as Python. The compiler decides — you write one file.

# hello.sym — this is all you need
print "Hello from SymbolCore!"

let name = "World"
print "Hello, {name}!"
# Run it
sym run hello.sym

02. Variables & Constants

let — mutable variable

let x = 42
let name = "Abir"
let pi = 3.14159
let active = true
let items = [1, 2, 3]

const — immutable

const MAX = 1000
const URL = "https://api.example.com"

With types (optional)

let x: int = 42
let name: str = "Abir"

Reassignment (no let)

let x = 10
x = 20        # no let for reassignment
x += 5        # compound: +=  -=  *=  /=
Rule: First assignment uses let. Subsequent reassignments don't. const cannot be reassigned.

03. Type System gradual

Types are optional. Adding them enables better C compilation and catches errors early.

SymbolCoreDescriptionC Type
int64-bit integerint64_t
i3232-bit integerint32_t
float64-bit floatdouble
f3232-bit floatfloat
boolBooleanint
strUTF-8 stringchar*
list<T>Dynamic arrayPython list
dict<K,V>Hash mapPython dict
T?Optional (nullable)
Syntax: Types go after name with colon: name: type. Return types use arrow: -> type.

04. Functions

Basic

fn add(a: int, b: int) -> int
    return a + b

Single expression (fat arrow)

fn double(x: int) -> int => x * 2

No return type (void)

fn greet(name: str)
    print "Hello {name}"

Default parameters

fn connect(host: str, port: int = 8080)
    print "Connecting to {host}:{port}"

Recursive

fn factorial(n: int) -> int
    if n <= 1
        return 1
    return n * factorial(n - 1)
Rule: Use fn, NOT def. No colon after signature. No parentheses around body. 4-space indent. Return type uses ->.

05. Control Flow

if / elif / else

if score >= 90
    grade = "A"
elif score >= 80
    grade = "B"
else
    grade = "F"
Rule: No colon after if/elif/else. No parentheses around condition. Body indented 4 spaces.

06. Loops & Ranges

for with range (..)

for i in 0..10
    print i            # 0 through 9 (exclusive end)

for over collection

for item in items
    print item

for with index

for i, val in enumerate(data)
    print "{i}: {val}"

while

let x = 0
while x < 100
    x += 1

break / continue

for i in 0..100
    if i == 50
        break
    if i % 2 == 0
        continue
    print i
Rule: Range is start..stop (exclusive end). Two dots. No colon after for/while. range() also works.

07. Strings & Interpolation

let name = "Abir"
let age = 28
print "Name: {name}, Age: {age}"     # auto f-string
print "2 + 2 = {2 + 2}"              # expressions work

let msg = "Score: " + str(score)     # concatenation
Rule: Any string with {expr} auto-interpolates. No f"..." prefix needed. Both "double" and 'single' quotes work.

08. Collections

Lists

let nums = [1, 2, 3, 4, 5]
let first = nums[0]          # indexing
let slice = nums[1:3]       # slicing
nums.append(6)               # methods work

Dicts

let user = {"name": "Abir", "age": 28}
print user["name"]

Tuples

let point = (3.0, 4.0)

09. Structs & Methods

struct Point
    x: float
    y: float

    fn distance(self, other: Point) -> float
        let dx = self.x - other.x
        let dy = self.y - other.y
        return sqrt(dx * dx + dy * dy)

let p1 = Point(0.0, 0.0)
let p2 = Point(3.0, 4.0)
print p1.distance(p2)     # 5.0

Default fields

struct Config
    host: str = "localhost"
    port: int = 8080
Rule: Constructor auto-generated from fields. Methods take self as first param. Structs stay in Python mode (not compiled to C).

10. Traits & Impl

trait Printable
    fn to_string(self) -> str

impl Printable for Point
    fn to_string(self) -> str
        return "Point({self.x}, {self.y})"

11. Python Interop killer feature

Use ANY pip package. The py. prefix tells the compiler it's a Python library. Missing packages are auto-installed.

Import syntax

import py.numpy as np
import py.pandas as pd
import py.matplotlib.pyplot as plt
import py.requests as req
import py.sklearn.ensemble as sk
import py.torch as torch
import py.bs4.BeautifulSoup as BS
import py.json as json
import py.os as os
import py.sys as sys

Usage

import py.numpy as np

let data = np.array([1, 2, 3, 4, 5])
print "Mean: {np.mean(data)}"

Auto-install chain

When a package is missing: pip install --userpip3 install --usersudo apt install python3-pkg → prints manual instructions.

Name mappings

ModulePip Package
cv2opencv-python
PILPillow
sklearnscikit-learn
bs4beautifulsoup4
yamlpyyaml
docxpython-docx
serialpyserial
Cryptopycryptodome
Critical: ALL Python imports MUST use py. prefix. import numpy will NOT work. Use import py.numpy as np.

12. Built-in Functions

Always available. No import needed.

FunctionUsageNotes
printprint "Hello {x}"Keyword — no parens needed
sortsort dataKeyword — in-place, adaptive algorithm
len(x)len(data)Function call syntax
map(coll, fn)map(data, (x) => x*2)Returns new list
filter(coll, fn)filter(data, (x) => x>0)Returns filtered list
range(a, b)range(0, 100)Same as 0..100
enumerate(x)enumerate(items)Index + value pairs
zip(a, b)zip(keys, vals)Combine collections
type(x)type(42)Get type
clone(x)clone(data)Deep copy
str(x)str(42)Convert to string
sqrt(x)sqrt(16)Square root
sin cos tansin(3.14)Trig functions
log log2 log10log(100)Logarithms
floor ceilfloor(3.7)Round down/up

Constants: PI, E, INF

13. Error Handling

try
    let data = read_file("config.json")
catch e
    print "Error: " + str(e)

# With type
try
    let r = py.requests.get(url)
catch e: Exception
    print "Failed"
Rule: try/catch, NOT try/except. No colons.

14. Pattern Matching

match command
    "start" => run()
    "stop"  => shutdown()
    "help"  => show_help()
    _       => print "Unknown"
Rule: => fat arrow between pattern and action. _ is wildcard/default.

15. Lambdas & Pipes

Lambda

let sq = (x) => x * x
let add = (a, b) => a + b

let evens = filter(data, (x) => x % 2 == 0)

Pipe operator

let result = data |> filter((x) => x > 0) |> map((x) => x * 2)
Rule: (params) => expr, not lambda. Pipe |> passes left as first arg to right.

16. Benchmark & Optimize

benchmark fn test_algo()
    let result = fibonacci(30)
    print result

test_algo()   # prints timing automatically

Smart sort picks algorithm by data size:

SizeAlgorithm
<16Insertion sort
Nearly sortedTimsort
Largeqsort (C) / Timsort (Python)

17. All Three Syntax Modes

All three compile to the same AST — zero performance difference. Choose your style.

Hello World

Normal (.sym)

print "Hello!"
let x = 42
print "x = {x}"

Compact (#compact)

#compact
>> "Hello!"
@ x = 42
>> "x = {x}"

Symbol (#symbol)

#symbol"Hello!"
∂ x = 42"x = {x}"

Functions

Normal

fn fib(n: int) -> int
    if n <= 1
        return n
    return fib(n-1) + fib(n-2)

Compact

#compact
f fib(n: int) -> int
    ? n <= 1
        <- n
    <- fib(n-1) + fib(n-2)

Symbol

#symbol
ƒ fib(n:ℤ)→ℤ
    ? n ≤ 1
        ← n
    ← fib(n-1) + fib(n-2)

Loops

Normal

for i in 0..10
    print i

while x > 0
    x -= 1

Compact

#compact
~ i in 0..10
    >> i

~~ x > 0
    x -= 1

Symbol

#symbol
∀ i in 0..10
    ⊕ i

⟳ x > 0
    x -= 1

Imports

Normal

import py.numpy as np

Compact

#compact
<< py.numpy as np

Symbol

#symbol
⊂ py.numpy as np

18. Compact Mode — Complete Reference

Start file with #compact on the first line.

NormalCompactMeaning
fnfDefine function
let@Variable declaration
return<-Return from function
if?If condition
elif??Else-if
else!Else block
for~For loop
while~~While loop
print>>Print output
import<<Import module

Everything else (operators, types, strings, structs, etc.) stays the same.

19. Symbol Mode — Complete Reference

Start file with #symbol. Inherits ALL compact mode shortcuts plus Unicode operators.

NormalSymbolUnicode Name
fnƒLatin Small F with Hook (U+0192)
letPartial Differential (U+2202)
returnLeftwards Arrow (U+2190)
forFor All (U+2200)
whileClockwise Arrow (U+27F3)
importSubset Of (U+2282)
printCircled Plus (U+2295)
->Rightwards Arrow (U+2192)
!=Not Equal To (U+2260)
<=Less-Than or Equal (U+2264)
>=Greater-Than or Equal (U+2265)
=Colon Equals (U+2254)
intDouble-Struck Z (U+2124)
floatDouble-Struck R (U+211D)
bool𝔹Double-Struck B (U+1D539)
str𝕊Double-Struck S (U+1D54A)

Symbol mode also supports compact shortcuts: ? for if, ! for else, ~ for for, ~~ for while, >> for print, << for import, <- for return.

20. Compilation & Hybrid Engine

How it works

sym run file.sym automatically:

  1. Parses the file
  2. Analyzes each function — does it use py.* libraries?
  3. Pure functions (no Python deps) → compiled to C shared library (.so)
  4. Python-dependent functions → stay as Python
  5. Generated Python loads .so via ctypes, calls native C functions
  6. The .so is cached — subsequent runs skip compilation

What goes to C (pure)

What stays Python

Check the split

sym check file.sym
# ✅ file.sym: 7 statements
#    Functions: 5 total
#      → C:      4 (fibonacci, is_prime, count_primes, sum_cubes)
#      → Python: 1

21. Benchmarks vs Python real numbers

All benchmarks run on the same machine, same test (fib(35) + sum_squares(1M) + count_primes(100K)).

Overall: fib(35) + sum_squares(1M) + count_primes(100K)

Raw Python 3.12
2,237 ms
1x
SymbolCore (Python)
~2,200 ms
~1x
SymbolCore (Hybrid)
900 ms
2.5x
SymbolCore (Native)
60 ms
37x

fibonacci(35) — recursive

Python
1,778 ms
1x
SymbolCore Native
29 ms
62x

sum_squares(1,000,000) — tight loop

Python
166 ms
1x
SymbolCore Native
<0.1 ms
>1000x

count_primes(100,000) — while + modulo

Python
228 ms
1x
SymbolCore Native
46 ms
5x

When to use which mode

ModeCommandUse when
Pythonsym run --python file.symDebugging, or code uses only Python libs
Hybrid (default)sym run file.symMixed code — auto-splits C and Python
Native binarysym build -t native file.symPure computation, no Python libs needed

22. Operators Reference

CategoryOperators
Arithmetic+ - * / // (floor div) % (modulo) ** (power)
Comparison== != < > <= >=
Logicand or not
Assignment= += -= *= /=
Range.. (exclusive end)
Arrow-> (return type) => (lambda / match)
Pipe|> (pass left as first arg to right)
Membershipin
Access. (member) [] (index) [:] (slice)

23. CLI Reference

CommandWhat it does
sym run <file.sym>Run (hybrid C+Python, automatic)
sym run -v <file>Verbose — shows C vs Python split
sym run --python <file>Force pure Python mode
sym run --emit <file>Show generated C + Python code
sym run --tokens <file>Show lexer tokens
sym run --ast <file>Show AST
sym build -t python <file>Emit .py source
sym build -t c <file>Emit .c source
sym build -t native <file>Compile to binary (gcc)
sym build -t hybrid <file>Build .so + Python wrapper
sym check <file>Analyze purity, show C vs Python
sym replInteractive REPL
sym versionShow version

24. Full Examples

Web Scraper

import py.requests as req
import py.json as json

let r = req.get("https://api.github.com/repos/python/cpython")
let data = r.json()
print "Stars: " + str(data["stargazers_count"])

Data Pipeline

import py.numpy as np
import py.pandas as pd

# Pure → compiles to C
fn sum_squares(n: int) -> int
    let total = 0
    for i in 0..n
        total += i * i
    return total

# Python interop → stays Python
let df = pd.read_csv("data.csv")
print df.describe()

Hybrid Speed Demo

import py.json as json

# These 4 → compiled to C
fn fibonacci(n: int) -> int
    if n <= 1
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

fn is_prime(n: int) -> int
    if n < 2
        return 0
    let i = 2
    while i * i <= n
        if n % i == 0
            return 0
        i += 1
    return 1

# This → stays Python (uses json)
let results = {"fib": fibonacci(35)}
print json.dumps(results, indent=2)

Snake Game (Symbol Mode)

#symbol
⊂ py.curses as curses
⊂ py.random as random

ƒ game(stdscr)
    curses.curs_set(0)
    ∂ snake = [[10, 15], [10, 14], [10, 13]]
    ∂ dy = 0
    ∂ dx = 1
    ∂ alive = 1

    ⟳ alive == 1
        ∂ key = stdscr.getch()
        ? key == curses.KEY_UP
            ? dy ≠ 1
                dy = -1
                dx = 0
        # ... movement logic

∂ final = curses.wrapper(game)

25. All Rules Summary

1. 4-space indentation. No tabs. No braces. Indentation defines blocks.
2. No colons after if for while fn else elif struct match try catch.
3. Functions: fn name(params) -> type. NOT def.
4. Variables: let x = value for first assignment. No let for reassignment.
5. Python imports: import py.package as alias. The py. prefix is REQUIRED.
6. Strings: "text {expr}" auto-interpolates. No f"..." prefix.
7. print is a keyword: print "hello". No parentheses needed.
8. sort is a keyword: sort data. In-place. Adaptive algorithm.
9. Ranges: 0..100. Two dots. Exclusive end.
10. Lambdas: (x) => x * 2. Fat arrow, not lambda.
11. Logic: and or not. Words, not symbols.
12. Booleans: true false none. Lowercase.
13. Error handling: try/catch. NOT try/except.
14. Match: match value then pattern => action. _ for default.
15. Structs: struct Name with field: type. Methods use fn with self.
16. Comments: # comment. Hash style.
17. File extension: .sym. Always.
18. No semicolons. One statement per line.
19. Power: **. Floor div: //. Modulo: %.
20. Pipe: |>. Passes left as first arg to right function.
21. Mode declaration: #compact or #symbol on first line of file.
22. Compact: @=let ?=if !=else ~=for ~~=while >>=print <<=import <-=return f=fn
23. Symbol: =let ƒ=fn =return =for =while =import =print =!= =<= =>=
24. Symbol types: =int =float 𝔹=bool 𝕊=str

SymbolCore v0.2.0 — Complete Language Reference

Hosted on testwallah.in